diff
stringlengths
262
553k
is_single_chunk
bool
2 classes
is_single_function
bool
1 class
buggy_function
stringlengths
20
391k
fixed_function
stringlengths
0
392k
diff --git a/src/org/apache/xerces/impl/xs/XSConstraints.java b/src/org/apache/xerces/impl/xs/XSConstraints.java index a0ab6772f..28db4ed71 100644 --- a/src/org/apache/xerces/impl/xs/XSConstraints.java +++ b/src/org/apache/xerces/impl/xs/XSConstraints.java @@ -1,1441 +1,1442 @@ /* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999-2002 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.apache.org. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package org.apache.xerces.impl.xs; import org.apache.xerces.impl.dv.XSSimpleType; import org.apache.xerces.impl.dv.InvalidDatatypeValueException; import org.apache.xerces.impl.dv.ValidatedInfo; import org.apache.xerces.impl.XMLErrorReporter; import org.apache.xerces.impl.xs.models.CMBuilder; import org.apache.xerces.impl.xs.models.XSCMValidator; import org.apache.xerces.impl.xs.util.SimpleLocator; import org.apache.xerces.impl.xs.psvi.XSConstants; import org.apache.xerces.impl.xs.psvi.XSObjectList; import org.apache.xerces.impl.xs.psvi.XSTypeDefinition; import org.apache.xerces.impl.dv.ValidationContext; import org.apache.xerces.util.SymbolHash; import java.util.Vector; /** * Constaints shared by traversers and validator * * @author Sandy Gao, IBM * * @version $Id$ */ public class XSConstraints { static final int OCCURRENCE_UNKNOWN = SchemaSymbols.OCCURRENCE_UNBOUNDED-1; static final XSSimpleType STRING_TYPE = (XSSimpleType)SchemaGrammar.SG_SchemaNS.getGlobalTypeDecl(SchemaSymbols.ATTVAL_STRING); /** * check whether derived is valid derived from base, given a subset * of {restriction, extension}.B */ public static boolean checkTypeDerivationOk(XSTypeDefinition derived, XSTypeDefinition base, short block) { // if derived is anyType, then it's valid only if base is anyType too if (derived == SchemaGrammar.fAnyType) return derived == base; // if derived is anySimpleType, then it's valid only if the base // is ur-type if (derived == SchemaGrammar.fAnySimpleType) { return (base == SchemaGrammar.fAnyType || base == SchemaGrammar.fAnySimpleType); } // if derived is simple type if (derived.getTypeCategory() == XSTypeDefinition.SIMPLE_TYPE) { // if base is complex type if (base.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE) { // if base is anyType, change base to anySimpleType, // otherwise, not valid if (base == SchemaGrammar.fAnyType) base = SchemaGrammar.fAnySimpleType; else return false; } return checkSimpleDerivation((XSSimpleType)derived, (XSSimpleType)base, block); } else { return checkComplexDerivation((XSComplexTypeDecl)derived, base, block); } } /** * check whether simple type derived is valid derived from base, * given a subset of {restriction, extension}. */ public static boolean checkSimpleDerivationOk(XSSimpleType derived, XSTypeDefinition base, short block) { // if derived is anySimpleType, then it's valid only if the base // is ur-type if (derived == SchemaGrammar.fAnySimpleType) { return (base == SchemaGrammar.fAnyType || base == SchemaGrammar.fAnySimpleType); } // if base is complex type if (base.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE) { // if base is anyType, change base to anySimpleType, // otherwise, not valid if (base == SchemaGrammar.fAnyType) base = SchemaGrammar.fAnySimpleType; else return false; } return checkSimpleDerivation((XSSimpleType)derived, (XSSimpleType)base, block); } /** * check whether complex type derived is valid derived from base, * given a subset of {restriction, extension}. */ public static boolean checkComplexDerivationOk(XSComplexTypeDecl derived, XSTypeDefinition base, short block) { // if derived is anyType, then it's valid only if base is anyType too if (derived == SchemaGrammar.fAnyType) return derived == base; return checkComplexDerivation((XSComplexTypeDecl)derived, base, block); } /** * Note: this will be a private method, and it assumes that derived is not * anySimpleType, and base is not anyType. Another method will be * introduced for public use, which will call this method. */ private static boolean checkSimpleDerivation(XSSimpleType derived, XSSimpleType base, short block) { // 1 They are the same type definition. if (derived == base) return true; // 2 All of the following must be true: // 2.1 restriction is not in the subset, or in the {final} of its own {base type definition}; if ((block & XSConstants.DERIVATION_RESTRICTION) != 0 || (derived.getBaseType().getFinal() & XSConstants.DERIVATION_RESTRICTION) != 0) { return false; } // 2.2 One of the following must be true: // 2.2.1 D's base type definition is B. XSSimpleType directBase = (XSSimpleType)derived.getBaseType(); if (directBase == base) return true; // 2.2.2 D's base type definition is not the simple ur-type definition and is validly derived from B given the subset, as defined by this constraint. if (directBase != SchemaGrammar.fAnySimpleType && checkSimpleDerivation(directBase, base, block)) { return true; } // 2.2.3 D's {variety} is list or union and B is the simple ur-type definition. if ((derived.getVariety() == XSSimpleType.VARIETY_LIST || derived.getVariety() == XSSimpleType.VARIETY_UNION) && base == SchemaGrammar.fAnySimpleType) { return true; } // 2.2.4 B's {variety} is union and D is validly derived from a type definition in B's {member type definitions} given the subset, as defined by this constraint. if (base.getVariety() == XSSimpleType.VARIETY_UNION) { XSObjectList subUnionMemberDV = base.getMemberTypes(); int subUnionSize = subUnionMemberDV.getLength(); for (int i=0; i<subUnionSize; i++) { base = (XSSimpleType)subUnionMemberDV.item(i); if (checkSimpleDerivation(derived, base, block)) return true; } } return false; } /** * Note: this will be a private method, and it assumes that derived is not * anyType. Another method will be introduced for public use, * which will call this method. */ private static boolean checkComplexDerivation(XSComplexTypeDecl derived, XSTypeDefinition base, short block) { // 2.1 B and D must be the same type definition. if (derived == base) return true; // 1 If B and D are not the same type definition, then the {derivation method} of D must not be in the subset. if ((derived.fDerivedBy & block) != 0) return false; // 2 One of the following must be true: XSTypeDefinition directBase = derived.fBaseType; // 2.2 B must be D's {base type definition}. if (directBase == base) return true; // 2.3 All of the following must be true: // 2.3.1 D's {base type definition} must not be the ur-type definition. if (directBase == SchemaGrammar.fAnyType || directBase == SchemaGrammar.fAnySimpleType) { return false; } // 2.3.2 The appropriate case among the following must be true: // 2.3.2.1 If D's {base type definition} is complex, then it must be validly derived from B given the subset as defined by this constraint. if (directBase.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE) return checkComplexDerivation((XSComplexTypeDecl)directBase, base, block); // 2.3.2.2 If D's {base type definition} is simple, then it must be validly derived from B given the subset as defined in Type Derivation OK (Simple) (3.14.6). if (directBase.getTypeCategory() == XSTypeDefinition.SIMPLE_TYPE) { // if base is complex type if (base.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE) { // if base is anyType, change base to anySimpleType, // otherwise, not valid if (base == SchemaGrammar.fAnyType) base = SchemaGrammar.fAnySimpleType; else return false; } return checkSimpleDerivation((XSSimpleType)directBase, (XSSimpleType)base, block); } return false; } /** * check whether a value is a valid default for some type * returns the compiled form of the value * The parameter value could be either a String or a ValidatedInfo object */ public static Object ElementDefaultValidImmediate(XSTypeDefinition type, String value, ValidationContext context, ValidatedInfo vinfo) { XSSimpleType dv = null; // e-props-correct // For a string to be a valid default with respect to a type definition the appropriate case among the following must be true: // 1 If the type definition is a simple type definition, then the string must be valid with respect to that definition as defined by String Valid (3.14.4). if (type.getTypeCategory() == XSTypeDefinition.SIMPLE_TYPE) { dv = (XSSimpleType)type; } // 2 If the type definition is a complex type definition, then all of the following must be true: else { // 2.1 its {content type} must be a simple type definition or mixed. XSComplexTypeDecl ctype = (XSComplexTypeDecl)type; // 2.2 The appropriate case among the following must be true: // 2.2.1 If the {content type} is a simple type definition, then the string must be valid with respect to that simple type definition as defined by String Valid (3.14.4). if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_SIMPLE) { dv = ctype.fXSSimpleType; } // 2.2.2 If the {content type} is mixed, then the {content type}'s particle must be emptiable as defined by Particle Emptiable (3.9.6). else if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_MIXED) { if (!((XSParticleDecl)ctype.getParticle()).emptiable()) return null; } else { return null; } } // get the simple type declaration, and validate Object actualValue = null; if (dv == null) { // complex type with mixed. to make sure that we store correct // information in vinfo and return the correct value, we use // "string" type for validation dv = STRING_TYPE; } try { // validate the original lexical rep, and set the actual value actualValue = dv.validate(value, context, vinfo); // validate the canonical lexical rep if (vinfo != null) actualValue = dv.validate(vinfo.stringValue(), context, vinfo); } catch (InvalidDatatypeValueException ide) { return null; } return actualValue; } static void reportSchemaError(XMLErrorReporter errorReporter, SimpleLocator loc, String key, Object[] args) { if (loc != null) { errorReporter.reportError(loc, XSMessageFormatter.SCHEMA_DOMAIN, key, args, XMLErrorReporter.SEVERITY_ERROR); } else { errorReporter.reportError(XSMessageFormatter.SCHEMA_DOMAIN, key, args, XMLErrorReporter.SEVERITY_ERROR); } } /** * used to check the 3 constraints against each complex type * (should be each model group): * Unique Particle Attribution, Particle Derivation (Restriction), * Element Declrations Consistent. */ public static void fullSchemaChecking(XSGrammarBucket grammarBucket, SubstitutionGroupHandler SGHandler, CMBuilder cmBuilder, XMLErrorReporter errorReporter) { // get all grammars, and put all substitution group information // in the substitution group handler SchemaGrammar[] grammars = grammarBucket.getGrammars(); for (int i = grammars.length-1; i >= 0; i--) { SGHandler.addSubstitutionGroup(grammars[i].getSubstitutionGroups()); } XSParticleDecl fakeDerived = new XSParticleDecl(); XSParticleDecl fakeBase = new XSParticleDecl(); fakeDerived.fType = XSParticleDecl.PARTICLE_MODELGROUP; fakeBase.fType = XSParticleDecl.PARTICLE_MODELGROUP; // before worrying about complexTypes, let's get // groups redefined by restriction out of the way. for (int g = grammars.length-1; g >= 0; g--) { XSGroupDecl [] redefinedGroups = grammars[g].getRedefinedGroupDecls(); SimpleLocator [] rgLocators = grammars[g].getRGLocators(); for(int i=0; i<redefinedGroups.length; ) { XSGroupDecl derivedGrp = redefinedGroups[i++]; XSModelGroupImpl derivedMG = derivedGrp.fModelGroup; XSGroupDecl baseGrp = redefinedGroups[i++]; XSModelGroupImpl baseMG = baseGrp.fModelGroup; if(baseMG == null) { if(derivedMG != null) { // can't be a restriction! reportSchemaError(errorReporter, rgLocators[i/2-1], "src-redefine.6.2.2", new Object[]{derivedGrp.fName, "rcase-Recurse.2"}); } } else { fakeDerived.fValue = derivedMG; fakeBase.fValue = baseMG; try { particleValidRestriction(fakeDerived, SGHandler, fakeBase, SGHandler); } catch (XMLSchemaException e) { String key = e.getKey(); reportSchemaError(errorReporter, rgLocators[i/2-1], key, e.getArgs()); reportSchemaError(errorReporter, rgLocators[i/2-1], "src-redefine.6.2.2", new Object[]{derivedGrp.fName, key}); } } } } // for each complex type, check the 3 constraints. // types need to be checked XSComplexTypeDecl[] types; SimpleLocator [] ctLocators; // to hold the errors // REVISIT: do we want to report all errors? or just one? //XMLSchemaError1D errors = new XMLSchemaError1D(); // whether need to check this type again; // whether only do UPA checking boolean further, fullChecked; // if do all checkings, how many need to be checked again. int keepType; // i: grammar; j: type; k: error // for all grammars SymbolHash elemTable = new SymbolHash(); for (int i = grammars.length-1, j, k; i >= 0; i--) { // get whether to skip EDC, and types need to be checked keepType = 0; fullChecked = grammars[i].fFullChecked; types = grammars[i].getUncheckedComplexTypeDecls(); ctLocators = grammars[i].getUncheckedCTLocators(); // for each type for (j = types.length-1; j >= 0; j--) { // if we've already full-checked this grammar, then // skip the EDC constraint if (!fullChecked) { // 1. Element Decl Consistent if (types[j].fParticle!=null) { elemTable.clear(); try { checkElementDeclsConsistent(types[j], types[j].fParticle, elemTable, SGHandler); } catch (XMLSchemaException e) { reportSchemaError(errorReporter, ctLocators[j], e.getKey(), e.getArgs()); } } } // 2. Particle Derivation if (types[j].fBaseType != null && types[j].fBaseType != SchemaGrammar.fAnyType && types[j].fDerivedBy == XSConstants.DERIVATION_RESTRICTION && (types[j].fBaseType instanceof XSComplexTypeDecl)) { XSParticleDecl derivedParticle=types[j].fParticle; XSParticleDecl baseParticle= ((XSComplexTypeDecl)(types[j].fBaseType)).fParticle; if (derivedParticle==null && (!(baseParticle==null || baseParticle.emptiable()))) { reportSchemaError(errorReporter,ctLocators[j], "derivation-ok-restriction.5.2.2", new Object[]{types[j].fName}); } else if (derivedParticle!=null && baseParticle!=null) try { particleValidRestriction(types[j].fParticle, SGHandler, ((XSComplexTypeDecl)(types[j].fBaseType)).fParticle, SGHandler); } catch (XMLSchemaException e) { reportSchemaError(errorReporter, ctLocators[j], e.getKey(), e.getArgs()); reportSchemaError(errorReporter, ctLocators[j], "derivation-ok-restriction.5.3.2", new Object[]{types[j].fName}); } } // 3. UPA // get the content model and check UPA XSCMValidator cm = types[j].getContentModel(cmBuilder); further = false; if (cm != null) { try { further = cm.checkUniqueParticleAttribution(SGHandler); } catch (XMLSchemaException e) { reportSchemaError(errorReporter, ctLocators[j], e.getKey(), e.getArgs()); } } // now report all errors // REVISIT: do we want to report all errors? or just one? /*for (k = errors.getErrorCodeNum()-1; k >= 0; k--) { reportSchemaError(errorReporter, ctLocators[j], errors.getErrorCode(k), errors.getArgs(k)); }*/ // if we are doing all checkings, and this one needs further // checking, store it in the type array. if (!fullChecked && further) types[keepType++] = types[j]; // clear errors for the next type. // REVISIT: do we want to report all errors? or just one? //errors.clear(); } // we've done with the types in this grammar. if we are checking // all constraints, need to trim type array to a proper size: // only contain those need further checking. // and mark this grammar that it only needs UPA checking. if (!fullChecked) { grammars[i].setUncheckedTypeNum(keepType); grammars[i].fFullChecked = true; } } } /* Check that a given particle is a valid restriction of a base particle. */ public static void checkElementDeclsConsistent(XSComplexTypeDecl type, XSParticleDecl particle, SymbolHash elemDeclHash, SubstitutionGroupHandler sgHandler) throws XMLSchemaException { // check for elements in the tree with the same name and namespace int pType = particle.fType; if (pType == XSParticleDecl.PARTICLE_EMPTY || pType == XSParticleDecl.PARTICLE_WILDCARD) return; if (pType == XSParticleDecl.PARTICLE_ELEMENT) { XSElementDecl elem = (XSElementDecl)(particle.fValue); findElemInTable(type, elem, elemDeclHash); if (elem.fScope == XSConstants.SCOPE_GLOBAL) { // Check for subsitution groups. XSElementDecl[] subGroup = sgHandler.getSubstitutionGroup(elem); for (int i = 0; i < subGroup.length; i++) { findElemInTable(type, subGroup[i], elemDeclHash); } } return; } XSModelGroupImpl group = (XSModelGroupImpl)particle.fValue; for (int i = 0; i < group.fParticleCount; i++) checkElementDeclsConsistent(type, group.fParticles[i], elemDeclHash, sgHandler); } public static void findElemInTable(XSComplexTypeDecl type, XSElementDecl elem, SymbolHash elemDeclHash) throws XMLSchemaException { // How can we avoid this concat? LM. String name = elem.fName + "," + elem.fTargetNamespace; XSElementDecl existingElem = null; if ((existingElem = (XSElementDecl)(elemDeclHash.get(name))) == null) { // just add it in elemDeclHash.put(name, elem); } else { // If this is the same check element, we're O.K. if (elem == existingElem) return; if (elem.fType != existingElem.fType) { // Types are not the same throw new XMLSchemaException("cos-element-consistent", new Object[] {type.fName, name}); } } } /* Check that a given particle is a valid restriction of a base particle. */ private static void particleValidRestriction(XSParticleDecl dParticle, SubstitutionGroupHandler dSGHandler, XSParticleDecl bParticle, SubstitutionGroupHandler bSGHandler) throws XMLSchemaException { particleValidRestriction(dParticle, dSGHandler, bParticle, bSGHandler, true); } private static void particleValidRestriction(XSParticleDecl dParticle, SubstitutionGroupHandler dSGHandler, XSParticleDecl bParticle, SubstitutionGroupHandler bSGHandler, boolean checkWCOccurrence) throws XMLSchemaException { Vector dChildren = null; Vector bChildren = null; int dMinEffectiveTotalRange=OCCURRENCE_UNKNOWN; int dMaxEffectiveTotalRange=OCCURRENCE_UNKNOWN; // Check for empty particles. If either base or derived particle is empty, // (and the other isn't) it's an error. - if (! (dParticle.isEmpty() == bParticle.isEmpty())) { + if ((dParticle.isEmpty() && !bParticle.emptiable()) || + (!dParticle.isEmpty() && bParticle.isEmpty())) { throw new XMLSchemaException("cos-particle-restrict", null); } // // Do setup prior to invoking the Particle (Restriction) cases. // This involves: // - removing pointless occurrences for groups, and retrieving a vector of // non-pointless children // - turning top-level elements with substitution groups into CHOICE groups. // short dType = dParticle.fType; // // Handle pointless groups for the derived particle // if (dType == XSParticleDecl.PARTICLE_MODELGROUP) { dType = ((XSModelGroupImpl)dParticle.fValue).fCompositor; // Find a group, starting with this particle, with more than 1 child. There // may be none, and the particle of interest trivially becomes an element or // wildcard. XSParticleDecl dtmp = getNonUnaryGroup(dParticle); if (dtmp != dParticle) { // Particle has been replaced. Retrieve new type info. dParticle = dtmp; dType = dParticle.fType; if (dType == XSParticleDecl.PARTICLE_MODELGROUP) dType = ((XSModelGroupImpl)dParticle.fValue).fCompositor; } // Fill in a vector with the children of the particle, removing any // pointless model groups in the process. dChildren = removePointlessChildren(dParticle); } int dMinOccurs = dParticle.fMinOccurs; int dMaxOccurs = dParticle.fMaxOccurs; // // For elements which are the heads of substitution groups, treat as CHOICE // if (dSGHandler != null && dType == XSParticleDecl.PARTICLE_ELEMENT) { XSElementDecl dElement = (XSElementDecl)dParticle.fValue; if (dElement.fScope == XSConstants.SCOPE_GLOBAL) { // Check for subsitution groups. Treat any element that has a // subsitution group as a choice. Fill in the children vector with the // members of the substitution group XSElementDecl[] subGroup = dSGHandler.getSubstitutionGroup(dElement); if (subGroup.length >0 ) { // Now, set the type to be CHOICE. The "group" will have the same // occurrence information as the original particle. dType = XSModelGroupImpl.MODELGROUP_CHOICE; dMinEffectiveTotalRange = dMinOccurs; dMaxEffectiveTotalRange = dMaxOccurs; // Fill in the vector of children dChildren = new Vector(subGroup.length+1); for (int i = 0; i < subGroup.length; i++) { addElementToParticleVector(dChildren, subGroup[i]); } addElementToParticleVector(dChildren, dElement); // Set the handler to null, to indicate that we've finished handling // substitution groups for this particle. dSGHandler = null; } } } short bType = bParticle.fType; // // Handle pointless groups for the base particle // if (bType == XSParticleDecl.PARTICLE_MODELGROUP) { bType = ((XSModelGroupImpl)bParticle.fValue).fCompositor; // Find a group, starting with this particle, with more than 1 child. There // may be none, and the particle of interest trivially becomes an element or // wildcard. XSParticleDecl btmp = getNonUnaryGroup(bParticle); if (btmp != bParticle) { // Particle has been replaced. Retrieve new type info. bParticle = btmp; bType = bParticle.fType; if (bType == XSParticleDecl.PARTICLE_MODELGROUP) bType = ((XSModelGroupImpl)bParticle.fValue).fCompositor; } // Fill in a vector with the children of the particle, removing any // pointless model groups in the process. bChildren = removePointlessChildren(bParticle); } int bMinOccurs = bParticle.fMinOccurs; int bMaxOccurs = bParticle.fMaxOccurs; if (bSGHandler != null && bType == XSParticleDecl.PARTICLE_ELEMENT) { XSElementDecl bElement = (XSElementDecl)bParticle.fValue; if (bElement.fScope == XSConstants.SCOPE_GLOBAL) { // Check for subsitution groups. Treat any element that has a // subsitution group as a choice. Fill in the children vector with the // members of the substitution group XSElementDecl[] bsubGroup = bSGHandler.getSubstitutionGroup(bElement); if (bsubGroup.length >0 ) { // Now, set the type to be CHOICE bType = XSModelGroupImpl.MODELGROUP_CHOICE; bChildren = new Vector(bsubGroup.length+1); for (int i = 0; i < bsubGroup.length; i++) { addElementToParticleVector(bChildren, bsubGroup[i]); } addElementToParticleVector(bChildren, bElement); // Set the handler to null, to indicate that we've finished handling // substitution groups for this particle. bSGHandler = null; } } } // // O.K. - Figure out which particle derivation rule applies and call it // switch (dType) { case XSParticleDecl.PARTICLE_ELEMENT: { switch (bType) { // Elt:Elt NameAndTypeOK case XSParticleDecl.PARTICLE_ELEMENT: { checkNameAndTypeOK((XSElementDecl)dParticle.fValue,dMinOccurs,dMaxOccurs, (XSElementDecl)bParticle.fValue,bMinOccurs,bMaxOccurs); return; } // Elt:Any NSCompat case XSParticleDecl.PARTICLE_WILDCARD: { checkNSCompat((XSElementDecl)dParticle.fValue,dMinOccurs,dMaxOccurs, (XSWildcardDecl)bParticle.fValue,bMinOccurs,bMaxOccurs, checkWCOccurrence); return; } // Elt:All RecurseAsIfGroup case XSModelGroupImpl.MODELGROUP_CHOICE: { // Treat the element as if it were in a group of the same type // as the base Particle dChildren = new Vector(); dChildren.addElement(dParticle); checkRecurseLax(dChildren, 1, 1, dSGHandler, bChildren, bMinOccurs, bMaxOccurs, bSGHandler); return; } case XSModelGroupImpl.MODELGROUP_SEQUENCE: case XSModelGroupImpl.MODELGROUP_ALL: { // Treat the element as if it were in a group of the same type // as the base Particle dChildren = new Vector(); dChildren.addElement(dParticle); checkRecurse(dChildren, 1, 1, dSGHandler, bChildren, bMinOccurs, bMaxOccurs, bSGHandler); return; } default: { throw new XMLSchemaException("Internal-Error", new Object[]{"in particleValidRestriction"}); } } } case XSParticleDecl.PARTICLE_WILDCARD: { switch (bType) { // Any:Any NSSubset case XSParticleDecl.PARTICLE_WILDCARD: { checkNSSubset((XSWildcardDecl)dParticle.fValue, dMinOccurs, dMaxOccurs, (XSWildcardDecl)bParticle.fValue, bMinOccurs, bMaxOccurs); return; } case XSModelGroupImpl.MODELGROUP_CHOICE: case XSModelGroupImpl.MODELGROUP_SEQUENCE: case XSModelGroupImpl.MODELGROUP_ALL: case XSParticleDecl.PARTICLE_ELEMENT: { throw new XMLSchemaException("cos-particle-restrict.2", new Object[]{"any:choice,sequence,all,elt"}); } default: { throw new XMLSchemaException("Internal-Error", new Object[]{"in particleValidRestriction"}); } } } case XSModelGroupImpl.MODELGROUP_ALL: { switch (bType) { // All:Any NSRecurseCheckCardinality case XSParticleDecl.PARTICLE_WILDCARD: { if (dMinEffectiveTotalRange == OCCURRENCE_UNKNOWN) dMinEffectiveTotalRange = dParticle.minEffectiveTotalRange(); if (dMaxEffectiveTotalRange == OCCURRENCE_UNKNOWN) dMaxEffectiveTotalRange = dParticle.maxEffectiveTotalRange(); checkNSRecurseCheckCardinality(dChildren, dMinEffectiveTotalRange, dMaxEffectiveTotalRange, dSGHandler, bParticle,bMinOccurs,bMaxOccurs, checkWCOccurrence); return; } case XSModelGroupImpl.MODELGROUP_ALL: { checkRecurse(dChildren, dMinOccurs, dMaxOccurs, dSGHandler, bChildren, bMinOccurs, bMaxOccurs, bSGHandler); return; } case XSModelGroupImpl.MODELGROUP_CHOICE: case XSModelGroupImpl.MODELGROUP_SEQUENCE: case XSParticleDecl.PARTICLE_ELEMENT: { throw new XMLSchemaException("cos-particle-restrict.2", new Object[]{"all:choice,sequence,elt"}); } default: { throw new XMLSchemaException("Internal-Error", new Object[]{"in particleValidRestriction"}); } } } case XSModelGroupImpl.MODELGROUP_CHOICE: { switch (bType) { // Choice:Any NSRecurseCheckCardinality case XSParticleDecl.PARTICLE_WILDCARD: { if (dMinEffectiveTotalRange == OCCURRENCE_UNKNOWN) dMinEffectiveTotalRange = dParticle.minEffectiveTotalRange(); if (dMaxEffectiveTotalRange == OCCURRENCE_UNKNOWN) dMaxEffectiveTotalRange = dParticle.maxEffectiveTotalRange(); checkNSRecurseCheckCardinality(dChildren, dMinEffectiveTotalRange, dMaxEffectiveTotalRange, dSGHandler, bParticle,bMinOccurs,bMaxOccurs, checkWCOccurrence); return; } case XSModelGroupImpl.MODELGROUP_CHOICE: { checkRecurseLax(dChildren, dMinOccurs, dMaxOccurs, dSGHandler, bChildren, bMinOccurs, bMaxOccurs, bSGHandler); return; } case XSModelGroupImpl.MODELGROUP_ALL: case XSModelGroupImpl.MODELGROUP_SEQUENCE: case XSParticleDecl.PARTICLE_ELEMENT: { throw new XMLSchemaException("cos-particle-restrict.2", new Object[]{"choice:all,sequence,elt"}); } default: { throw new XMLSchemaException("Internal-Error", new Object[]{"in particleValidRestriction"}); } } } case XSModelGroupImpl.MODELGROUP_SEQUENCE: { switch (bType) { // Choice:Any NSRecurseCheckCardinality case XSParticleDecl.PARTICLE_WILDCARD: { if (dMinEffectiveTotalRange == OCCURRENCE_UNKNOWN) dMinEffectiveTotalRange = dParticle.minEffectiveTotalRange(); if (dMaxEffectiveTotalRange == OCCURRENCE_UNKNOWN) dMaxEffectiveTotalRange = dParticle.maxEffectiveTotalRange(); checkNSRecurseCheckCardinality(dChildren, dMinEffectiveTotalRange, dMaxEffectiveTotalRange, dSGHandler, bParticle,bMinOccurs,bMaxOccurs, checkWCOccurrence); return; } case XSModelGroupImpl.MODELGROUP_ALL: { checkRecurseUnordered(dChildren, dMinOccurs, dMaxOccurs, dSGHandler, bChildren, bMinOccurs, bMaxOccurs, bSGHandler); return; } case XSModelGroupImpl.MODELGROUP_SEQUENCE: { checkRecurse(dChildren, dMinOccurs, dMaxOccurs, dSGHandler, bChildren, bMinOccurs, bMaxOccurs, bSGHandler); return; } case XSModelGroupImpl.MODELGROUP_CHOICE: { int min1 = dMinOccurs * dChildren.size(); int max1 = (dMaxOccurs == SchemaSymbols.OCCURRENCE_UNBOUNDED)? dMaxOccurs : dMaxOccurs * dChildren.size(); checkMapAndSum(dChildren, min1, max1, dSGHandler, bChildren, bMinOccurs, bMaxOccurs, bSGHandler); return; } case XSParticleDecl.PARTICLE_ELEMENT: { throw new XMLSchemaException("cos-particle-restrict.2", new Object[]{"seq:elt"}); } default: { throw new XMLSchemaException("Internal-Error", new Object[]{"in particleValidRestriction"}); } } } } } private static void addElementToParticleVector (Vector v, XSElementDecl d) { XSParticleDecl p = new XSParticleDecl(); p.fValue = d; p.fType = XSParticleDecl.PARTICLE_ELEMENT; v.addElement(p); } private static XSParticleDecl getNonUnaryGroup(XSParticleDecl p) { if (p.fType == XSParticleDecl.PARTICLE_ELEMENT || p.fType == XSParticleDecl.PARTICLE_WILDCARD) return p; if (p.fMinOccurs==1 && p.fMaxOccurs==1 && p.fValue!=null && ((XSModelGroupImpl)p.fValue).fParticleCount == 1) return getNonUnaryGroup(((XSModelGroupImpl)p.fValue).fParticles[0]); else return p; } private static Vector removePointlessChildren(XSParticleDecl p) { if (p.fType == XSParticleDecl.PARTICLE_ELEMENT || p.fType == XSParticleDecl.PARTICLE_WILDCARD || p.fType == XSParticleDecl.PARTICLE_EMPTY) return null; Vector children = new Vector(); XSModelGroupImpl group = (XSModelGroupImpl)p.fValue; for (int i = 0; i < group.fParticleCount; i++) gatherChildren(group.fCompositor, group.fParticles[i], children); return children; } private static void gatherChildren(int parentType, XSParticleDecl p, Vector children) { int min = p.fMinOccurs; int max = p.fMaxOccurs; int type = p.fType; if (type == XSParticleDecl.PARTICLE_MODELGROUP) type = ((XSModelGroupImpl)p.fValue).fCompositor; if (type == XSParticleDecl.PARTICLE_EMPTY) return; if (type == XSParticleDecl.PARTICLE_ELEMENT || type== XSParticleDecl.PARTICLE_WILDCARD) { children.addElement(p); return; } if (! (min==1 && max==1)) { children.addElement(p); } else if (parentType == type) { XSModelGroupImpl group = (XSModelGroupImpl)p.fValue; for (int i = 0; i < group.fParticleCount; i++) gatherChildren(type, group.fParticles[i], children); } else if (!p.isEmpty()) { children.addElement(p); } } private static void checkNameAndTypeOK(XSElementDecl dElement, int dMin, int dMax, XSElementDecl bElement, int bMin, int bMax) throws XMLSchemaException { // // Check that the names are the same // if (dElement.fName != bElement.fName || dElement.fTargetNamespace != bElement.fTargetNamespace) { throw new XMLSchemaException( "rcase-NameAndTypeOK.1",new Object[]{dElement.fName, dElement.fTargetNamespace, bElement.fName, bElement.fTargetNamespace}); } // // Check nillable // if (! (bElement.getNillable() || !dElement.getNillable())) { throw new XMLSchemaException("rcase-NameAndTypeOK.2", new Object[]{dElement.fName}); } // // Check occurrence range // if (!checkOccurrenceRange(dMin, dMax, bMin, bMax)) { throw new XMLSchemaException("rcase-NameAndTypeOK.3", new Object[]{dElement.fName}); } // // Check for consistent fixed values // if (bElement.getConstraintType() == XSConstants.VC_FIXED) { // derived one has to have a fixed value if (dElement.getConstraintType() != XSConstants.VC_FIXED) { throw new XMLSchemaException("rcase-NameAndTypeOK.4", new Object[]{dElement.fName}); } // get simple type boolean isSimple = false; if (dElement.fType.getTypeCategory() == XSTypeDefinition.SIMPLE_TYPE || ((XSComplexTypeDecl)dElement.fType).fContentType == XSComplexTypeDecl.CONTENTTYPE_SIMPLE) { isSimple = true; } // if there is no simple type, then compare based on string if (!isSimple && !bElement.fDefault.normalizedValue.equals(dElement.fDefault.normalizedValue) || isSimple && !bElement.fDefault.actualValue.equals(dElement.fDefault.actualValue)) { throw new XMLSchemaException("rcase-NameAndTypeOK.4", new Object[]{dElement.fName}); } } // // Check identity constraints // checkIDConstraintRestriction(dElement, bElement); // // Check for disallowed substitutions // int blockSet1 = dElement.fBlock; int blockSet2 = bElement.fBlock; if (((blockSet1 & blockSet2)!=blockSet2) || (blockSet1==XSConstants.DERIVATION_NONE && blockSet2!=XSConstants.DERIVATION_NONE)) throw new XMLSchemaException("rcase-NameAndTypeOK.6", new Object[]{dElement.fName}); // // Check that the derived element's type is derived from the base's. // if (!checkTypeDerivationOk(dElement.fType, bElement.fType, (short)(XSConstants.DERIVATION_EXTENSION|XSConstants.DERIVATION_LIST|XSConstants.DERIVATION_UNION))) { throw new XMLSchemaException("rcase-NameAndTypeOK.7", new Object[]{dElement.fName}); } } private static void checkIDConstraintRestriction(XSElementDecl derivedElemDecl, XSElementDecl baseElemDecl) throws XMLSchemaException { // TODO } // checkIDConstraintRestriction private static 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 static void checkNSCompat(XSElementDecl elem, int min1, int max1, XSWildcardDecl wildcard, int min2, int max2, boolean checkWCOccurrence) throws XMLSchemaException { // check Occurrence ranges if (checkWCOccurrence && !checkOccurrenceRange(min1,max1,min2,max2)) { throw new XMLSchemaException("rcase-NSCompat.2", new Object[]{elem.fName}); } // check wildcard allows namespace of element if (!wildcard.allowNamespace(elem.fTargetNamespace)) { throw new XMLSchemaException("rcase-NSCompat.1", new Object[]{elem.fName,elem.fTargetNamespace}); } } private static void checkNSSubset(XSWildcardDecl dWildcard, int min1, int max1, XSWildcardDecl bWildcard, int min2, int max2) throws XMLSchemaException { // check Occurrence ranges if (!checkOccurrenceRange(min1,max1,min2,max2)) { throw new XMLSchemaException("rcase-NSSubset.2",null); } // check wildcard subset if (!dWildcard.isSubsetOf(bWildcard)) { throw new XMLSchemaException("rcase-NSSubset.1",null); } if (dWildcard.weakerProcessContents(bWildcard)) { throw new XMLSchemaException("rcase-NSSubset.3",null); } } private static void checkNSRecurseCheckCardinality(Vector children, int min1, int max1, SubstitutionGroupHandler dSGHandler, XSParticleDecl wildcard, int min2, int max2, boolean checkWCOccurrence) throws XMLSchemaException { // check Occurrence ranges if (checkWCOccurrence && !checkOccurrenceRange(min1,max1,min2,max2)) { throw new XMLSchemaException("rcase-NSRecurseCheckCardinality.2", null); } // Check that each member of the group is a valid restriction of the wildcard int count = children.size(); try { for (int i = 0; i < count; i++) { XSParticleDecl particle1 = (XSParticleDecl)children.elementAt(i); particleValidRestriction(particle1, dSGHandler, wildcard, null, false); } } catch (XMLSchemaException e) { throw new XMLSchemaException("rcase-NSRecurseCheckCardinality.1", null); } } private static void checkRecurse(Vector dChildren, int min1, int max1, SubstitutionGroupHandler dSGHandler, Vector bChildren, int min2, int max2, SubstitutionGroupHandler bSGHandler) throws XMLSchemaException { // check Occurrence ranges if (!checkOccurrenceRange(min1,max1,min2,max2)) { throw new XMLSchemaException("rcase-Recurse.1", null); } int count1= dChildren.size(); int count2= bChildren.size(); int current = 0; label: for (int i = 0; i<count1; i++) { XSParticleDecl particle1 = (XSParticleDecl)dChildren.elementAt(i); for (int j = current; j<count2; j++) { XSParticleDecl particle2 = (XSParticleDecl)bChildren.elementAt(j); current +=1; try { particleValidRestriction(particle1, dSGHandler, particle2, bSGHandler); continue label; } catch (XMLSchemaException e) { if (!particle2.emptiable()) throw new XMLSchemaException("rcase-Recurse.2", null); } } throw new XMLSchemaException("rcase-Recurse.2", null); } // Now, see if there are some elements in the base we didn't match up for (int j=current; j < count2; j++) { XSParticleDecl particle2 = (XSParticleDecl)bChildren.elementAt(j); if (!particle2.emptiable()) { throw new XMLSchemaException("rcase-Recurse.2", null); } } } private static void checkRecurseUnordered(Vector dChildren, int min1, int max1, SubstitutionGroupHandler dSGHandler, Vector bChildren, int min2, int max2, SubstitutionGroupHandler bSGHandler) throws XMLSchemaException { // check Occurrence ranges if (!checkOccurrenceRange(min1,max1,min2,max2)) { throw new XMLSchemaException("rcase-RecurseUnordered.1", null); } int count1= dChildren.size(); int count2 = bChildren.size(); boolean foundIt[] = new boolean[count2]; label: for (int i = 0; i<count1; i++) { XSParticleDecl particle1 = (XSParticleDecl)dChildren.elementAt(i); for (int j = 0; j<count2; j++) { XSParticleDecl particle2 = (XSParticleDecl)bChildren.elementAt(j); try { particleValidRestriction(particle1, dSGHandler, particle2, bSGHandler); if (foundIt[j]) throw new XMLSchemaException("rcase-RecurseUnordered.2", null); else foundIt[j]=true; continue label; } catch (XMLSchemaException e) { } } // didn't find a match. Detect an error throw new XMLSchemaException("rcase-RecurseUnordered.2", null); } // Now, see if there are some elements in the base we didn't match up for (int j=0; j < count2; j++) { XSParticleDecl particle2 = (XSParticleDecl)bChildren.elementAt(j); if (!foundIt[j] && !particle2.emptiable()) { throw new XMLSchemaException("rcase-RecurseUnordered.2", null); } } } private static void checkRecurseLax(Vector dChildren, int min1, int max1, SubstitutionGroupHandler dSGHandler, Vector bChildren, int min2, int max2, SubstitutionGroupHandler bSGHandler) throws XMLSchemaException { // check Occurrence ranges if (!checkOccurrenceRange(min1,max1,min2,max2)) { throw new XMLSchemaException("rcase-RecurseLax.1", null); } int count1= dChildren.size(); int count2 = bChildren.size(); int current = 0; label: for (int i = 0; i<count1; i++) { XSParticleDecl particle1 = (XSParticleDecl)dChildren.elementAt(i); for (int j = current; j<count2; j++) { XSParticleDecl particle2 = (XSParticleDecl)bChildren.elementAt(j); current +=1; try { particleValidRestriction(particle1, dSGHandler, particle2, bSGHandler); continue label; } catch (XMLSchemaException e) { } } // didn't find a match. Detect an error throw new XMLSchemaException("rcase-RecurseLax.2", null); } } private static void checkMapAndSum(Vector dChildren, int min1, int max1, SubstitutionGroupHandler dSGHandler, Vector bChildren, int min2, int max2, SubstitutionGroupHandler bSGHandler) throws XMLSchemaException { // See if the sequence group is a valid restriction of the choice // Here is an example of a valid restriction: // <choice minOccurs="2"> // <a/> // <b/> // <c/> // </choice> // // <sequence> // <b/> // <a/> // </sequence> // check Occurrence ranges if (!checkOccurrenceRange(min1,max1,min2,max2)) { throw new XMLSchemaException("rcase-MapAndSum.2", null); } int count1 = dChildren.size(); int count2 = bChildren.size(); label: for (int i = 0; i<count1; i++) { XSParticleDecl particle1 = (XSParticleDecl)dChildren.elementAt(i); for (int j = 0; j<count2; j++) { XSParticleDecl particle2 = (XSParticleDecl)bChildren.elementAt(j); try { particleValidRestriction(particle1, dSGHandler, particle2, bSGHandler); continue label; } catch (XMLSchemaException e) { } } // didn't find a match. Detect an error throw new XMLSchemaException("rcase-MapAndSum.1", null); } } // to check whether two element overlap, as defined in constraint UPA public static boolean overlapUPA(XSElementDecl element1, XSElementDecl element2, SubstitutionGroupHandler sgHandler) { // if the two element have the same name and namespace, if (element1.fName == element2.fName && element1.fTargetNamespace == element2.fTargetNamespace) { return true; } // or if there is an element decl in element1's substitution group, // who has the same name/namespace with element2 XSElementDecl[] subGroup = sgHandler.getSubstitutionGroup(element1); for (int i = subGroup.length-1; i >= 0; i--) { if (subGroup[i].fName == element2.fName && subGroup[i].fTargetNamespace == element2.fTargetNamespace) { return true; } } // or if there is an element decl in element2's substitution group, // who has the same name/namespace with element1 subGroup = sgHandler.getSubstitutionGroup(element2); for (int i = subGroup.length-1; i >= 0; i--) { if (subGroup[i].fName == element1.fName && subGroup[i].fTargetNamespace == element1.fTargetNamespace) { return true; } } return false; } // to check whether an element overlaps with a wildcard, // as defined in constraint UPA public static boolean overlapUPA(XSElementDecl element, XSWildcardDecl wildcard, SubstitutionGroupHandler sgHandler) { // if the wildcard allows the element if (wildcard.allowNamespace(element.fTargetNamespace)) return true; // or if the wildcard allows any element in the substitution group XSElementDecl[] subGroup = sgHandler.getSubstitutionGroup(element); for (int i = subGroup.length-1; i >= 0; i--) { if (wildcard.allowNamespace(subGroup[i].fTargetNamespace)) return true; } return false; } public static boolean overlapUPA(XSWildcardDecl wildcard1, XSWildcardDecl wildcard2) { // if the intersection of the two wildcard is not empty list XSWildcardDecl intersect = wildcard1.performIntersectionWith(wildcard2, wildcard1.fProcessContents); if (intersect == null || intersect.fType != XSWildcardDecl.NSCONSTRAINT_LIST || intersect.fNamespaceList.length != 0) { return true; } return false; } // call one of the above methods according to the type of decls public static boolean overlapUPA(Object decl1, Object decl2, SubstitutionGroupHandler sgHandler) { if (decl1 instanceof XSElementDecl) { if (decl2 instanceof XSElementDecl) { return overlapUPA((XSElementDecl)decl1, (XSElementDecl)decl2, sgHandler); } else { return overlapUPA((XSElementDecl)decl1, (XSWildcardDecl)decl2, sgHandler); } } else { if (decl2 instanceof XSElementDecl) { return overlapUPA((XSElementDecl)decl2, (XSWildcardDecl)decl1, sgHandler); } else { return overlapUPA((XSWildcardDecl)decl1, (XSWildcardDecl)decl2); } } } } // class XSContraints
true
true
private static void particleValidRestriction(XSParticleDecl dParticle, SubstitutionGroupHandler dSGHandler, XSParticleDecl bParticle, SubstitutionGroupHandler bSGHandler, boolean checkWCOccurrence) throws XMLSchemaException { Vector dChildren = null; Vector bChildren = null; int dMinEffectiveTotalRange=OCCURRENCE_UNKNOWN; int dMaxEffectiveTotalRange=OCCURRENCE_UNKNOWN; // Check for empty particles. If either base or derived particle is empty, // (and the other isn't) it's an error. if (! (dParticle.isEmpty() == bParticle.isEmpty())) { throw new XMLSchemaException("cos-particle-restrict", null); } // // Do setup prior to invoking the Particle (Restriction) cases. // This involves: // - removing pointless occurrences for groups, and retrieving a vector of // non-pointless children // - turning top-level elements with substitution groups into CHOICE groups. // short dType = dParticle.fType; // // Handle pointless groups for the derived particle // if (dType == XSParticleDecl.PARTICLE_MODELGROUP) { dType = ((XSModelGroupImpl)dParticle.fValue).fCompositor; // Find a group, starting with this particle, with more than 1 child. There // may be none, and the particle of interest trivially becomes an element or // wildcard. XSParticleDecl dtmp = getNonUnaryGroup(dParticle); if (dtmp != dParticle) { // Particle has been replaced. Retrieve new type info. dParticle = dtmp; dType = dParticle.fType; if (dType == XSParticleDecl.PARTICLE_MODELGROUP) dType = ((XSModelGroupImpl)dParticle.fValue).fCompositor; } // Fill in a vector with the children of the particle, removing any // pointless model groups in the process. dChildren = removePointlessChildren(dParticle); } int dMinOccurs = dParticle.fMinOccurs; int dMaxOccurs = dParticle.fMaxOccurs; // // For elements which are the heads of substitution groups, treat as CHOICE // if (dSGHandler != null && dType == XSParticleDecl.PARTICLE_ELEMENT) { XSElementDecl dElement = (XSElementDecl)dParticle.fValue; if (dElement.fScope == XSConstants.SCOPE_GLOBAL) { // Check for subsitution groups. Treat any element that has a // subsitution group as a choice. Fill in the children vector with the // members of the substitution group XSElementDecl[] subGroup = dSGHandler.getSubstitutionGroup(dElement); if (subGroup.length >0 ) { // Now, set the type to be CHOICE. The "group" will have the same // occurrence information as the original particle. dType = XSModelGroupImpl.MODELGROUP_CHOICE; dMinEffectiveTotalRange = dMinOccurs; dMaxEffectiveTotalRange = dMaxOccurs; // Fill in the vector of children dChildren = new Vector(subGroup.length+1); for (int i = 0; i < subGroup.length; i++) { addElementToParticleVector(dChildren, subGroup[i]); } addElementToParticleVector(dChildren, dElement); // Set the handler to null, to indicate that we've finished handling // substitution groups for this particle. dSGHandler = null; } } } short bType = bParticle.fType; // // Handle pointless groups for the base particle // if (bType == XSParticleDecl.PARTICLE_MODELGROUP) { bType = ((XSModelGroupImpl)bParticle.fValue).fCompositor; // Find a group, starting with this particle, with more than 1 child. There // may be none, and the particle of interest trivially becomes an element or // wildcard. XSParticleDecl btmp = getNonUnaryGroup(bParticle); if (btmp != bParticle) { // Particle has been replaced. Retrieve new type info. bParticle = btmp; bType = bParticle.fType; if (bType == XSParticleDecl.PARTICLE_MODELGROUP) bType = ((XSModelGroupImpl)bParticle.fValue).fCompositor; } // Fill in a vector with the children of the particle, removing any // pointless model groups in the process. bChildren = removePointlessChildren(bParticle); } int bMinOccurs = bParticle.fMinOccurs; int bMaxOccurs = bParticle.fMaxOccurs; if (bSGHandler != null && bType == XSParticleDecl.PARTICLE_ELEMENT) { XSElementDecl bElement = (XSElementDecl)bParticle.fValue; if (bElement.fScope == XSConstants.SCOPE_GLOBAL) { // Check for subsitution groups. Treat any element that has a // subsitution group as a choice. Fill in the children vector with the // members of the substitution group XSElementDecl[] bsubGroup = bSGHandler.getSubstitutionGroup(bElement); if (bsubGroup.length >0 ) { // Now, set the type to be CHOICE bType = XSModelGroupImpl.MODELGROUP_CHOICE; bChildren = new Vector(bsubGroup.length+1); for (int i = 0; i < bsubGroup.length; i++) { addElementToParticleVector(bChildren, bsubGroup[i]); } addElementToParticleVector(bChildren, bElement); // Set the handler to null, to indicate that we've finished handling // substitution groups for this particle. bSGHandler = null; } } } // // O.K. - Figure out which particle derivation rule applies and call it // switch (dType) { case XSParticleDecl.PARTICLE_ELEMENT: { switch (bType) { // Elt:Elt NameAndTypeOK case XSParticleDecl.PARTICLE_ELEMENT: { checkNameAndTypeOK((XSElementDecl)dParticle.fValue,dMinOccurs,dMaxOccurs, (XSElementDecl)bParticle.fValue,bMinOccurs,bMaxOccurs); return; } // Elt:Any NSCompat case XSParticleDecl.PARTICLE_WILDCARD: { checkNSCompat((XSElementDecl)dParticle.fValue,dMinOccurs,dMaxOccurs, (XSWildcardDecl)bParticle.fValue,bMinOccurs,bMaxOccurs, checkWCOccurrence); return; } // Elt:All RecurseAsIfGroup case XSModelGroupImpl.MODELGROUP_CHOICE: { // Treat the element as if it were in a group of the same type // as the base Particle dChildren = new Vector(); dChildren.addElement(dParticle); checkRecurseLax(dChildren, 1, 1, dSGHandler, bChildren, bMinOccurs, bMaxOccurs, bSGHandler); return; } case XSModelGroupImpl.MODELGROUP_SEQUENCE: case XSModelGroupImpl.MODELGROUP_ALL: { // Treat the element as if it were in a group of the same type // as the base Particle dChildren = new Vector(); dChildren.addElement(dParticle); checkRecurse(dChildren, 1, 1, dSGHandler, bChildren, bMinOccurs, bMaxOccurs, bSGHandler); return; } default: { throw new XMLSchemaException("Internal-Error", new Object[]{"in particleValidRestriction"}); } } } case XSParticleDecl.PARTICLE_WILDCARD: { switch (bType) { // Any:Any NSSubset case XSParticleDecl.PARTICLE_WILDCARD: { checkNSSubset((XSWildcardDecl)dParticle.fValue, dMinOccurs, dMaxOccurs, (XSWildcardDecl)bParticle.fValue, bMinOccurs, bMaxOccurs); return; } case XSModelGroupImpl.MODELGROUP_CHOICE: case XSModelGroupImpl.MODELGROUP_SEQUENCE: case XSModelGroupImpl.MODELGROUP_ALL: case XSParticleDecl.PARTICLE_ELEMENT: { throw new XMLSchemaException("cos-particle-restrict.2", new Object[]{"any:choice,sequence,all,elt"}); } default: { throw new XMLSchemaException("Internal-Error", new Object[]{"in particleValidRestriction"}); } } } case XSModelGroupImpl.MODELGROUP_ALL: { switch (bType) { // All:Any NSRecurseCheckCardinality case XSParticleDecl.PARTICLE_WILDCARD: { if (dMinEffectiveTotalRange == OCCURRENCE_UNKNOWN) dMinEffectiveTotalRange = dParticle.minEffectiveTotalRange(); if (dMaxEffectiveTotalRange == OCCURRENCE_UNKNOWN) dMaxEffectiveTotalRange = dParticle.maxEffectiveTotalRange(); checkNSRecurseCheckCardinality(dChildren, dMinEffectiveTotalRange, dMaxEffectiveTotalRange, dSGHandler, bParticle,bMinOccurs,bMaxOccurs, checkWCOccurrence); return; } case XSModelGroupImpl.MODELGROUP_ALL: { checkRecurse(dChildren, dMinOccurs, dMaxOccurs, dSGHandler, bChildren, bMinOccurs, bMaxOccurs, bSGHandler); return; } case XSModelGroupImpl.MODELGROUP_CHOICE: case XSModelGroupImpl.MODELGROUP_SEQUENCE: case XSParticleDecl.PARTICLE_ELEMENT: { throw new XMLSchemaException("cos-particle-restrict.2", new Object[]{"all:choice,sequence,elt"}); } default: { throw new XMLSchemaException("Internal-Error", new Object[]{"in particleValidRestriction"}); } } } case XSModelGroupImpl.MODELGROUP_CHOICE: { switch (bType) { // Choice:Any NSRecurseCheckCardinality case XSParticleDecl.PARTICLE_WILDCARD: { if (dMinEffectiveTotalRange == OCCURRENCE_UNKNOWN) dMinEffectiveTotalRange = dParticle.minEffectiveTotalRange(); if (dMaxEffectiveTotalRange == OCCURRENCE_UNKNOWN) dMaxEffectiveTotalRange = dParticle.maxEffectiveTotalRange(); checkNSRecurseCheckCardinality(dChildren, dMinEffectiveTotalRange, dMaxEffectiveTotalRange, dSGHandler, bParticle,bMinOccurs,bMaxOccurs, checkWCOccurrence); return; } case XSModelGroupImpl.MODELGROUP_CHOICE: { checkRecurseLax(dChildren, dMinOccurs, dMaxOccurs, dSGHandler, bChildren, bMinOccurs, bMaxOccurs, bSGHandler); return; } case XSModelGroupImpl.MODELGROUP_ALL: case XSModelGroupImpl.MODELGROUP_SEQUENCE: case XSParticleDecl.PARTICLE_ELEMENT: { throw new XMLSchemaException("cos-particle-restrict.2", new Object[]{"choice:all,sequence,elt"}); } default: { throw new XMLSchemaException("Internal-Error", new Object[]{"in particleValidRestriction"}); } } } case XSModelGroupImpl.MODELGROUP_SEQUENCE: { switch (bType) { // Choice:Any NSRecurseCheckCardinality case XSParticleDecl.PARTICLE_WILDCARD: { if (dMinEffectiveTotalRange == OCCURRENCE_UNKNOWN) dMinEffectiveTotalRange = dParticle.minEffectiveTotalRange(); if (dMaxEffectiveTotalRange == OCCURRENCE_UNKNOWN) dMaxEffectiveTotalRange = dParticle.maxEffectiveTotalRange(); checkNSRecurseCheckCardinality(dChildren, dMinEffectiveTotalRange, dMaxEffectiveTotalRange, dSGHandler, bParticle,bMinOccurs,bMaxOccurs, checkWCOccurrence); return; } case XSModelGroupImpl.MODELGROUP_ALL: { checkRecurseUnordered(dChildren, dMinOccurs, dMaxOccurs, dSGHandler, bChildren, bMinOccurs, bMaxOccurs, bSGHandler); return; } case XSModelGroupImpl.MODELGROUP_SEQUENCE: { checkRecurse(dChildren, dMinOccurs, dMaxOccurs, dSGHandler, bChildren, bMinOccurs, bMaxOccurs, bSGHandler); return; } case XSModelGroupImpl.MODELGROUP_CHOICE: { int min1 = dMinOccurs * dChildren.size(); int max1 = (dMaxOccurs == SchemaSymbols.OCCURRENCE_UNBOUNDED)? dMaxOccurs : dMaxOccurs * dChildren.size(); checkMapAndSum(dChildren, min1, max1, dSGHandler, bChildren, bMinOccurs, bMaxOccurs, bSGHandler); return; } case XSParticleDecl.PARTICLE_ELEMENT: { throw new XMLSchemaException("cos-particle-restrict.2", new Object[]{"seq:elt"}); } default: { throw new XMLSchemaException("Internal-Error", new Object[]{"in particleValidRestriction"}); } } } } }
private static void particleValidRestriction(XSParticleDecl dParticle, SubstitutionGroupHandler dSGHandler, XSParticleDecl bParticle, SubstitutionGroupHandler bSGHandler, boolean checkWCOccurrence) throws XMLSchemaException { Vector dChildren = null; Vector bChildren = null; int dMinEffectiveTotalRange=OCCURRENCE_UNKNOWN; int dMaxEffectiveTotalRange=OCCURRENCE_UNKNOWN; // Check for empty particles. If either base or derived particle is empty, // (and the other isn't) it's an error. if ((dParticle.isEmpty() && !bParticle.emptiable()) || (!dParticle.isEmpty() && bParticle.isEmpty())) { throw new XMLSchemaException("cos-particle-restrict", null); } // // Do setup prior to invoking the Particle (Restriction) cases. // This involves: // - removing pointless occurrences for groups, and retrieving a vector of // non-pointless children // - turning top-level elements with substitution groups into CHOICE groups. // short dType = dParticle.fType; // // Handle pointless groups for the derived particle // if (dType == XSParticleDecl.PARTICLE_MODELGROUP) { dType = ((XSModelGroupImpl)dParticle.fValue).fCompositor; // Find a group, starting with this particle, with more than 1 child. There // may be none, and the particle of interest trivially becomes an element or // wildcard. XSParticleDecl dtmp = getNonUnaryGroup(dParticle); if (dtmp != dParticle) { // Particle has been replaced. Retrieve new type info. dParticle = dtmp; dType = dParticle.fType; if (dType == XSParticleDecl.PARTICLE_MODELGROUP) dType = ((XSModelGroupImpl)dParticle.fValue).fCompositor; } // Fill in a vector with the children of the particle, removing any // pointless model groups in the process. dChildren = removePointlessChildren(dParticle); } int dMinOccurs = dParticle.fMinOccurs; int dMaxOccurs = dParticle.fMaxOccurs; // // For elements which are the heads of substitution groups, treat as CHOICE // if (dSGHandler != null && dType == XSParticleDecl.PARTICLE_ELEMENT) { XSElementDecl dElement = (XSElementDecl)dParticle.fValue; if (dElement.fScope == XSConstants.SCOPE_GLOBAL) { // Check for subsitution groups. Treat any element that has a // subsitution group as a choice. Fill in the children vector with the // members of the substitution group XSElementDecl[] subGroup = dSGHandler.getSubstitutionGroup(dElement); if (subGroup.length >0 ) { // Now, set the type to be CHOICE. The "group" will have the same // occurrence information as the original particle. dType = XSModelGroupImpl.MODELGROUP_CHOICE; dMinEffectiveTotalRange = dMinOccurs; dMaxEffectiveTotalRange = dMaxOccurs; // Fill in the vector of children dChildren = new Vector(subGroup.length+1); for (int i = 0; i < subGroup.length; i++) { addElementToParticleVector(dChildren, subGroup[i]); } addElementToParticleVector(dChildren, dElement); // Set the handler to null, to indicate that we've finished handling // substitution groups for this particle. dSGHandler = null; } } } short bType = bParticle.fType; // // Handle pointless groups for the base particle // if (bType == XSParticleDecl.PARTICLE_MODELGROUP) { bType = ((XSModelGroupImpl)bParticle.fValue).fCompositor; // Find a group, starting with this particle, with more than 1 child. There // may be none, and the particle of interest trivially becomes an element or // wildcard. XSParticleDecl btmp = getNonUnaryGroup(bParticle); if (btmp != bParticle) { // Particle has been replaced. Retrieve new type info. bParticle = btmp; bType = bParticle.fType; if (bType == XSParticleDecl.PARTICLE_MODELGROUP) bType = ((XSModelGroupImpl)bParticle.fValue).fCompositor; } // Fill in a vector with the children of the particle, removing any // pointless model groups in the process. bChildren = removePointlessChildren(bParticle); } int bMinOccurs = bParticle.fMinOccurs; int bMaxOccurs = bParticle.fMaxOccurs; if (bSGHandler != null && bType == XSParticleDecl.PARTICLE_ELEMENT) { XSElementDecl bElement = (XSElementDecl)bParticle.fValue; if (bElement.fScope == XSConstants.SCOPE_GLOBAL) { // Check for subsitution groups. Treat any element that has a // subsitution group as a choice. Fill in the children vector with the // members of the substitution group XSElementDecl[] bsubGroup = bSGHandler.getSubstitutionGroup(bElement); if (bsubGroup.length >0 ) { // Now, set the type to be CHOICE bType = XSModelGroupImpl.MODELGROUP_CHOICE; bChildren = new Vector(bsubGroup.length+1); for (int i = 0; i < bsubGroup.length; i++) { addElementToParticleVector(bChildren, bsubGroup[i]); } addElementToParticleVector(bChildren, bElement); // Set the handler to null, to indicate that we've finished handling // substitution groups for this particle. bSGHandler = null; } } } // // O.K. - Figure out which particle derivation rule applies and call it // switch (dType) { case XSParticleDecl.PARTICLE_ELEMENT: { switch (bType) { // Elt:Elt NameAndTypeOK case XSParticleDecl.PARTICLE_ELEMENT: { checkNameAndTypeOK((XSElementDecl)dParticle.fValue,dMinOccurs,dMaxOccurs, (XSElementDecl)bParticle.fValue,bMinOccurs,bMaxOccurs); return; } // Elt:Any NSCompat case XSParticleDecl.PARTICLE_WILDCARD: { checkNSCompat((XSElementDecl)dParticle.fValue,dMinOccurs,dMaxOccurs, (XSWildcardDecl)bParticle.fValue,bMinOccurs,bMaxOccurs, checkWCOccurrence); return; } // Elt:All RecurseAsIfGroup case XSModelGroupImpl.MODELGROUP_CHOICE: { // Treat the element as if it were in a group of the same type // as the base Particle dChildren = new Vector(); dChildren.addElement(dParticle); checkRecurseLax(dChildren, 1, 1, dSGHandler, bChildren, bMinOccurs, bMaxOccurs, bSGHandler); return; } case XSModelGroupImpl.MODELGROUP_SEQUENCE: case XSModelGroupImpl.MODELGROUP_ALL: { // Treat the element as if it were in a group of the same type // as the base Particle dChildren = new Vector(); dChildren.addElement(dParticle); checkRecurse(dChildren, 1, 1, dSGHandler, bChildren, bMinOccurs, bMaxOccurs, bSGHandler); return; } default: { throw new XMLSchemaException("Internal-Error", new Object[]{"in particleValidRestriction"}); } } } case XSParticleDecl.PARTICLE_WILDCARD: { switch (bType) { // Any:Any NSSubset case XSParticleDecl.PARTICLE_WILDCARD: { checkNSSubset((XSWildcardDecl)dParticle.fValue, dMinOccurs, dMaxOccurs, (XSWildcardDecl)bParticle.fValue, bMinOccurs, bMaxOccurs); return; } case XSModelGroupImpl.MODELGROUP_CHOICE: case XSModelGroupImpl.MODELGROUP_SEQUENCE: case XSModelGroupImpl.MODELGROUP_ALL: case XSParticleDecl.PARTICLE_ELEMENT: { throw new XMLSchemaException("cos-particle-restrict.2", new Object[]{"any:choice,sequence,all,elt"}); } default: { throw new XMLSchemaException("Internal-Error", new Object[]{"in particleValidRestriction"}); } } } case XSModelGroupImpl.MODELGROUP_ALL: { switch (bType) { // All:Any NSRecurseCheckCardinality case XSParticleDecl.PARTICLE_WILDCARD: { if (dMinEffectiveTotalRange == OCCURRENCE_UNKNOWN) dMinEffectiveTotalRange = dParticle.minEffectiveTotalRange(); if (dMaxEffectiveTotalRange == OCCURRENCE_UNKNOWN) dMaxEffectiveTotalRange = dParticle.maxEffectiveTotalRange(); checkNSRecurseCheckCardinality(dChildren, dMinEffectiveTotalRange, dMaxEffectiveTotalRange, dSGHandler, bParticle,bMinOccurs,bMaxOccurs, checkWCOccurrence); return; } case XSModelGroupImpl.MODELGROUP_ALL: { checkRecurse(dChildren, dMinOccurs, dMaxOccurs, dSGHandler, bChildren, bMinOccurs, bMaxOccurs, bSGHandler); return; } case XSModelGroupImpl.MODELGROUP_CHOICE: case XSModelGroupImpl.MODELGROUP_SEQUENCE: case XSParticleDecl.PARTICLE_ELEMENT: { throw new XMLSchemaException("cos-particle-restrict.2", new Object[]{"all:choice,sequence,elt"}); } default: { throw new XMLSchemaException("Internal-Error", new Object[]{"in particleValidRestriction"}); } } } case XSModelGroupImpl.MODELGROUP_CHOICE: { switch (bType) { // Choice:Any NSRecurseCheckCardinality case XSParticleDecl.PARTICLE_WILDCARD: { if (dMinEffectiveTotalRange == OCCURRENCE_UNKNOWN) dMinEffectiveTotalRange = dParticle.minEffectiveTotalRange(); if (dMaxEffectiveTotalRange == OCCURRENCE_UNKNOWN) dMaxEffectiveTotalRange = dParticle.maxEffectiveTotalRange(); checkNSRecurseCheckCardinality(dChildren, dMinEffectiveTotalRange, dMaxEffectiveTotalRange, dSGHandler, bParticle,bMinOccurs,bMaxOccurs, checkWCOccurrence); return; } case XSModelGroupImpl.MODELGROUP_CHOICE: { checkRecurseLax(dChildren, dMinOccurs, dMaxOccurs, dSGHandler, bChildren, bMinOccurs, bMaxOccurs, bSGHandler); return; } case XSModelGroupImpl.MODELGROUP_ALL: case XSModelGroupImpl.MODELGROUP_SEQUENCE: case XSParticleDecl.PARTICLE_ELEMENT: { throw new XMLSchemaException("cos-particle-restrict.2", new Object[]{"choice:all,sequence,elt"}); } default: { throw new XMLSchemaException("Internal-Error", new Object[]{"in particleValidRestriction"}); } } } case XSModelGroupImpl.MODELGROUP_SEQUENCE: { switch (bType) { // Choice:Any NSRecurseCheckCardinality case XSParticleDecl.PARTICLE_WILDCARD: { if (dMinEffectiveTotalRange == OCCURRENCE_UNKNOWN) dMinEffectiveTotalRange = dParticle.minEffectiveTotalRange(); if (dMaxEffectiveTotalRange == OCCURRENCE_UNKNOWN) dMaxEffectiveTotalRange = dParticle.maxEffectiveTotalRange(); checkNSRecurseCheckCardinality(dChildren, dMinEffectiveTotalRange, dMaxEffectiveTotalRange, dSGHandler, bParticle,bMinOccurs,bMaxOccurs, checkWCOccurrence); return; } case XSModelGroupImpl.MODELGROUP_ALL: { checkRecurseUnordered(dChildren, dMinOccurs, dMaxOccurs, dSGHandler, bChildren, bMinOccurs, bMaxOccurs, bSGHandler); return; } case XSModelGroupImpl.MODELGROUP_SEQUENCE: { checkRecurse(dChildren, dMinOccurs, dMaxOccurs, dSGHandler, bChildren, bMinOccurs, bMaxOccurs, bSGHandler); return; } case XSModelGroupImpl.MODELGROUP_CHOICE: { int min1 = dMinOccurs * dChildren.size(); int max1 = (dMaxOccurs == SchemaSymbols.OCCURRENCE_UNBOUNDED)? dMaxOccurs : dMaxOccurs * dChildren.size(); checkMapAndSum(dChildren, min1, max1, dSGHandler, bChildren, bMinOccurs, bMaxOccurs, bSGHandler); return; } case XSParticleDecl.PARTICLE_ELEMENT: { throw new XMLSchemaException("cos-particle-restrict.2", new Object[]{"seq:elt"}); } default: { throw new XMLSchemaException("Internal-Error", new Object[]{"in particleValidRestriction"}); } } } } }
diff --git a/charaparser/src/semanticMarkup/ling/extract/lib/PPChunkProcessor.java b/charaparser/src/semanticMarkup/ling/extract/lib/PPChunkProcessor.java index a2812787..a98bd0a8 100644 --- a/charaparser/src/semanticMarkup/ling/extract/lib/PPChunkProcessor.java +++ b/charaparser/src/semanticMarkup/ling/extract/lib/PPChunkProcessor.java @@ -1,195 +1,195 @@ package semanticMarkup.ling.extract.lib; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import semanticMarkup.core.description.DescriptionTreatmentElement; import semanticMarkup.core.description.DescriptionType; import semanticMarkup.know.ICharacterKnowledgeBase; import semanticMarkup.know.IGlossary; import semanticMarkup.know.IPOSKnowledgeBase; import semanticMarkup.ling.chunk.Chunk; import semanticMarkup.ling.chunk.ChunkType; import semanticMarkup.ling.extract.AbstractChunkProcessor; import semanticMarkup.ling.extract.ProcessingContext; import semanticMarkup.ling.extract.ProcessingContextState; import semanticMarkup.ling.learn.ITerminologyLearner; import semanticMarkup.ling.parse.AbstractParseTree; import semanticMarkup.ling.transform.IInflector; import com.google.inject.Inject; import com.google.inject.name.Named; public class PPChunkProcessor extends AbstractChunkProcessor { @Inject public PPChunkProcessor(IInflector inflector, IGlossary glossary, ITerminologyLearner terminologyLearner, ICharacterKnowledgeBase characterKnowledgeBase, @Named("LearnedPOSKnowledgeBase") IPOSKnowledgeBase posKnowledgeBase, @Named("BaseCountWords")Set<String> baseCountWords, @Named("LocationPrepositionWords")Set<String> locationPrepositions, @Named("Clusters")Set<String> clusters, @Named("Units")String units, @Named("EqualCharacters")HashMap<String, String> equalCharacters, @Named("NumberPattern")String numberPattern, @Named("AttachToLast")boolean attachToLast, @Named("TimesWords")String times) { super(inflector, glossary, terminologyLearner, characterKnowledgeBase, posKnowledgeBase, baseCountWords, locationPrepositions, clusters, units, equalCharacters, numberPattern, attachToLast, times); } @Override protected ArrayList<DescriptionTreatmentElement> processChunk(Chunk chunk, ProcessingContext processingContext) { ArrayList<DescriptionTreatmentElement> result = new ArrayList<DescriptionTreatmentElement>(); ProcessingContextState processingContextState = processingContext.getCurrentState(); LinkedList<DescriptionTreatmentElement> lastElements = processingContextState.getLastElements(); List<Chunk> unassignedModifiers = processingContextState.getUnassignedModifiers(); //r[{} {} p[of] o[.....]] List<Chunk> modifier = new ArrayList<Chunk>();// chunk.getChunks(ChunkType.MODIFIER); Chunk preposition = chunk.getChunkDFS(ChunkType.PREPOSITION); LinkedHashSet<Chunk> prepositionChunks = preposition.getChunks(); Chunk object = chunk.getChunkDFS(ChunkType.OBJECT); if(characterPrep(chunk, processingContextState)) return result; boolean lastIsStructure = false; boolean lastIsCharacter = false; boolean lastIsComma = false; if (lastElements.isEmpty()) { unassignedModifiers.add(chunk); return result; } DescriptionTreatmentElement lastElement = lastElements.getLast(); if(lastElement != null) { lastIsStructure = lastElement.isOfDescriptionType(DescriptionType.STRUCTURE); lastIsCharacter = lastElement.isOfDescriptionType(DescriptionType.CHARACTER); if(lastIsStructure && isNumerical(object)) { List<Chunk> modifiers = new ArrayList<Chunk>(); result.addAll(annotateNumericals(object.getTerminalsText(), "count", modifiers, lastElements, false, processingContextState)); return result; } Set<Chunk> objects = new HashSet<Chunk>(); if(object.containsChildOfChunkType(ChunkType.OR) || object.containsChildOfChunkType(ChunkType.AND) || object.containsChildOfChunkType(ChunkType.NP_LIST)) { objects = splitObject(object); } else { objects.add(object); } LinkedList<DescriptionTreatmentElement> subjectStructures = processingContextState.getLastElements(); - if(!lastIsStructure) { + if(!lastIsStructure || processingContextState.isCommaAndOrEosEolAfterLastElements()) { subjectStructures = processingContextState.getSubjects(); } for(Chunk aObject : objects) { boolean lastChunkIsOrgan = true; boolean foundOrgan = false; LinkedHashSet<Chunk> beforeOrganChunks = new LinkedHashSet<Chunk>(); LinkedHashSet<Chunk> organChunks = new LinkedHashSet<Chunk>(); LinkedHashSet<Chunk> afterOrganChunks = new LinkedHashSet<Chunk>(); this.getOrganChunks(aObject, beforeOrganChunks, organChunks, afterOrganChunks); foundOrgan = !organChunks.isEmpty(); lastChunkIsOrgan = afterOrganChunks.isEmpty() && foundOrgan; /*for(Chunk objectChunk : object.getChunks()) { if(objectChunk.isOfChunkType(ChunkType.ORGAN)) { lastChunkIsOrgan = true; foundOrgan = true; organChunks.add(objectChunk); } else { lastChunkIsOrgan = false; if(foundOrgan) afterOrganChunks.add(objectChunk); else beforeOrganChunks.add(objectChunk); } }*/ if(lastChunkIsOrgan) { result.addAll(linkObjects(subjectStructures, modifier, preposition, aObject, lastIsStructure, lastIsCharacter, processingContext, processingContextState)); } else if(foundOrgan) { LinkedHashSet<Chunk> objectChunks = new LinkedHashSet<Chunk>(); objectChunks.addAll(beforeOrganChunks); objectChunks.addAll(organChunks); //obj = beforeOrganChunks + organChunks; //modi = afterOrganChunks; Chunk objectChunk = new Chunk(ChunkType.UNASSIGNED, objectChunks); result.addAll(linkObjects(subjectStructures, modifier, preposition, objectChunk, lastIsStructure, lastIsCharacter, processingContext, processingContextState)); //result.addAll(structures); } else { if(lastIsStructure) lastElement.appendProperty("constraint", chunk.getTerminalsText()); else if(lastIsCharacter) { LinkedList<DescriptionTreatmentElement> objectStructures = this.extractStructuresFromObject(object, processingContext, processingContextState); lastElement.appendProperty("constraint", chunk.getTerminalsText()); if(!objectStructures.isEmpty()) { result.addAll(objectStructures); lastElement.setProperty("constraintId", listStructureIds(objectStructures)); } } } } } processingContextState.setCommaAndOrEosEolAfterLastElements(false); return result; } private Set<Chunk> splitObject(Chunk object) { Set<Chunk> objectChunks = new HashSet<Chunk>(); LinkedHashSet<Chunk> childChunks = new LinkedHashSet<Chunk>(); boolean collectedOrgan = false; if(object.containsChildOfChunkType(ChunkType.NP_LIST)) object = object.getChildChunk(ChunkType.NP_LIST); for(Chunk chunk : object.getChunks()) { if((chunk.isOfChunkType(ChunkType.OR) || chunk.isOfChunkType(ChunkType.AND) || chunk.getTerminalsText().equals("and") || chunk.getTerminalsText().equals("or")) && collectedOrgan) { Chunk objectChunk = new Chunk(ChunkType.OBJECT, childChunks); objectChunks.add(objectChunk); childChunks.clear(); } else { for(AbstractParseTree terminal : chunk.getTerminals()) { if(chunk.isPartOfChunkType(terminal, ChunkType.ORGAN)) { collectedOrgan = true; childChunks.add(chunk); } else { childChunks.add(chunk); } } } } Chunk objectChunk = new Chunk(ChunkType.OBJECT, childChunks); objectChunks.add(objectChunk); return objectChunks; } private void getOrganChunks(Chunk organParentChunk, LinkedHashSet<Chunk> beforeOrganChunks, LinkedHashSet<Chunk> organChunks, LinkedHashSet<Chunk> afterOrganChunks) { if(organParentChunk.isOfChunkType(ChunkType.ORGAN)) { organChunks.add(organParentChunk); } else if(!organParentChunk.containsChunkType(ChunkType.ORGAN) || !afterOrganChunks.isEmpty()) { if(organChunks.isEmpty()) { beforeOrganChunks.add(organParentChunk); } if(!organChunks.isEmpty()) { afterOrganChunks.add(organParentChunk); } } else if(organParentChunk.containsChunkType(ChunkType.ORGAN)) { LinkedHashSet<Chunk> chunks = organParentChunk.getChunks(); for(Chunk chunk : chunks) { getOrganChunks(chunk, beforeOrganChunks, organChunks, afterOrganChunks); } } } }
true
true
protected ArrayList<DescriptionTreatmentElement> processChunk(Chunk chunk, ProcessingContext processingContext) { ArrayList<DescriptionTreatmentElement> result = new ArrayList<DescriptionTreatmentElement>(); ProcessingContextState processingContextState = processingContext.getCurrentState(); LinkedList<DescriptionTreatmentElement> lastElements = processingContextState.getLastElements(); List<Chunk> unassignedModifiers = processingContextState.getUnassignedModifiers(); //r[{} {} p[of] o[.....]] List<Chunk> modifier = new ArrayList<Chunk>();// chunk.getChunks(ChunkType.MODIFIER); Chunk preposition = chunk.getChunkDFS(ChunkType.PREPOSITION); LinkedHashSet<Chunk> prepositionChunks = preposition.getChunks(); Chunk object = chunk.getChunkDFS(ChunkType.OBJECT); if(characterPrep(chunk, processingContextState)) return result; boolean lastIsStructure = false; boolean lastIsCharacter = false; boolean lastIsComma = false; if (lastElements.isEmpty()) { unassignedModifiers.add(chunk); return result; } DescriptionTreatmentElement lastElement = lastElements.getLast(); if(lastElement != null) { lastIsStructure = lastElement.isOfDescriptionType(DescriptionType.STRUCTURE); lastIsCharacter = lastElement.isOfDescriptionType(DescriptionType.CHARACTER); if(lastIsStructure && isNumerical(object)) { List<Chunk> modifiers = new ArrayList<Chunk>(); result.addAll(annotateNumericals(object.getTerminalsText(), "count", modifiers, lastElements, false, processingContextState)); return result; } Set<Chunk> objects = new HashSet<Chunk>(); if(object.containsChildOfChunkType(ChunkType.OR) || object.containsChildOfChunkType(ChunkType.AND) || object.containsChildOfChunkType(ChunkType.NP_LIST)) { objects = splitObject(object); } else { objects.add(object); } LinkedList<DescriptionTreatmentElement> subjectStructures = processingContextState.getLastElements(); if(!lastIsStructure) { subjectStructures = processingContextState.getSubjects(); } for(Chunk aObject : objects) { boolean lastChunkIsOrgan = true; boolean foundOrgan = false; LinkedHashSet<Chunk> beforeOrganChunks = new LinkedHashSet<Chunk>(); LinkedHashSet<Chunk> organChunks = new LinkedHashSet<Chunk>(); LinkedHashSet<Chunk> afterOrganChunks = new LinkedHashSet<Chunk>(); this.getOrganChunks(aObject, beforeOrganChunks, organChunks, afterOrganChunks); foundOrgan = !organChunks.isEmpty(); lastChunkIsOrgan = afterOrganChunks.isEmpty() && foundOrgan; /*for(Chunk objectChunk : object.getChunks()) { if(objectChunk.isOfChunkType(ChunkType.ORGAN)) { lastChunkIsOrgan = true; foundOrgan = true; organChunks.add(objectChunk); } else { lastChunkIsOrgan = false; if(foundOrgan) afterOrganChunks.add(objectChunk); else beforeOrganChunks.add(objectChunk); } }*/ if(lastChunkIsOrgan) { result.addAll(linkObjects(subjectStructures, modifier, preposition, aObject, lastIsStructure, lastIsCharacter, processingContext, processingContextState)); } else if(foundOrgan) { LinkedHashSet<Chunk> objectChunks = new LinkedHashSet<Chunk>(); objectChunks.addAll(beforeOrganChunks); objectChunks.addAll(organChunks); //obj = beforeOrganChunks + organChunks; //modi = afterOrganChunks; Chunk objectChunk = new Chunk(ChunkType.UNASSIGNED, objectChunks); result.addAll(linkObjects(subjectStructures, modifier, preposition, objectChunk, lastIsStructure, lastIsCharacter, processingContext, processingContextState)); //result.addAll(structures); } else { if(lastIsStructure) lastElement.appendProperty("constraint", chunk.getTerminalsText()); else if(lastIsCharacter) { LinkedList<DescriptionTreatmentElement> objectStructures = this.extractStructuresFromObject(object, processingContext, processingContextState); lastElement.appendProperty("constraint", chunk.getTerminalsText()); if(!objectStructures.isEmpty()) { result.addAll(objectStructures); lastElement.setProperty("constraintId", listStructureIds(objectStructures)); } } } } }
protected ArrayList<DescriptionTreatmentElement> processChunk(Chunk chunk, ProcessingContext processingContext) { ArrayList<DescriptionTreatmentElement> result = new ArrayList<DescriptionTreatmentElement>(); ProcessingContextState processingContextState = processingContext.getCurrentState(); LinkedList<DescriptionTreatmentElement> lastElements = processingContextState.getLastElements(); List<Chunk> unassignedModifiers = processingContextState.getUnassignedModifiers(); //r[{} {} p[of] o[.....]] List<Chunk> modifier = new ArrayList<Chunk>();// chunk.getChunks(ChunkType.MODIFIER); Chunk preposition = chunk.getChunkDFS(ChunkType.PREPOSITION); LinkedHashSet<Chunk> prepositionChunks = preposition.getChunks(); Chunk object = chunk.getChunkDFS(ChunkType.OBJECT); if(characterPrep(chunk, processingContextState)) return result; boolean lastIsStructure = false; boolean lastIsCharacter = false; boolean lastIsComma = false; if (lastElements.isEmpty()) { unassignedModifiers.add(chunk); return result; } DescriptionTreatmentElement lastElement = lastElements.getLast(); if(lastElement != null) { lastIsStructure = lastElement.isOfDescriptionType(DescriptionType.STRUCTURE); lastIsCharacter = lastElement.isOfDescriptionType(DescriptionType.CHARACTER); if(lastIsStructure && isNumerical(object)) { List<Chunk> modifiers = new ArrayList<Chunk>(); result.addAll(annotateNumericals(object.getTerminalsText(), "count", modifiers, lastElements, false, processingContextState)); return result; } Set<Chunk> objects = new HashSet<Chunk>(); if(object.containsChildOfChunkType(ChunkType.OR) || object.containsChildOfChunkType(ChunkType.AND) || object.containsChildOfChunkType(ChunkType.NP_LIST)) { objects = splitObject(object); } else { objects.add(object); } LinkedList<DescriptionTreatmentElement> subjectStructures = processingContextState.getLastElements(); if(!lastIsStructure || processingContextState.isCommaAndOrEosEolAfterLastElements()) { subjectStructures = processingContextState.getSubjects(); } for(Chunk aObject : objects) { boolean lastChunkIsOrgan = true; boolean foundOrgan = false; LinkedHashSet<Chunk> beforeOrganChunks = new LinkedHashSet<Chunk>(); LinkedHashSet<Chunk> organChunks = new LinkedHashSet<Chunk>(); LinkedHashSet<Chunk> afterOrganChunks = new LinkedHashSet<Chunk>(); this.getOrganChunks(aObject, beforeOrganChunks, organChunks, afterOrganChunks); foundOrgan = !organChunks.isEmpty(); lastChunkIsOrgan = afterOrganChunks.isEmpty() && foundOrgan; /*for(Chunk objectChunk : object.getChunks()) { if(objectChunk.isOfChunkType(ChunkType.ORGAN)) { lastChunkIsOrgan = true; foundOrgan = true; organChunks.add(objectChunk); } else { lastChunkIsOrgan = false; if(foundOrgan) afterOrganChunks.add(objectChunk); else beforeOrganChunks.add(objectChunk); } }*/ if(lastChunkIsOrgan) { result.addAll(linkObjects(subjectStructures, modifier, preposition, aObject, lastIsStructure, lastIsCharacter, processingContext, processingContextState)); } else if(foundOrgan) { LinkedHashSet<Chunk> objectChunks = new LinkedHashSet<Chunk>(); objectChunks.addAll(beforeOrganChunks); objectChunks.addAll(organChunks); //obj = beforeOrganChunks + organChunks; //modi = afterOrganChunks; Chunk objectChunk = new Chunk(ChunkType.UNASSIGNED, objectChunks); result.addAll(linkObjects(subjectStructures, modifier, preposition, objectChunk, lastIsStructure, lastIsCharacter, processingContext, processingContextState)); //result.addAll(structures); } else { if(lastIsStructure) lastElement.appendProperty("constraint", chunk.getTerminalsText()); else if(lastIsCharacter) { LinkedList<DescriptionTreatmentElement> objectStructures = this.extractStructuresFromObject(object, processingContext, processingContextState); lastElement.appendProperty("constraint", chunk.getTerminalsText()); if(!objectStructures.isEmpty()) { result.addAll(objectStructures); lastElement.setProperty("constraintId", listStructureIds(objectStructures)); } } } } }
diff --git a/Rania/src/com/game/rania/model/element/Player.java b/Rania/src/com/game/rania/model/element/Player.java index ca8b043..f6762f1 100644 --- a/Rania/src/com/game/rania/model/element/Player.java +++ b/Rania/src/com/game/rania/model/element/Player.java @@ -1,109 +1,111 @@ package com.game.rania.model.element; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType; import com.game.rania.RaniaGame; import com.game.rania.model.Font; public class Player extends User { public Target target = new Target(0, Target.none, null); public Player(int id, float posX, float posY, String ShipName, String PilotName, int domain) { super(id, posX, posY, ShipName, PilotName, domain); zIndex = Indexes.player; isPlayer = true; } public Player(int id, float posX, float posY, String ShipName, String PilotName, int domain, int inPlanet) { super(id, posX, posY, ShipName, PilotName, domain, inPlanet); zIndex = Indexes.player; isPlayer = true; } public void clearTarget() { target.id = 0; target.type = Target.none; target.object = null; } @Override public boolean update(float deltaTime) { if (!super.update(deltaTime)) return false; target.update(deltaTime); return true; } protected Text deadText = new Text("�� �������. ���������� ���������...", Font.getFont("data/fonts/Arial.ttf", 50), new Color(1, 0, 0, 1), 0, 0); @Override public boolean draw(SpriteBatch sprite, ShapeRenderer shape) { if (planet > 0) { angle.value = 0.0f; position.set(target.object.position); return true; } if (body.wear <= 0) { deadText.draw(sprite, position.x, position.y); return true; } target.draw(sprite, shape); sprite.end(); shape.begin(ShapeType.Filled); float dx = RaniaGame.mView.getCamera().getWidth() * 0.25f; float dy = RaniaGame.mView.getCamera().getHeight() * 0.5f; if (body != null) { shape.setColor(new Color(1, 0, 0, 0.75f)); shape.rect(position.x - dx, position.y + dy - 20, dx * ((float) Math.max(0, body.wear) / body.item.durability), 15); } if (shield != null) { shape.setColor(new Color(0, 0, 1, 0.75f)); shape.rect(position.x - dx, position.y + dy - 35, dx * ((float) Math.max(0, shield.wear) / shield.item.durability), 15); } if (battery != null) { shape.setColor(new Color(0, 1, 0, 0.75f)); shape.rect(position.x - dx, position.y + dy - 50, dx * ((float) Math.max(0, energy) / maxEnergy), 15); } if (target.type == Target.user) { User user = target.getObject(User.class); + if (user.body.wear <= 0) + clearTarget(); if (user.body != null) { shape.setColor(new Color(1, 0, 0, 0.75f)); shape.rect(position.x + 15, position.y + dy - 20, dx * ((float) Math.max(0, user.body.wear) / user.body.item.durability), 15); } if (shield != null) { shape.setColor(new Color(0, 0, 1, 0.75f)); shape.rect(position.x + 15, position.y + dy - 35, dx * ((float) Math.max(0, user.shield.wear) / user.shield.item.durability), 15); } } shape.end(); sprite.begin(); return super.draw(sprite, shape); } public float getTargetDistance() { return (float) Math.sqrt(Math.pow(position.x - target.object.position.x, 2) + Math.pow(position.y - target.object.position.y, 2)); } }
true
true
public boolean draw(SpriteBatch sprite, ShapeRenderer shape) { if (planet > 0) { angle.value = 0.0f; position.set(target.object.position); return true; } if (body.wear <= 0) { deadText.draw(sprite, position.x, position.y); return true; } target.draw(sprite, shape); sprite.end(); shape.begin(ShapeType.Filled); float dx = RaniaGame.mView.getCamera().getWidth() * 0.25f; float dy = RaniaGame.mView.getCamera().getHeight() * 0.5f; if (body != null) { shape.setColor(new Color(1, 0, 0, 0.75f)); shape.rect(position.x - dx, position.y + dy - 20, dx * ((float) Math.max(0, body.wear) / body.item.durability), 15); } if (shield != null) { shape.setColor(new Color(0, 0, 1, 0.75f)); shape.rect(position.x - dx, position.y + dy - 35, dx * ((float) Math.max(0, shield.wear) / shield.item.durability), 15); } if (battery != null) { shape.setColor(new Color(0, 1, 0, 0.75f)); shape.rect(position.x - dx, position.y + dy - 50, dx * ((float) Math.max(0, energy) / maxEnergy), 15); } if (target.type == Target.user) { User user = target.getObject(User.class); if (user.body != null) { shape.setColor(new Color(1, 0, 0, 0.75f)); shape.rect(position.x + 15, position.y + dy - 20, dx * ((float) Math.max(0, user.body.wear) / user.body.item.durability), 15); } if (shield != null) { shape.setColor(new Color(0, 0, 1, 0.75f)); shape.rect(position.x + 15, position.y + dy - 35, dx * ((float) Math.max(0, user.shield.wear) / user.shield.item.durability), 15); } } shape.end(); sprite.begin(); return super.draw(sprite, shape); }
public boolean draw(SpriteBatch sprite, ShapeRenderer shape) { if (planet > 0) { angle.value = 0.0f; position.set(target.object.position); return true; } if (body.wear <= 0) { deadText.draw(sprite, position.x, position.y); return true; } target.draw(sprite, shape); sprite.end(); shape.begin(ShapeType.Filled); float dx = RaniaGame.mView.getCamera().getWidth() * 0.25f; float dy = RaniaGame.mView.getCamera().getHeight() * 0.5f; if (body != null) { shape.setColor(new Color(1, 0, 0, 0.75f)); shape.rect(position.x - dx, position.y + dy - 20, dx * ((float) Math.max(0, body.wear) / body.item.durability), 15); } if (shield != null) { shape.setColor(new Color(0, 0, 1, 0.75f)); shape.rect(position.x - dx, position.y + dy - 35, dx * ((float) Math.max(0, shield.wear) / shield.item.durability), 15); } if (battery != null) { shape.setColor(new Color(0, 1, 0, 0.75f)); shape.rect(position.x - dx, position.y + dy - 50, dx * ((float) Math.max(0, energy) / maxEnergy), 15); } if (target.type == Target.user) { User user = target.getObject(User.class); if (user.body.wear <= 0) clearTarget(); if (user.body != null) { shape.setColor(new Color(1, 0, 0, 0.75f)); shape.rect(position.x + 15, position.y + dy - 20, dx * ((float) Math.max(0, user.body.wear) / user.body.item.durability), 15); } if (shield != null) { shape.setColor(new Color(0, 0, 1, 0.75f)); shape.rect(position.x + 15, position.y + dy - 35, dx * ((float) Math.max(0, user.shield.wear) / user.shield.item.durability), 15); } } shape.end(); sprite.begin(); return super.draw(sprite, shape); }
diff --git a/src/com/jambit/coffeeparty/AvatarActivity.java b/src/com/jambit/coffeeparty/AvatarActivity.java index 0501b3d..2126a19 100644 --- a/src/com/jambit/coffeeparty/AvatarActivity.java +++ b/src/com/jambit/coffeeparty/AvatarActivity.java @@ -1,63 +1,68 @@ package com.jambit.coffeeparty; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.provider.MediaStore; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Gallery; import android.widget.TextView; public class AvatarActivity extends Activity { private static final int TAKE_PHOTO_ACTIONCODE = 0; public static String PLAYERNAME_EXTRA = "playerName"; public static String SELECTED_AVATAR_EXTRA = "selected_avatar"; private Intent data = new Intent(); private ImageAdapter imageAdapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.avataractivity); imageAdapter = new ImageAdapter(this); Gallery g = (Gallery) findViewById(R.id.gallery1); g.setAdapter(imageAdapter); TextView playerNameTextView = (TextView) findViewById(R.id.playerNameTextView); CharSequence playerName = getIntent().getCharSequenceExtra(PLAYERNAME_EXTRA); playerNameTextView.setText(playerName); data.putExtra(PLAYERNAME_EXTRA, playerName); g.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(@SuppressWarnings("rawtypes") AdapterView parent, View v, int position, long id) { - data.putExtra(SELECTED_AVATAR_EXTRA, imageAdapter.getItemId(position)); + Drawable selectedDrawable = (Drawable) imageAdapter.getItem(position); + if (selectedDrawable instanceof BitmapDrawable) { + data.putExtra(SELECTED_AVATAR_EXTRA, ((BitmapDrawable) selectedDrawable).getBitmap()); + } else { + Log.e("AvatarActivity", "Selected drawable is not a Bitmap."); + } } }); } public void onApplyButtonClicked(View v) { setResult(RESULT_OK, data); finish(); } public void cameraButtonOnClick(View v) { Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(takePictureIntent, TAKE_PHOTO_ACTIONCODE); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { Bundle extras = data.getExtras(); if (requestCode == TAKE_PHOTO_ACTIONCODE) { Bitmap mImageBitmap = (Bitmap) extras.get("data"); data.putExtra(SELECTED_AVATAR_EXTRA, mImageBitmap); imageAdapter.addBitmap(mImageBitmap); } super.onActivityResult(requestCode, resultCode, data); } }
true
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.avataractivity); imageAdapter = new ImageAdapter(this); Gallery g = (Gallery) findViewById(R.id.gallery1); g.setAdapter(imageAdapter); TextView playerNameTextView = (TextView) findViewById(R.id.playerNameTextView); CharSequence playerName = getIntent().getCharSequenceExtra(PLAYERNAME_EXTRA); playerNameTextView.setText(playerName); data.putExtra(PLAYERNAME_EXTRA, playerName); g.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(@SuppressWarnings("rawtypes") AdapterView parent, View v, int position, long id) { data.putExtra(SELECTED_AVATAR_EXTRA, imageAdapter.getItemId(position)); } }); }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.avataractivity); imageAdapter = new ImageAdapter(this); Gallery g = (Gallery) findViewById(R.id.gallery1); g.setAdapter(imageAdapter); TextView playerNameTextView = (TextView) findViewById(R.id.playerNameTextView); CharSequence playerName = getIntent().getCharSequenceExtra(PLAYERNAME_EXTRA); playerNameTextView.setText(playerName); data.putExtra(PLAYERNAME_EXTRA, playerName); g.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(@SuppressWarnings("rawtypes") AdapterView parent, View v, int position, long id) { Drawable selectedDrawable = (Drawable) imageAdapter.getItem(position); if (selectedDrawable instanceof BitmapDrawable) { data.putExtra(SELECTED_AVATAR_EXTRA, ((BitmapDrawable) selectedDrawable).getBitmap()); } else { Log.e("AvatarActivity", "Selected drawable is not a Bitmap."); } } }); }
diff --git a/freemind/plugins/map/MapDialog.java b/freemind/plugins/map/MapDialog.java index 35205c0..c9e8edc 100644 --- a/freemind/plugins/map/MapDialog.java +++ b/freemind/plugins/map/MapDialog.java @@ -1,989 +1,990 @@ package plugins.map; //License: GPL. Copyright 2008 by Jan Peter Stotz import java.awt.AWTEvent; import java.awt.BorderLayout; import java.awt.Color; import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.Vector; import javax.swing.AbstractAction; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.ListSelectionModel; import javax.swing.WindowConstants; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.table.AbstractTableModel; import org.openstreetmap.gui.jmapviewer.Coordinate; import org.openstreetmap.gui.jmapviewer.JMapViewer; import org.openstreetmap.gui.jmapviewer.OsmMercator; import org.openstreetmap.gui.jmapviewer.OsmTileLoader; import org.openstreetmap.gui.jmapviewer.events.JMVCommandEvent; import org.openstreetmap.gui.jmapviewer.interfaces.JMapViewerEventListener; import org.openstreetmap.gui.jmapviewer.tilesources.OsmTileSource.Mapnik; import plugins.map.FreeMindMapController.CursorPositionListener; import plugins.map.MapNodePositionHolder.MapNodePositionListener; import plugins.map.Registration.NodeVisibilityListener; import accessories.plugins.time.TableSorter; import freemind.common.TextTranslator; import freemind.controller.MapModuleManager.MapModuleChangeObserver; import freemind.controller.actions.generated.instance.MapWindowConfigurationStorage; import freemind.controller.actions.generated.instance.Place; import freemind.controller.actions.generated.instance.TableColumnSetting; import freemind.main.Resources; import freemind.main.Tools; import freemind.modes.MindMapNode; import freemind.modes.Mode; import freemind.modes.ModeController.NodeSelectionListener; import freemind.modes.mindmapmode.MindMapController; import freemind.modes.mindmapmode.hooks.MindMapHookAdapter; import freemind.view.MapModule; import freemind.view.mindmapview.NodeView; /** * * Demonstrates the usage of {@link JMapViewer} * * @author Jan Peter Stotz adapted for FreeMind by Chris. */ public class MapDialog extends MindMapHookAdapter implements JMapViewerEventListener, MapModuleChangeObserver, MapNodePositionListener, NodeSelectionListener, NodeVisibilityListener { private static final String WINDOW_PREFERENCE_STORAGE_PROPERTY = MapDialog.class .getName(); static final String TILE_CACHE_CLASS = "tile_cache_class"; static final String FILE_TILE_CACHE_DIRECTORY = "file_tile_cache_directory"; public static final String TILE_CACHE_MAX_AGE = "tile_cache_max_age"; private static final int SEARCH_DESCRIPTION_COLUMN = 0; public static final int SEARCH_DISTANCE_COLUMN = 1; private JCursorMapViewer map = null; private JLabel zoomLabel = null; private JLabel zoomValue = null; private JLabel mperpLabelName = null; private JLabel mperpLabelValue = null; private MindMapController mMyMindMapController; private JDialog mMapDialog; private HashMap /* < MapNodePositionHolder, MapMarkerLocation > */mMarkerMap = new HashMap(); private CloseAction mCloseAction; private JPanel mSearchFieldPanel; private JSplitPane mSearchSplitPane; private boolean mSearchBarVisible; private JPanel mSearchPanel; private JTextField mSearchTerm; static final String MAP_HOOK_NAME = "plugins/map/MapDialog.properties"; public static final String TILE_CACHE_PURGE_TIME = "tile_cache_purge_time"; public static final long TILE_CACHE_PURGE_TIME_DEFAULT = 1000 * 60 * 10; private static final String SEARCH_DESCRIPTION_COLUMN_TEXT = "plugins/map/MapDialog.Description"; private static final String SEARCH_DISTANCE_COLUMN_TEXT = "plugins/map/MapDialog.Distance"; private JLabel mStatusLabel; /** * Indicates that after a search, when a place was selected, the search * dialog should close */ private boolean mSingleSearch = false; private JTable mResultTable; private ResultTableModel mResultTableModel; private TableSorter mResultTableSorter; private Color mTableOriginalBackgroundColor; /** * I know, that the JSplitPane collects this information, but I want to * handle it here. */ private int mLastDividerPosition = 300; private boolean mLimitSearchToRegion = false; private JLabel mSearchStringLabel; private String mResourceSearchLocationString; private String mResourceSearchString; private final class CloseAction extends AbstractAction { public CloseAction() { super(getResourceString("MapDialog_close")); } public void actionPerformed(ActionEvent arg0) { disposeDialog(); } } /** * @author foltin * @date 25.04.2012 */ public final class ResultTableModel extends AbstractTableModel implements CursorPositionListener { /** * */ private final String[] COLUMNS = new String[] { SEARCH_DESCRIPTION_COLUMN_TEXT, SEARCH_DISTANCE_COLUMN_TEXT }; Vector mData = new Vector(); private Coordinate mCursorCoordinate = new Coordinate(0, 0); private HashMap mMapSearchMarkerLocationHash = new HashMap(); private final TextTranslator mTextTranslator; /** * @param pCursorCoordinate */ public ResultTableModel(Coordinate pCursorCoordinate, TextTranslator pTextTranslator) { super(); mCursorCoordinate = pCursorCoordinate; mTextTranslator = pTextTranslator; } /* * (non-Javadoc) * * @see javax.swing.table.AbstractTableModel#getColumnClass(int) */ public Class getColumnClass(int arg0) { switch (arg0) { case SEARCH_DESCRIPTION_COLUMN: return String.class; case SEARCH_DISTANCE_COLUMN: return Double.class; default: return Object.class; } } /** * @param pPlace */ public void addPlace(Place pPlace) { mData.add(pPlace); final int row = mData.size() - 1; MapSearchMarkerLocation location = new MapSearchMarkerLocation( MapDialog.this, pPlace); mMapSearchMarkerLocationHash.put(pPlace, location); getMap().addMapMarker(location); fireTableRowsInserted(row, row); } public MapSearchMarkerLocation getMapSearchMarkerLocation(int index) { if (index >= 0 && index < getRowCount()) { Place place = getPlace(index); return (MapSearchMarkerLocation) mMapSearchMarkerLocationHash .get(place); } throw new IllegalArgumentException("Index " + index + " is out of range."); } public Place getPlace(int pIndex) { return (Place) mData.get(pIndex); } /* * (non-Javadoc) * * @see javax.swing.table.AbstractTableModel#getColumnName(int) */ public String getColumnName(int pColumn) { return mTextTranslator.getText(COLUMNS[pColumn]); } /* * (non-Javadoc) * * @see javax.swing.table.TableModel#getRowCount() */ public int getRowCount() { return mData.size(); } /* * (non-Javadoc) * * @see javax.swing.table.TableModel#getColumnCount() */ public int getColumnCount() { return 2; } /* * (non-Javadoc) * * @see javax.swing.table.TableModel#getValueAt(int, int) */ public Object getValueAt(int pRowIndex, int pColumnIndex) { final Place place = getPlace(pRowIndex); switch (pColumnIndex) { case SEARCH_DISTANCE_COLUMN: final double value = OsmMercator.getDistance( mCursorCoordinate.getLat(), mCursorCoordinate.getLon(), place.getLat(), place.getLon()) / 1000.0; if (Double.isInfinite(value) || Double.isNaN(value)) { return Double.valueOf(-1.0); } return new Double(value); case SEARCH_DESCRIPTION_COLUMN: return place.getDisplayName(); } return null; } /** * */ public void clear() { // clear old search results: for (Iterator it = mMapSearchMarkerLocationHash.keySet().iterator(); it.hasNext();) { Place place = (Place) it.next(); MapSearchMarkerLocation location = (MapSearchMarkerLocation) mMapSearchMarkerLocationHash.get(place); getMap().removeMapMarker(location); } mMapSearchMarkerLocationHash.clear(); mData.clear(); fireTableDataChanged(); } /* * (non-Javadoc) * * @see plugins.map.FreeMindMapController.CursorPositionListener# * cursorPositionChanged(org.openstreetmap.gui.jmapviewer.Coordinate) */ public void cursorPositionChanged(Coordinate pCursorPosition) { mCursorCoordinate = pCursorPosition; fireTableDataChanged(); } } /* * (non-Javadoc) * * @see freemind.extensions.HookAdapter#startupMapHook() */ public void startupMapHook() { super.startupMapHook(); mMyMindMapController = super.getMindMapController(); getMindMapController().getController().getMapModuleManager() .addListener(this); mMapDialog = new JDialog(getController().getFrame().getJFrame(), false /* unmodal */); mMapDialog.setTitle(getResourceString("MapDialog_title")); mMapDialog .setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); mMapDialog.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent event) { disposeDialog(); } }); mCloseAction = new CloseAction(); // the action title is changed by the following method, thus we create // another close action. Tools.addEscapeActionToDialog(mMapDialog, new CloseAction()); mMapDialog.setSize(400, 400); map = new JCursorMapViewer(getMindMapController(), mMapDialog, getRegistration().getTileCache(), this); map.addJMVListener(this); FreeMindMapController.changeTileSource(Mapnik.class.getName(), map); OsmTileLoader loader = getRegistration().createTileLoader(map); map.setTileLoader(loader); mMapDialog.setLayout(new BorderLayout()); mSearchPanel = new JPanel(new BorderLayout()); mResourceSearchString = getResourceString("MapDialog_Search"); mResourceSearchLocationString = getResourceString("MapDialog_Search_Location"); mSearchStringLabel = new JLabel(mResourceSearchString); mSearchTerm = new JTextField(); mSearchTerm.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent pEvent) { if (pEvent.getKeyCode() == KeyEvent.VK_DOWN && pEvent.getModifiers() == 0) { logger.info("Set Focus to search list."); mResultTable.requestFocusInWindow(); mResultTable.getSelectionModel().setSelectionInterval(0, 0); pEvent.consume(); } } }); mSearchTerm.addKeyListener(getFreeMindMapController()); mSearchFieldPanel = new JPanel(); mSearchFieldPanel.setLayout(new BorderLayout(10, 0)); JButton clearButton = new JButton(new ImageIcon(Resources.getInstance() .getResource("images/clear_box.png"))); clearButton.setFocusable(false); mSearchFieldPanel.add(mSearchStringLabel, BorderLayout.WEST); mSearchFieldPanel.add(mSearchTerm, BorderLayout.CENTER); mSearchFieldPanel.add(clearButton, BorderLayout.EAST); mResultTable = new JTable(); mTableOriginalBackgroundColor = mResultTable.getBackground(); mResultTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); mResultTable.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent pEvent) { int index = mResultTable.getSelectedRow(); if (index == 0 && pEvent.getKeyCode() == KeyEvent.VK_UP && pEvent.getModifiers() == 0) { logger.info("Set Focus to search item."); mResultTable.clearSelection(); mSearchTerm.requestFocusInWindow(); pEvent.consume(); return; } if (pEvent.getKeyCode() == KeyEvent.VK_ENTER && pEvent.getModifiers() == 0) { logger.info("Set result in map."); pEvent.consume(); displaySearchItem(mResultTableModel, index); return; } } }); mResultTable.addKeyListener(getFreeMindMapController()); mResultTable.getSelectionModel().addListSelectionListener( new ListSelectionListener() { public void valueChanged(ListSelectionEvent pE) { clearIndexes(); final int selectedRow = mResultTable.getSelectedRow(); if (selectedRow >= 0 && selectedRow < mResultTableSorter .getRowCount()) { int index = selectedRow; index = mResultTableSorter.modelIndex(index); MapSearchMarkerLocation marker = mResultTableModel .getMapSearchMarkerLocation(index); marker.setSelected(true); } mResultTable.repaint(); + getMap().repaint(); } private void clearIndexes() { for (int i = 0; i < mResultTableModel.getRowCount(); i++) { MapSearchMarkerLocation marker = mResultTableModel .getMapSearchMarkerLocation(i); marker.setSelected(false); } } }); mResultTable.getTableHeader().setReorderingAllowed(false); mResultTableModel = new ResultTableModel(getMap().getCursorPosition(), getMindMapController()); getFreeMindMapController().addCursorPositionListener(mResultTableModel); mResultTableSorter = new TableSorter(mResultTableModel); mResultTable.setModel(mResultTableSorter); mResultTableSorter.setTableHeader(mResultTable.getTableHeader()); mResultTableSorter.setColumnComparator(String.class, TableSorter.LEXICAL_COMPARATOR); mResultTableSorter.setColumnComparator(Double.class, TableSorter.COMPARABLE_COMAPRATOR); // Sort by default by date. mResultTableSorter.setSortingStatus(SEARCH_DISTANCE_COLUMN, TableSorter.ASCENDING); clearButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent pE) { mResultTableModel.clear(); mSearchTerm.setText(""); mResultTable.setBackground(mTableOriginalBackgroundColor); } }); MouseListener mouseListener = new MouseAdapter() { public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { // int index = mResultTable.locationToIndex(e.getPoint()); int index = mResultTable.getSelectedRow(); displaySearchItem(mResultTableModel, index); } } }; mResultTable.addMouseListener(mouseListener); mSearchTerm.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent pE) { search(mSearchTerm.getText(), false); } }); final JScrollPane resultTableScrollPane = new JScrollPane(mResultTable); mSearchPanel.setLayout(new BorderLayout()); mSearchPanel.add(mSearchFieldPanel, BorderLayout.NORTH); mSearchPanel.add(resultTableScrollPane, BorderLayout.CENTER); mSearchBarVisible = true; mSearchSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, mSearchPanel, map); mSearchSplitPane.setContinuousLayout(true); mSearchSplitPane.setOneTouchExpandable(false); Tools.correctJSplitPaneKeyMap(); mSearchSplitPane.setResizeWeight(0d); mSearchSplitPane.addPropertyChangeListener( JSplitPane.DIVIDER_LOCATION_PROPERTY, new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent pEvt) { final int dividerLocation = mSearchSplitPane .getDividerLocation(); if (dividerLocation > 1) { mLastDividerPosition = dividerLocation; logger.info("Setting last divider to " + mLastDividerPosition); } } }); mMapDialog.add(mSearchSplitPane, BorderLayout.CENTER); mStatusLabel = new JLabel(" "); mMapDialog.add(mStatusLabel, BorderLayout.SOUTH); map.setCursorPosition(new Coordinate(49.8, 8.8)); map.setUseCursor(true); addMarkersToMap(); getRegistration().registerMapNodePositionListener(this); getRegistration().registerNodeVisibilityListener(this); getMindMapController().registerNodeSelectionListener(this, true); mMapDialog.validate(); // restore preferences: // Retrieve window size and column positions. MapWindowConfigurationStorage storage = (MapWindowConfigurationStorage) getMindMapController() .decorateDialog(mMapDialog, WINDOW_PREFERENCE_STORAGE_PROPERTY); if (storage != null) { // TODO: Better would be to store these data per map. map.setDisplayPositionByLatLon(storage.getMapCenterLatitude(), storage.getMapCenterLongitude(), storage.getZoom()); final Coordinate position = new Coordinate( storage.getCursorLatitude(), storage.getCursorLongitude()); getFreeMindMapController().setCursorPosition(position); FreeMindMapController .changeTileSource(storage.getTileSource(), map); map.setZoomContolsVisible(storage.getZoomControlsVisible()); map.setTileGridVisible(storage.getTileGridVisible()); map.setMapMarkerVisible(storage.getShowMapMarker()); map.setHideFoldedNodes(storage.getHideFoldedNodes()); int column = 0; for (Iterator i = storage.getListTableColumnSettingList() .iterator(); i.hasNext();) { TableColumnSetting setting = (TableColumnSetting) i.next(); mResultTable.getColumnModel().getColumn(column) .setPreferredWidth(setting.getColumnWidth()); mResultTableSorter.setSortingStatus(column, setting.getColumnSorting()); column++; } mLastDividerPosition = storage.getLastDividerPosition(); logger.info("Setting last divider to " + mLastDividerPosition); if (!storage.getSearchControlVisible()) { toggleSearchBar(); } else { mSearchSplitPane.setDividerLocation(mLastDividerPosition); } } mMapDialog.setVisible(true); getRegistration().setMapDialog(this); } public void addMarkersToMap() { // add known markers to the map. Set mapNodePositionHolders = getAllMapNodePositionHolders(); for (Iterator it = mapNodePositionHolders.iterator(); it.hasNext();) { MapNodePositionHolder nodePositionHolder = (MapNodePositionHolder) it .next(); boolean visible = !nodePositionHolder.hasFoldedParents(); changeVisibilityOfNode(nodePositionHolder, visible); } } protected void changeVisibilityOfNode( MapNodePositionHolder nodePositionHolder, boolean pVisible) { if (!pVisible && map.isHideFoldedNodes()) { removeMapMarker(nodePositionHolder); } else { addMapMarker(nodePositionHolder); } } public Registration getRegistration() { return (Registration) getPluginBaseClass(); } public void toggleSearchBar() { mSingleSearch = false; toggleSearchBar(null); } public void toggleSearchBar(AWTEvent pEvent) { if (mSearchBarVisible) { // hide search bar mLastDividerPosition = mSearchSplitPane.getDividerLocation(); logger.info("Setting last divider to " + mLastDividerPosition); mSearchSplitPane.setBottomComponent(null); mMapDialog.remove(mSearchSplitPane); mMapDialog.add(map, BorderLayout.CENTER); mSearchBarVisible = false; } else { // show search bar mMapDialog.remove(map); mMapDialog.add(mSearchSplitPane, BorderLayout.CENTER); mSearchSplitPane.setBottomComponent(map); mSearchSplitPane.setDividerLocation(mLastDividerPosition); focusSearchTerm(); mSearchBarVisible = true; } mMapDialog.validate(); if (pEvent != null) { mSearchTerm.setText(""); mSearchTerm.dispatchEvent(pEvent); /* Special for mac, as otherwise, everything is selected... GRRR. */ if (Tools.isMacOsX()) { EventQueue.invokeLater(new Runnable() { public void run() { mSearchTerm.setCaretPosition(mSearchTerm.getDocument() .getLength()); } }); } } } protected void focusSearchTerm() { mSearchTerm.selectAll(); mSearchTerm.requestFocusInWindow(); } /** * @return a set of MapNodePositionHolder elements of all nodes (even if * hidden) */ public Set getAllMapNodePositionHolders() { return getRegistration().getMapNodePositionHolders(); } /** * @return a set of MapNodePositionHolder elements to those nodes currently * displayed (ie. not hidden). */ public Set getMapNodePositionHolders() { return mMarkerMap.keySet(); } protected void addMapMarker(MapNodePositionHolder nodePositionHolder) { if (mMarkerMap.containsKey(nodePositionHolder)) { // already present. logger.fine("Node " + nodePositionHolder + " already present."); return; } Coordinate position = nodePositionHolder.getPosition(); logger.fine("Adding map position for " + nodePositionHolder.getNode() + " at " + position); MapMarkerLocation marker = new MapMarkerLocation(nodePositionHolder, this); map.addMapMarker(marker); mMarkerMap.put(nodePositionHolder, marker); } protected void removeMapMarker(MapNodePositionHolder pMapNodePositionHolder) { MapMarkerLocation marker = (MapMarkerLocation) mMarkerMap .remove(pMapNodePositionHolder); if (marker != null) { map.removeMapMarker(marker); } } /** * Overwritten, as this dialog is not modal, but after the plugin has * terminated, the dialog is still present and needs the controller to store * its values. * */ public MindMapController getMindMapController() { return mMyMindMapController; } public FreeMindMapController getFreeMindMapController() { return map.getFreeMindMapController(); } /** * */ public void disposeDialog() { Registration registration = (Registration) getPluginBaseClass(); if (registration != null) { // on close, it is null. Why? registration.setMapDialog(null); registration.deregisterMapNodePositionListener(this); registration.deregisterNodeVisibilityListener(this); } getMindMapController().deregisterNodeSelectionListener(this); // store window positions: MapWindowConfigurationStorage storage = new MapWindowConfigurationStorage(); // Set coordinates storage.setZoom(map.getZoom()); Coordinate position = map.getPosition(); storage.setMapCenterLongitude(position.getLon()); storage.setMapCenterLatitude(position.getLat()); Coordinate cursorPosition = map.getCursorPosition(); storage.setCursorLongitude(cursorPosition.getLon()); storage.setCursorLatitude(cursorPosition.getLat()); storage.setTileSource(map.getTileController().getTileSource() .getClass().getName()); storage.setTileGridVisible(map.isTileGridVisible()); storage.setZoomControlsVisible(map.getZoomContolsVisible()); storage.setShowMapMarker(map.getMapMarkersVisible()); storage.setSearchControlVisible(mSearchBarVisible); storage.setHideFoldedNodes(map.isHideFoldedNodes()); storage.setLastDividerPosition(mLastDividerPosition); for (int i = 0; i < mResultTable.getColumnCount(); i++) { TableColumnSetting setting = new TableColumnSetting(); setting.setColumnWidth(mResultTable.getColumnModel().getColumn(i) .getWidth()); setting.setColumnSorting(mResultTableSorter.getSortingStatus(i)); storage.addTableColumnSetting(setting); } getMindMapController().storeDialogPositions(mMapDialog, storage, WINDOW_PREFERENCE_STORAGE_PROPERTY); getMindMapController().getController().getMapModuleManager() .removeListener(this); mMapDialog.setVisible(false); mMapDialog.dispose(); } private void updateZoomParameters() { if (mperpLabelValue != null) mperpLabelValue.setText(format("%s", map.getMeterPerPixel())); if (zoomValue != null) zoomValue.setText(format("%s", map.getZoom())); } /** * @param pString * @param pMeterPerPixel * @return */ private String format(String pString, double pObject) { return "" + pObject; } public void processCommand(JMVCommandEvent command) { if (command.getCommand().equals(JMVCommandEvent.COMMAND.ZOOM) || command.getCommand().equals(JMVCommandEvent.COMMAND.MOVE)) { updateZoomParameters(); } } /* * (non-Javadoc) * * @see freemind.controller.MapModuleManager.MapModuleChangeObserver# * isMapModuleChangeAllowed(freemind.view.MapModule, freemind.modes.Mode, * freemind.view.MapModule, freemind.modes.Mode) */ public boolean isMapModuleChangeAllowed(MapModule pOldMapModule, Mode pOldMode, MapModule pNewMapModule, Mode pNewMode) { return true; } /* * (non-Javadoc) * * @see freemind.controller.MapModuleManager.MapModuleChangeObserver# * beforeMapModuleChange(freemind.view.MapModule, freemind.modes.Mode, * freemind.view.MapModule, freemind.modes.Mode) */ public void beforeMapModuleChange(MapModule pOldMapModule, Mode pOldMode, MapModule pNewMapModule, Mode pNewMode) { } /* * (non-Javadoc) * * @see * freemind.controller.MapModuleManager.MapModuleChangeObserver#afterMapClose * (freemind.view.MapModule, freemind.modes.Mode) */ public void afterMapClose(MapModule pOldMapModule, Mode pOldMode) { disposeDialog(); } /* * (non-Javadoc) * * @see freemind.controller.MapModuleManager.MapModuleChangeObserver# * afterMapModuleChange(freemind.view.MapModule, freemind.modes.Mode, * freemind.view.MapModule, freemind.modes.Mode) */ public void afterMapModuleChange(MapModule pOldMapModule, Mode pOldMode, MapModule pNewMapModule, Mode pNewMode) { disposeDialog(); } /* * (non-Javadoc) * * @see freemind.controller.MapModuleManager.MapModuleChangeObserver# * numberOfOpenMapInformation(int, int) */ public void numberOfOpenMapInformation(int pNumber, int pIndex) { } /* * (non-Javadoc) * * @see * plugins.map.MapNodePositionHolder.MapNodePositionListener#registerMapNode * (plugins.map.MapNodePositionHolder) */ public void registerMapNode(MapNodePositionHolder pMapNodePositionHolder) { addMapMarker(pMapNodePositionHolder); } /* * (non-Javadoc) * * @see * plugins.map.MapNodePositionHolder.MapNodePositionListener#deregisterMapNode * (plugins.map.MapNodePositionHolder) */ public void deregisterMapNode(MapNodePositionHolder pMapNodePositionHolder) { removeMapMarker(pMapNodePositionHolder); } /* * (non-Javadoc) * * @see * freemind.modes.ModeController.NodeSelectionListener#onUpdateNodeHook( * freemind.modes.MindMapNode) */ public void onUpdateNodeHook(MindMapNode pNode) { // update MapMarkerLocation if present: MapNodePositionHolder hook = MapNodePositionHolder.getHook(pNode); if (hook != null && mMarkerMap.containsKey(hook)) { MapMarkerLocation location = (MapMarkerLocation) mMarkerMap .get(hook); location.update(); location.repaint(); } } /* * (non-Javadoc) * * @see * freemind.modes.ModeController.NodeSelectionListener#onSelectHook(freemind * .view.mindmapview.NodeView) */ public void onFocusNode(NodeView pNode) { } public void selectMapPosition(NodeView pNode, boolean sel) { // test for map position: MapNodePositionHolder hook = MapNodePositionHolder.getHook(pNode .getModel()); if (hook != null) { if (mMarkerMap.containsKey(hook)) { MapMarkerLocation location = (MapMarkerLocation) mMarkerMap .get(hook); location.setSelected(sel); map.repaint(); } } } /* * (non-Javadoc) * * @see * freemind.modes.ModeController.NodeSelectionListener#onDeselectHook(freemind * .view.mindmapview.NodeView) */ public void onLostFocusNode(NodeView pNode) { } /* * (non-Javadoc) * * @see * freemind.modes.ModeController.NodeSelectionListener#onSaveNode(freemind * .modes.MindMapNode) */ public void onSaveNode(MindMapNode pNode) { } /* * (non-Javadoc) * * @see * freemind.modes.ModeController.NodeSelectionListener#onSelectionChange * (freemind.modes.MindMapNode, boolean) */ public void onSelectionChange(NodeView pNode, boolean pIsSelected) { selectMapPosition(pNode, pIsSelected); } public CloseAction getCloseAction() { return mCloseAction; } public boolean isSearchBarVisible() { return mSearchBarVisible; } /** * @return < MapNodePositionHolder, MapMarkerLocation > of those nodes * currently displayed (ie. not hidden) */ public Map getMarkerMap() { return Collections.unmodifiableMap(mMarkerMap); } public JCursorMapViewer getMap() { return map; } public void displaySearchItem(final ResultTableModel pResultTableModel, int index) { Place place = pResultTableModel.getPlace(index); getFreeMindMapController().setCursorPosition(place); if (mSingleSearch && isSearchBarVisible()) { toggleSearchBar(); } mSingleSearch = false; } public JDialog getMapDialog() { return mMapDialog; } /* * (non-Javadoc) * * @see * plugins.map.Registration.NodeVisibilityListener#nodeVisibilityChanged * (boolean) */ public void nodeVisibilityChanged( MapNodePositionHolder pMapNodePositionHolder, boolean pVisible) { changeVisibilityOfNode(pMapNodePositionHolder, pVisible); } public JLabel getStatusLabel() { return mStatusLabel; } public void search(String searchText, boolean pSelectFirstResult) { if (!isSearchBarVisible()) { toggleSearchBar(); } mSearchTerm.setText(searchText); boolean resultOk = getFreeMindMapController().search(mResultTableModel, mResultTable, searchText, mTableOriginalBackgroundColor); final int rowCount = mResultTableModel.getRowCount(); if (resultOk && pSelectFirstResult) { if (rowCount > 0) { displaySearchItem(mResultTableModel, 0); } } if (mSingleSearch && rowCount == 1) { displaySearchItem(mResultTableModel, 0); this.map.requestFocus(); return; } if (resultOk) { mResultTable.requestFocus(); } else { mSearchTerm.requestFocus(); } } /** * */ public void setSingleSearch() { mSingleSearch = true; } /** * @return */ public boolean isLimitSearchToRegion() { return mLimitSearchToRegion; } /** * */ public void toggleLimitSearchToRegion() { mLimitSearchToRegion = !mLimitSearchToRegion; if (mLimitSearchToRegion) { mSearchStringLabel.setText(mResourceSearchLocationString); } else { mSearchStringLabel.setText(mResourceSearchString); } mSearchStringLabel.validate(); } }
true
true
public void startupMapHook() { super.startupMapHook(); mMyMindMapController = super.getMindMapController(); getMindMapController().getController().getMapModuleManager() .addListener(this); mMapDialog = new JDialog(getController().getFrame().getJFrame(), false /* unmodal */); mMapDialog.setTitle(getResourceString("MapDialog_title")); mMapDialog .setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); mMapDialog.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent event) { disposeDialog(); } }); mCloseAction = new CloseAction(); // the action title is changed by the following method, thus we create // another close action. Tools.addEscapeActionToDialog(mMapDialog, new CloseAction()); mMapDialog.setSize(400, 400); map = new JCursorMapViewer(getMindMapController(), mMapDialog, getRegistration().getTileCache(), this); map.addJMVListener(this); FreeMindMapController.changeTileSource(Mapnik.class.getName(), map); OsmTileLoader loader = getRegistration().createTileLoader(map); map.setTileLoader(loader); mMapDialog.setLayout(new BorderLayout()); mSearchPanel = new JPanel(new BorderLayout()); mResourceSearchString = getResourceString("MapDialog_Search"); mResourceSearchLocationString = getResourceString("MapDialog_Search_Location"); mSearchStringLabel = new JLabel(mResourceSearchString); mSearchTerm = new JTextField(); mSearchTerm.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent pEvent) { if (pEvent.getKeyCode() == KeyEvent.VK_DOWN && pEvent.getModifiers() == 0) { logger.info("Set Focus to search list."); mResultTable.requestFocusInWindow(); mResultTable.getSelectionModel().setSelectionInterval(0, 0); pEvent.consume(); } } }); mSearchTerm.addKeyListener(getFreeMindMapController()); mSearchFieldPanel = new JPanel(); mSearchFieldPanel.setLayout(new BorderLayout(10, 0)); JButton clearButton = new JButton(new ImageIcon(Resources.getInstance() .getResource("images/clear_box.png"))); clearButton.setFocusable(false); mSearchFieldPanel.add(mSearchStringLabel, BorderLayout.WEST); mSearchFieldPanel.add(mSearchTerm, BorderLayout.CENTER); mSearchFieldPanel.add(clearButton, BorderLayout.EAST); mResultTable = new JTable(); mTableOriginalBackgroundColor = mResultTable.getBackground(); mResultTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); mResultTable.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent pEvent) { int index = mResultTable.getSelectedRow(); if (index == 0 && pEvent.getKeyCode() == KeyEvent.VK_UP && pEvent.getModifiers() == 0) { logger.info("Set Focus to search item."); mResultTable.clearSelection(); mSearchTerm.requestFocusInWindow(); pEvent.consume(); return; } if (pEvent.getKeyCode() == KeyEvent.VK_ENTER && pEvent.getModifiers() == 0) { logger.info("Set result in map."); pEvent.consume(); displaySearchItem(mResultTableModel, index); return; } } }); mResultTable.addKeyListener(getFreeMindMapController()); mResultTable.getSelectionModel().addListSelectionListener( new ListSelectionListener() { public void valueChanged(ListSelectionEvent pE) { clearIndexes(); final int selectedRow = mResultTable.getSelectedRow(); if (selectedRow >= 0 && selectedRow < mResultTableSorter .getRowCount()) { int index = selectedRow; index = mResultTableSorter.modelIndex(index); MapSearchMarkerLocation marker = mResultTableModel .getMapSearchMarkerLocation(index); marker.setSelected(true); } mResultTable.repaint(); } private void clearIndexes() { for (int i = 0; i < mResultTableModel.getRowCount(); i++) { MapSearchMarkerLocation marker = mResultTableModel .getMapSearchMarkerLocation(i); marker.setSelected(false); } } }); mResultTable.getTableHeader().setReorderingAllowed(false); mResultTableModel = new ResultTableModel(getMap().getCursorPosition(), getMindMapController()); getFreeMindMapController().addCursorPositionListener(mResultTableModel); mResultTableSorter = new TableSorter(mResultTableModel); mResultTable.setModel(mResultTableSorter); mResultTableSorter.setTableHeader(mResultTable.getTableHeader()); mResultTableSorter.setColumnComparator(String.class, TableSorter.LEXICAL_COMPARATOR); mResultTableSorter.setColumnComparator(Double.class, TableSorter.COMPARABLE_COMAPRATOR); // Sort by default by date. mResultTableSorter.setSortingStatus(SEARCH_DISTANCE_COLUMN, TableSorter.ASCENDING); clearButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent pE) { mResultTableModel.clear(); mSearchTerm.setText(""); mResultTable.setBackground(mTableOriginalBackgroundColor); } }); MouseListener mouseListener = new MouseAdapter() { public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { // int index = mResultTable.locationToIndex(e.getPoint()); int index = mResultTable.getSelectedRow(); displaySearchItem(mResultTableModel, index); } } }; mResultTable.addMouseListener(mouseListener); mSearchTerm.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent pE) { search(mSearchTerm.getText(), false); } }); final JScrollPane resultTableScrollPane = new JScrollPane(mResultTable); mSearchPanel.setLayout(new BorderLayout()); mSearchPanel.add(mSearchFieldPanel, BorderLayout.NORTH); mSearchPanel.add(resultTableScrollPane, BorderLayout.CENTER); mSearchBarVisible = true; mSearchSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, mSearchPanel, map); mSearchSplitPane.setContinuousLayout(true); mSearchSplitPane.setOneTouchExpandable(false); Tools.correctJSplitPaneKeyMap(); mSearchSplitPane.setResizeWeight(0d); mSearchSplitPane.addPropertyChangeListener( JSplitPane.DIVIDER_LOCATION_PROPERTY, new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent pEvt) { final int dividerLocation = mSearchSplitPane .getDividerLocation(); if (dividerLocation > 1) { mLastDividerPosition = dividerLocation; logger.info("Setting last divider to " + mLastDividerPosition); } } }); mMapDialog.add(mSearchSplitPane, BorderLayout.CENTER); mStatusLabel = new JLabel(" "); mMapDialog.add(mStatusLabel, BorderLayout.SOUTH); map.setCursorPosition(new Coordinate(49.8, 8.8)); map.setUseCursor(true); addMarkersToMap(); getRegistration().registerMapNodePositionListener(this); getRegistration().registerNodeVisibilityListener(this); getMindMapController().registerNodeSelectionListener(this, true); mMapDialog.validate(); // restore preferences: // Retrieve window size and column positions. MapWindowConfigurationStorage storage = (MapWindowConfigurationStorage) getMindMapController() .decorateDialog(mMapDialog, WINDOW_PREFERENCE_STORAGE_PROPERTY); if (storage != null) { // TODO: Better would be to store these data per map. map.setDisplayPositionByLatLon(storage.getMapCenterLatitude(), storage.getMapCenterLongitude(), storage.getZoom()); final Coordinate position = new Coordinate( storage.getCursorLatitude(), storage.getCursorLongitude()); getFreeMindMapController().setCursorPosition(position); FreeMindMapController .changeTileSource(storage.getTileSource(), map); map.setZoomContolsVisible(storage.getZoomControlsVisible()); map.setTileGridVisible(storage.getTileGridVisible()); map.setMapMarkerVisible(storage.getShowMapMarker()); map.setHideFoldedNodes(storage.getHideFoldedNodes()); int column = 0; for (Iterator i = storage.getListTableColumnSettingList() .iterator(); i.hasNext();) { TableColumnSetting setting = (TableColumnSetting) i.next(); mResultTable.getColumnModel().getColumn(column) .setPreferredWidth(setting.getColumnWidth()); mResultTableSorter.setSortingStatus(column, setting.getColumnSorting()); column++; } mLastDividerPosition = storage.getLastDividerPosition(); logger.info("Setting last divider to " + mLastDividerPosition); if (!storage.getSearchControlVisible()) { toggleSearchBar(); } else { mSearchSplitPane.setDividerLocation(mLastDividerPosition); } } mMapDialog.setVisible(true); getRegistration().setMapDialog(this); }
public void startupMapHook() { super.startupMapHook(); mMyMindMapController = super.getMindMapController(); getMindMapController().getController().getMapModuleManager() .addListener(this); mMapDialog = new JDialog(getController().getFrame().getJFrame(), false /* unmodal */); mMapDialog.setTitle(getResourceString("MapDialog_title")); mMapDialog .setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); mMapDialog.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent event) { disposeDialog(); } }); mCloseAction = new CloseAction(); // the action title is changed by the following method, thus we create // another close action. Tools.addEscapeActionToDialog(mMapDialog, new CloseAction()); mMapDialog.setSize(400, 400); map = new JCursorMapViewer(getMindMapController(), mMapDialog, getRegistration().getTileCache(), this); map.addJMVListener(this); FreeMindMapController.changeTileSource(Mapnik.class.getName(), map); OsmTileLoader loader = getRegistration().createTileLoader(map); map.setTileLoader(loader); mMapDialog.setLayout(new BorderLayout()); mSearchPanel = new JPanel(new BorderLayout()); mResourceSearchString = getResourceString("MapDialog_Search"); mResourceSearchLocationString = getResourceString("MapDialog_Search_Location"); mSearchStringLabel = new JLabel(mResourceSearchString); mSearchTerm = new JTextField(); mSearchTerm.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent pEvent) { if (pEvent.getKeyCode() == KeyEvent.VK_DOWN && pEvent.getModifiers() == 0) { logger.info("Set Focus to search list."); mResultTable.requestFocusInWindow(); mResultTable.getSelectionModel().setSelectionInterval(0, 0); pEvent.consume(); } } }); mSearchTerm.addKeyListener(getFreeMindMapController()); mSearchFieldPanel = new JPanel(); mSearchFieldPanel.setLayout(new BorderLayout(10, 0)); JButton clearButton = new JButton(new ImageIcon(Resources.getInstance() .getResource("images/clear_box.png"))); clearButton.setFocusable(false); mSearchFieldPanel.add(mSearchStringLabel, BorderLayout.WEST); mSearchFieldPanel.add(mSearchTerm, BorderLayout.CENTER); mSearchFieldPanel.add(clearButton, BorderLayout.EAST); mResultTable = new JTable(); mTableOriginalBackgroundColor = mResultTable.getBackground(); mResultTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); mResultTable.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent pEvent) { int index = mResultTable.getSelectedRow(); if (index == 0 && pEvent.getKeyCode() == KeyEvent.VK_UP && pEvent.getModifiers() == 0) { logger.info("Set Focus to search item."); mResultTable.clearSelection(); mSearchTerm.requestFocusInWindow(); pEvent.consume(); return; } if (pEvent.getKeyCode() == KeyEvent.VK_ENTER && pEvent.getModifiers() == 0) { logger.info("Set result in map."); pEvent.consume(); displaySearchItem(mResultTableModel, index); return; } } }); mResultTable.addKeyListener(getFreeMindMapController()); mResultTable.getSelectionModel().addListSelectionListener( new ListSelectionListener() { public void valueChanged(ListSelectionEvent pE) { clearIndexes(); final int selectedRow = mResultTable.getSelectedRow(); if (selectedRow >= 0 && selectedRow < mResultTableSorter .getRowCount()) { int index = selectedRow; index = mResultTableSorter.modelIndex(index); MapSearchMarkerLocation marker = mResultTableModel .getMapSearchMarkerLocation(index); marker.setSelected(true); } mResultTable.repaint(); getMap().repaint(); } private void clearIndexes() { for (int i = 0; i < mResultTableModel.getRowCount(); i++) { MapSearchMarkerLocation marker = mResultTableModel .getMapSearchMarkerLocation(i); marker.setSelected(false); } } }); mResultTable.getTableHeader().setReorderingAllowed(false); mResultTableModel = new ResultTableModel(getMap().getCursorPosition(), getMindMapController()); getFreeMindMapController().addCursorPositionListener(mResultTableModel); mResultTableSorter = new TableSorter(mResultTableModel); mResultTable.setModel(mResultTableSorter); mResultTableSorter.setTableHeader(mResultTable.getTableHeader()); mResultTableSorter.setColumnComparator(String.class, TableSorter.LEXICAL_COMPARATOR); mResultTableSorter.setColumnComparator(Double.class, TableSorter.COMPARABLE_COMAPRATOR); // Sort by default by date. mResultTableSorter.setSortingStatus(SEARCH_DISTANCE_COLUMN, TableSorter.ASCENDING); clearButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent pE) { mResultTableModel.clear(); mSearchTerm.setText(""); mResultTable.setBackground(mTableOriginalBackgroundColor); } }); MouseListener mouseListener = new MouseAdapter() { public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { // int index = mResultTable.locationToIndex(e.getPoint()); int index = mResultTable.getSelectedRow(); displaySearchItem(mResultTableModel, index); } } }; mResultTable.addMouseListener(mouseListener); mSearchTerm.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent pE) { search(mSearchTerm.getText(), false); } }); final JScrollPane resultTableScrollPane = new JScrollPane(mResultTable); mSearchPanel.setLayout(new BorderLayout()); mSearchPanel.add(mSearchFieldPanel, BorderLayout.NORTH); mSearchPanel.add(resultTableScrollPane, BorderLayout.CENTER); mSearchBarVisible = true; mSearchSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, mSearchPanel, map); mSearchSplitPane.setContinuousLayout(true); mSearchSplitPane.setOneTouchExpandable(false); Tools.correctJSplitPaneKeyMap(); mSearchSplitPane.setResizeWeight(0d); mSearchSplitPane.addPropertyChangeListener( JSplitPane.DIVIDER_LOCATION_PROPERTY, new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent pEvt) { final int dividerLocation = mSearchSplitPane .getDividerLocation(); if (dividerLocation > 1) { mLastDividerPosition = dividerLocation; logger.info("Setting last divider to " + mLastDividerPosition); } } }); mMapDialog.add(mSearchSplitPane, BorderLayout.CENTER); mStatusLabel = new JLabel(" "); mMapDialog.add(mStatusLabel, BorderLayout.SOUTH); map.setCursorPosition(new Coordinate(49.8, 8.8)); map.setUseCursor(true); addMarkersToMap(); getRegistration().registerMapNodePositionListener(this); getRegistration().registerNodeVisibilityListener(this); getMindMapController().registerNodeSelectionListener(this, true); mMapDialog.validate(); // restore preferences: // Retrieve window size and column positions. MapWindowConfigurationStorage storage = (MapWindowConfigurationStorage) getMindMapController() .decorateDialog(mMapDialog, WINDOW_PREFERENCE_STORAGE_PROPERTY); if (storage != null) { // TODO: Better would be to store these data per map. map.setDisplayPositionByLatLon(storage.getMapCenterLatitude(), storage.getMapCenterLongitude(), storage.getZoom()); final Coordinate position = new Coordinate( storage.getCursorLatitude(), storage.getCursorLongitude()); getFreeMindMapController().setCursorPosition(position); FreeMindMapController .changeTileSource(storage.getTileSource(), map); map.setZoomContolsVisible(storage.getZoomControlsVisible()); map.setTileGridVisible(storage.getTileGridVisible()); map.setMapMarkerVisible(storage.getShowMapMarker()); map.setHideFoldedNodes(storage.getHideFoldedNodes()); int column = 0; for (Iterator i = storage.getListTableColumnSettingList() .iterator(); i.hasNext();) { TableColumnSetting setting = (TableColumnSetting) i.next(); mResultTable.getColumnModel().getColumn(column) .setPreferredWidth(setting.getColumnWidth()); mResultTableSorter.setSortingStatus(column, setting.getColumnSorting()); column++; } mLastDividerPosition = storage.getLastDividerPosition(); logger.info("Setting last divider to " + mLastDividerPosition); if (!storage.getSearchControlVisible()) { toggleSearchBar(); } else { mSearchSplitPane.setDividerLocation(mLastDividerPosition); } } mMapDialog.setVisible(true); getRegistration().setMapDialog(this); }
diff --git a/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/DefaultArtifactResolver.java b/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/DefaultArtifactResolver.java index 896306952..eec243d31 100644 --- a/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/DefaultArtifactResolver.java +++ b/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/DefaultArtifactResolver.java @@ -1,299 +1,299 @@ package org.apache.maven.artifact.resolver; import org.apache.maven.artifact.AbstractArtifactComponent; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.resolver.filter.ArtifactFilter; import org.apache.maven.artifact.handler.manager.ArtifactHandlerNotFoundException; import org.apache.maven.artifact.manager.WagonManager; import org.apache.maven.artifact.metadata.ArtifactMetadataRetrievalException; import org.apache.maven.artifact.metadata.ArtifactMetadataSource; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.wagon.TransferFailedException; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; public class DefaultArtifactResolver extends AbstractArtifactComponent implements ArtifactResolver { private WagonManager wagonManager; public Artifact resolve( Artifact artifact, Set remoteRepositories, ArtifactRepository localRepository ) throws ArtifactResolutionException { // ---------------------------------------------------------------------- // Perform any transformation on the artifacts // ---------------------------------------------------------------------- // ---------------------------------------------------------------------- // Check for the existence of the artifact in the specified local // ArtifactRepository. If it is present then simply return as the request // for resolution has been satisfied. // ---------------------------------------------------------------------- try { setLocalRepositoryPath( artifact, localRepository ); if ( artifact.exists() ) { return artifact; } wagonManager.get( artifact, remoteRepositories, localRepository ); } catch ( ArtifactHandlerNotFoundException e ) { throw new ArtifactResolutionException( "Error resolving artifact: ", e ); } catch ( TransferFailedException e ) { throw new ArtifactResolutionException( artifactNotFound( artifact, remoteRepositories ), e ); } return artifact; } private String LS = System.getProperty( "line.separator" ); private String artifactNotFound( Artifact artifact, Set remoteRepositories ) { StringBuffer sb = new StringBuffer(); sb.append( "The artifact is not present locally as:" ) .append( LS ) .append( LS ) .append( artifact.getPath() ) .append( LS ) .append( LS ) .append( "or in any of the specified remote repositories:" ) .append( LS ) .append( LS ); for ( Iterator i = remoteRepositories.iterator(); i.hasNext(); ) { ArtifactRepository remoteRepository = (ArtifactRepository) i.next(); sb.append( remoteRepository.getUrl() ); if ( i.hasNext() ) { sb.append( ", " ); } } return sb.toString(); } public Set resolve( Set artifacts, Set remoteRepositories, ArtifactRepository localRepository ) throws ArtifactResolutionException { Set resolvedArtifacts = new HashSet(); for ( Iterator i = artifacts.iterator(); i.hasNext(); ) { Artifact artifact = (Artifact) i.next(); Artifact resolvedArtifact = resolve( artifact, remoteRepositories, localRepository ); resolvedArtifacts.add( resolvedArtifact ); } return resolvedArtifacts; } // ---------------------------------------------------------------------- // Transitive modes // ---------------------------------------------------------------------- public ArtifactResolutionResult resolveTransitively( Set artifacts, Set remoteRepositories, ArtifactRepository localRepository, ArtifactMetadataSource source, ArtifactFilter filter ) throws ArtifactResolutionException { ArtifactResolutionResult artifactResolutionResult; try { artifactResolutionResult = collect( artifacts, localRepository, remoteRepositories, source, filter ); } catch ( TransitiveArtifactResolutionException e ) { throw new ArtifactResolutionException( "Error transitively resolving artifacts: ", e ); } for ( Iterator i = artifactResolutionResult.getArtifacts().values().iterator(); i.hasNext(); ) { resolve( (Artifact) i.next(), remoteRepositories, localRepository ); } return artifactResolutionResult; } public ArtifactResolutionResult resolveTransitively( Set artifacts, Set remoteRepositories, ArtifactRepository localRepository, ArtifactMetadataSource source ) throws ArtifactResolutionException { return resolveTransitively( artifacts, remoteRepositories, localRepository, source, null ); } public ArtifactResolutionResult resolveTransitively( Artifact artifact, Set remoteRepositories, ArtifactRepository localRepository, ArtifactMetadataSource source ) throws ArtifactResolutionException { Set s = new HashSet(); s.add( artifact ); return resolveTransitively( s, remoteRepositories, localRepository, source ); } // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- protected ArtifactResolutionResult collect( Set artifacts, ArtifactRepository localRepository, Set remoteRepositories, ArtifactMetadataSource source, ArtifactFilter filter ) throws TransitiveArtifactResolutionException { ArtifactResolutionResult result = new ArtifactResolutionResult(); Map resolvedArtifacts = new HashMap(); List queue = new LinkedList(); queue.add( artifacts ); while ( !queue.isEmpty() ) { Set currentArtifacts = (Set) queue.remove( 0 ); for ( Iterator i = currentArtifacts.iterator(); i.hasNext(); ) { Artifact newArtifact = (Artifact) i.next(); String id = newArtifact.getConflictId(); if ( resolvedArtifacts.containsKey( id ) ) { Artifact knownArtifact = (Artifact) resolvedArtifacts.get( id ); String newVersion = newArtifact.getVersion(); String knownVersion = knownArtifact.getVersion(); if ( !newVersion.equals( knownVersion ) ) { addConflict( result, knownArtifact, newArtifact ); } } else { // ---------------------------------------------------------------------- // It's the first time we have encountered this artifact // ---------------------------------------------------------------------- if ( filter != null && !filter.include( newArtifact.getArtifactId() ) ) { continue; } resolvedArtifacts.put( id, newArtifact ); Set referencedDependencies = null; try { referencedDependencies = source.retrieve( newArtifact ); } catch ( ArtifactMetadataRetrievalException e ) { - throw new TransitiveArtifactResolutionException( "Error retrieving metadata: ", e ); + throw new TransitiveArtifactResolutionException( "Error retrieving metadata [" + newArtifact + "] : ", e ); } // the pom for given dependency exisit we will add it to the queue queue.add( referencedDependencies ); } } } // ---------------------------------------------------------------------- // the dependencies list is keyed by groupId+artifactId+type // so it must be 'rekeyed' to the complete id: groupId+artifactId+type+version // ---------------------------------------------------------------------- Map artifactResult = result.getArtifacts(); for ( Iterator it = resolvedArtifacts.values().iterator(); it.hasNext(); ) { Artifact artifact = (Artifact) it.next(); try { setLocalRepositoryPath( artifact, localRepository ); } catch ( ArtifactHandlerNotFoundException e ) { throw new TransitiveArtifactResolutionException( "Error collecting artifact: ", e ); } artifactResult.put( artifact.getId(), artifact ); } return result; } private void addConflict( ArtifactResolutionResult result, Artifact knownArtifact, Artifact newArtifact ) { List conflicts; conflicts = (List) result.getConflicts().get( newArtifact.getConflictId() ); if ( conflicts == null ) { conflicts = new LinkedList(); conflicts.add( knownArtifact ); result.getConflicts().put( newArtifact.getConflictId(), conflicts ); } conflicts.add( newArtifact ); } protected boolean includeArtifact( String artifactId, String[] artifactExcludes ) { for ( int b = 0; b < artifactExcludes.length; b++ ) { if ( artifactId.equals( artifactExcludes[b] ) ) { return false; } } return true; } }
true
true
protected ArtifactResolutionResult collect( Set artifacts, ArtifactRepository localRepository, Set remoteRepositories, ArtifactMetadataSource source, ArtifactFilter filter ) throws TransitiveArtifactResolutionException { ArtifactResolutionResult result = new ArtifactResolutionResult(); Map resolvedArtifacts = new HashMap(); List queue = new LinkedList(); queue.add( artifacts ); while ( !queue.isEmpty() ) { Set currentArtifacts = (Set) queue.remove( 0 ); for ( Iterator i = currentArtifacts.iterator(); i.hasNext(); ) { Artifact newArtifact = (Artifact) i.next(); String id = newArtifact.getConflictId(); if ( resolvedArtifacts.containsKey( id ) ) { Artifact knownArtifact = (Artifact) resolvedArtifacts.get( id ); String newVersion = newArtifact.getVersion(); String knownVersion = knownArtifact.getVersion(); if ( !newVersion.equals( knownVersion ) ) { addConflict( result, knownArtifact, newArtifact ); } } else { // ---------------------------------------------------------------------- // It's the first time we have encountered this artifact // ---------------------------------------------------------------------- if ( filter != null && !filter.include( newArtifact.getArtifactId() ) ) { continue; } resolvedArtifacts.put( id, newArtifact ); Set referencedDependencies = null; try { referencedDependencies = source.retrieve( newArtifact ); } catch ( ArtifactMetadataRetrievalException e ) { throw new TransitiveArtifactResolutionException( "Error retrieving metadata: ", e ); } // the pom for given dependency exisit we will add it to the queue queue.add( referencedDependencies ); } } } // ---------------------------------------------------------------------- // the dependencies list is keyed by groupId+artifactId+type // so it must be 'rekeyed' to the complete id: groupId+artifactId+type+version // ---------------------------------------------------------------------- Map artifactResult = result.getArtifacts(); for ( Iterator it = resolvedArtifacts.values().iterator(); it.hasNext(); ) { Artifact artifact = (Artifact) it.next(); try { setLocalRepositoryPath( artifact, localRepository ); } catch ( ArtifactHandlerNotFoundException e ) { throw new TransitiveArtifactResolutionException( "Error collecting artifact: ", e ); } artifactResult.put( artifact.getId(), artifact ); } return result; }
protected ArtifactResolutionResult collect( Set artifacts, ArtifactRepository localRepository, Set remoteRepositories, ArtifactMetadataSource source, ArtifactFilter filter ) throws TransitiveArtifactResolutionException { ArtifactResolutionResult result = new ArtifactResolutionResult(); Map resolvedArtifacts = new HashMap(); List queue = new LinkedList(); queue.add( artifacts ); while ( !queue.isEmpty() ) { Set currentArtifacts = (Set) queue.remove( 0 ); for ( Iterator i = currentArtifacts.iterator(); i.hasNext(); ) { Artifact newArtifact = (Artifact) i.next(); String id = newArtifact.getConflictId(); if ( resolvedArtifacts.containsKey( id ) ) { Artifact knownArtifact = (Artifact) resolvedArtifacts.get( id ); String newVersion = newArtifact.getVersion(); String knownVersion = knownArtifact.getVersion(); if ( !newVersion.equals( knownVersion ) ) { addConflict( result, knownArtifact, newArtifact ); } } else { // ---------------------------------------------------------------------- // It's the first time we have encountered this artifact // ---------------------------------------------------------------------- if ( filter != null && !filter.include( newArtifact.getArtifactId() ) ) { continue; } resolvedArtifacts.put( id, newArtifact ); Set referencedDependencies = null; try { referencedDependencies = source.retrieve( newArtifact ); } catch ( ArtifactMetadataRetrievalException e ) { throw new TransitiveArtifactResolutionException( "Error retrieving metadata [" + newArtifact + "] : ", e ); } // the pom for given dependency exisit we will add it to the queue queue.add( referencedDependencies ); } } } // ---------------------------------------------------------------------- // the dependencies list is keyed by groupId+artifactId+type // so it must be 'rekeyed' to the complete id: groupId+artifactId+type+version // ---------------------------------------------------------------------- Map artifactResult = result.getArtifacts(); for ( Iterator it = resolvedArtifacts.values().iterator(); it.hasNext(); ) { Artifact artifact = (Artifact) it.next(); try { setLocalRepositoryPath( artifact, localRepository ); } catch ( ArtifactHandlerNotFoundException e ) { throw new TransitiveArtifactResolutionException( "Error collecting artifact: ", e ); } artifactResult.put( artifact.getId(), artifact ); } return result; }
diff --git a/src/ZoneDessin.java b/src/ZoneDessin.java index bf95f9e..88d20c3 100755 --- a/src/ZoneDessin.java +++ b/src/ZoneDessin.java @@ -1,354 +1,354 @@ import java.awt.BasicStroke; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseWheelEvent; import java.awt.event.MouseWheelListener; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.JPanel; import javax.swing.event.MouseInputAdapter; @SuppressWarnings("serial") public class ZoneDessin extends JPanel{ int largeurDessin; //La largeur de la zone de dessin int hauteurDessin; //La longueur de la zone de dessin Color background; Curseur curseur; //Les bords de la zones de dessin int ecartHorizontal; int ecartVertical; Controleur c; BarreOutils barreOutils; private int clicSouris;//1 : Clic gauche, 3 : Clic Droit private Controleur controleur; /** * Constructeur de la zone de dessin */ ZoneDessin(int largeurDessin, int hauteurDessin, Color background, Curseur curseur){ this.largeurDessin = largeurDessin; this.hauteurDessin = hauteurDessin; this.background = background; this.curseur = curseur; this.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { clicSouris = e.getButton(); clicSouris(e.getX(), e.getY()); } }); this.addMouseMotionListener(new MouseInputAdapter(){ public void mouseDragged(MouseEvent e) { if(clicSouris == 1) clicSouris(e.getX(), e.getY()); } }); this.addMouseWheelListener(new MouseWheelListener(){ public void mouseWheelMoved(MouseWheelEvent e) { barreOutils.interactionSliderEpaisseur(-e.getWheelRotation()*4); } }); } public void clicSouris(int posX, int posY){ switch(clicSouris){ case 1 : //if((posX > ecartHorizontal - 30) && (posX < ecartHorizontal + largeurDessin + 30) && (posY > ecartVertical - 30) && (posY < ecartVertical + hauteurDessin + 30)){ int posX_final = (posX - ecartHorizontal < 0) ? 0 : (posX - ecartHorizontal > this.getLargeurDessin()) ? this.getLargeurDessin() : (posX - ecartHorizontal); int posY_final = (posY - ecartVertical < 0) ? 0 : (posY - ecartVertical > this.getHauteurDessin()) ? this.getHauteurDessin() : (posY - ecartVertical); c.commande("goto " + posX_final + " " + posY_final, true ); repaint(); //} break; case 2 : barreOutils.interactionBoutonOutil(); break; case 3 : barreOutils.interactionBoutonPoserOutil(); break; } } /** * Methode dessinant la zone de dessin puis le curseur */ public void paintComponent(Graphics gd){ Graphics2D g = (Graphics2D)gd; //Calcul de l'ecart de la zone de dessin pour centrer le dessin ecartHorizontal = (this.getWidth() - largeurDessin)/2; ecartVertical = (this.getHeight() - hauteurDessin)/2; //ETAPE 1 : Afficher la zone de dessin g.setColor(background);//Couleur de fond du dessin g.fillRect(ecartHorizontal, ecartVertical, this.largeurDessin, this.hauteurDessin); //ETAPE 2 : Afficher les traceurs Traceur t; for (int i = 0; i < StockageDonnee.liste_dessin.size(); i ++){ t = StockageDonnee.liste_dessin.get(i); //Initialisons les propriétés de l'objet graphics g.setColor(t.getColor()); int cap; int join; if(t.getForme() == 0){ cap = BasicStroke.CAP_ROUND; join = BasicStroke.JOIN_ROUND; } else{ cap = BasicStroke.CAP_BUTT; join = BasicStroke.CAP_ROUND; } g.setStroke(new BasicStroke(t.getEpaisseur(), cap, join)); /*System.out.println("Position X Début : " + posXAbsolue(t.getXOrigine())); System.out.println("Position Y Début : " + posYAbsolue(t.getYOrigine())); System.out.println("Position X Fin : " + posXAbsolue(t.getXArrivee())); System.out.println("Position Y Fin : " + posYAbsolue(t.getYArrivee())); System.out.println("Couleur Curseur : " + t.getColor()); System.out.println("Epaisseur : " + t.getEpaisseur()); */ //Si le t est une droite/point if (t.getType() == 1 || t.getType() == 0){ if(t.getForme() == 0) g.drawLine(posXAbsolue(t.getXOrigine()), posYAbsolue(t.getYOrigine()), posXAbsolue(t.getXArrivee()), posYAbsolue(t.getYArrivee())); //Dans le cas d'une forme carré, on va dessiner des carré aux points de départ/arrivée pour un effet pls propre else{ g.setStroke(new BasicStroke()); g.fillRect(posXAbsolue(t.getXOrigine()) - t.getEpaisseur()/2, posYAbsolue(t.getYOrigine()) - t.getEpaisseur()/2, t.getEpaisseur(), t.getEpaisseur()); g.fillRect(posXAbsolue(t.getXArrivee()) - t.getEpaisseur()/2, posYAbsolue(t.getYArrivee()) - t.getEpaisseur()/2, t.getEpaisseur(), t.getEpaisseur()); //Et on trace deux version du trait entre les points (en fait si on ne laisse qu'une seule des deux version, certains angles seront mal déssiné int[] x = {posXAbsolue(t.getXOrigine()) - t.getEpaisseur()/2, posXAbsolue(t.getXArrivee()) - t.getEpaisseur()/2, posXAbsolue(t.getXArrivee()) + t.getEpaisseur()/2, posXAbsolue(t.getXOrigine()) + t.getEpaisseur()/2 }; int[] y = {posYAbsolue(t.getYOrigine()) - t.getEpaisseur()/2, posYAbsolue(t.getYArrivee()) - t.getEpaisseur()/2, posYAbsolue(t.getYArrivee()) + t.getEpaisseur()/2, posYAbsolue(t.getYOrigine()) + t.getEpaisseur()/2 }; g.fillPolygon(x, y, 4); int[] x2 = {posXAbsolue(t.getXOrigine()) + t.getEpaisseur()/2, posXAbsolue(t.getXArrivee()) + t.getEpaisseur()/2, posXAbsolue(t.getXArrivee()) - t.getEpaisseur()/2, posXAbsolue(t.getXOrigine()) - t.getEpaisseur()/2 }; g.fillPolygon(x2, y, 4); } } //Si le t est un Rectangle else if (t.getType() == 2){ //On va faire une boucle qui dessin des triangle successifs selon l'epaisseur du curseur if(t.estRempli()){ g.fillRect(posXAbsolue(t.getXOrigine()), posYAbsolue(t.getYOrigine()), t.getLargeur(), t.getHauteur()); - } + } else{ g.drawRect(posXAbsolue(posXAbsolue(t.getXOrigine()) - t.getEpaisseur()), posYAbsolue(t.getYOrigine()) - t.getEpaisseur(), t.getLargeur() + t.getEpaisseur(), t.getHauteur() + t.getEpaisseur()); } } //Si le t est un triangle else if (t.getType() == 3){ int[] x = {posXAbsolue(t.getXOrigine()), posXAbsolue(t.getXArrivee()), posXAbsolue(t.getX3())}; int[] y = {posYAbsolue(t.getYOrigine()), posYAbsolue(t.getYArrivee()), posYAbsolue(t.getY3())}; if(!t.estRempli()){ g.fillPolygon(x, y, 3); } else{ g.drawPolygon(x, y, 3); } } //Si le t est un Cercle else if (t.getType() == 4){ //On va faire une boucle qui dessin des triangle successifs selon l'epaisseur du curseur if(!t.estRempli()){ g.fillOval(posXAbsolue(t.getXOrigine()), posYAbsolue(t.getYOrigine()), t.getLargeur(), t.getHauteur()); } else{ g.drawOval(posXAbsolue(t.getXOrigine()), posYAbsolue(t.getYOrigine()), t.getLargeur(), t.getHauteur()); } } //Si le t est une image else if(t.getType() == 5){ try { Image img = ImageIO.read(new File(t.getPath())); g.drawImage(img, ecartHorizontal, ecartVertical, this); //Pour une image de fond //g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), this); } catch (IOException e) { e.printStackTrace(); } } } //DESSINONS LE FOND g.setStroke(new BasicStroke()); //Fond de la zone de dessin g.setColor(new Color(180,180,180));//Couleur de fond g.fillRect(0, 0, ecartHorizontal, this.getHeight());//On défini une couleur derriere le dessin pour eviter les glitch graphiques g.fillRect(ecartHorizontal + largeurDessin, 0, this.getWidth(), this.getHeight()); g.fillRect(ecartHorizontal - 1, 0, largeurDessin + 1, ecartVertical); g.fillRect(ecartHorizontal - 1, hauteurDessin + ecartVertical, largeurDessin + 1, ecartVertical+1); //Ombre du dessin g.setColor(new Color(220,220,220)); g.fillRect(ecartHorizontal + largeurDessin, ecartVertical + 5, 5, hauteurDessin); g.fillRect(ecartHorizontal + 5, ecartVertical + hauteurDessin, largeurDessin, 5); //ETAPE 3 : Afficher le curseur //Deux curseurs à afficher : le curseur négatif (pour plus de lisibilité) et le curseur normal //Forme du curseur en fonction de l'outil BasicStroke forme; if(curseur.getType() == 0){ forme = new BasicStroke(0); } else{ float[] dashArray = {2, 2}; forme = new BasicStroke(0, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 0, dashArray, 0); } g.setStroke(forme); //AFFICHAGE DE LA BASE DU CURSEUR //Calcul du rayon de la base int rayonBase; if (curseur.getEpaisseur() > 10) rayonBase = curseur.getEpaisseur() / 2; else rayonBase = 5; //Dessin de la base //Sous curseur negatif g.setColor(Color.white); g.drawLine(this.getPosX() - (curseur.getEpaisseur() / 2), this.getPosY() + 1, this.getPosX() + (curseur.getEpaisseur() / 2), this.getPosY() + 1); g.drawLine(this.getPosX() + 1, this.getPosY() - (curseur.getEpaisseur() / 2), this.getPosX() +1, this.getPosY()+ (curseur.getEpaisseur() / 2)); if (curseur.isDown()){ if(curseur.getForme() == 0) g.drawOval(this.getPosX() - rayonBase, this.getPosY() - rayonBase + 1, rayonBase * 2, rayonBase * 2); else g.drawRect(this.getPosX() - curseur.getEpaisseur()/2 + 1, this.getPosY() - curseur.getEpaisseur()/2 + 1, curseur.getEpaisseur(), curseur.getEpaisseur()); } //Curseur de la bonne couleur g.setColor(Color.black); g.drawLine(this.getPosX() - (curseur.getEpaisseur() / 2), this.getPosY(), this.getPosX() + (curseur.getEpaisseur() / 2), this.getPosY()); g.drawLine(this.getPosX(), this.getPosY() - (curseur.getEpaisseur() / 2), this.getPosX(), this.getPosY() + (curseur.getEpaisseur() / 2)); if (curseur.isDown()){ if(curseur.getForme() == 0) g.drawOval(this.getPosX() - rayonBase, this.getPosY() - rayonBase , rayonBase * 2, rayonBase * 2); else g.drawRect(this.getPosX() - curseur.getEpaisseur()/2, this.getPosY() - curseur.getEpaisseur()/2, curseur.getEpaisseur(), curseur.getEpaisseur()); } //Affichage de la fleche d'orientation //Determinons le point d'arrivée du trait symbolisant l'orientation int tailleTrait; if (curseur.getEpaisseur() > 40) tailleTrait = curseur.getEpaisseur(); else tailleTrait = 40; double posX2 = this.getPosX() + tailleTrait * Math.sin(curseur.getOrientation() * Math.PI / 180); double posY2 = this.getPosY() + tailleTrait * Math.cos(curseur.getOrientation() * Math.PI / 180); //Dessinons le trait g.setStroke(new BasicStroke(0)); g.drawLine(this.getPosX(), this.getPosY(), (int)posX2, (int)posY2); g.setColor(Color.white); g.drawLine(this.getPosX() - 1, this.getPosY() - 1, (int)posX2 - 1, (int)posY2 - 1); //DETERMINONS LA TAILLE DU JPANEL this.setPreferredSize(new Dimension(largeurDessin, hauteurDessin)); this.setMinimumSize(new Dimension(largeurDessin, hauteurDessin)); this.setMaximumSize(new Dimension(largeurDessin, hauteurDessin)); } /*/// * ACCESSEURS //*/ public int posXAbsolue(int x){ return x + ecartHorizontal; } public int posYAbsolue(int y){ return y + ecartVertical; } /*/// * ACCESSEURS //*/ public int getPosX(){ return curseur.getPosX() + ecartHorizontal; } public int getPosY(){ return curseur.getPosY() + ecartVertical; } public int getEcartHorizontal(){ return ecartHorizontal; } public int getEcartVertical(){ return ecartVertical; } public int getLargeurDessin(){ return largeurDessin; } public int getHauteurDessin(){ return hauteurDessin; } public Color getBackground(){ return background; } /*/// * MODIFIEURS //*/ /** * Modifie le controleur * @param c nouveau controleur */ public void setControleur(Controleur c) { this.c = c; } public void setBackground(Color c){ background = c; } public void setLargeur(int l){ largeurDessin = l; } public void setHauteur(int h){ hauteurDessin = h; } public void setBarreOutils(BarreOutils b){ barreOutils = b;} }
true
true
public void paintComponent(Graphics gd){ Graphics2D g = (Graphics2D)gd; //Calcul de l'ecart de la zone de dessin pour centrer le dessin ecartHorizontal = (this.getWidth() - largeurDessin)/2; ecartVertical = (this.getHeight() - hauteurDessin)/2; //ETAPE 1 : Afficher la zone de dessin g.setColor(background);//Couleur de fond du dessin g.fillRect(ecartHorizontal, ecartVertical, this.largeurDessin, this.hauteurDessin); //ETAPE 2 : Afficher les traceurs Traceur t; for (int i = 0; i < StockageDonnee.liste_dessin.size(); i ++){ t = StockageDonnee.liste_dessin.get(i); //Initialisons les propriétés de l'objet graphics g.setColor(t.getColor()); int cap; int join; if(t.getForme() == 0){ cap = BasicStroke.CAP_ROUND; join = BasicStroke.JOIN_ROUND; } else{ cap = BasicStroke.CAP_BUTT; join = BasicStroke.CAP_ROUND; } g.setStroke(new BasicStroke(t.getEpaisseur(), cap, join)); /*System.out.println("Position X Début : " + posXAbsolue(t.getXOrigine())); System.out.println("Position Y Début : " + posYAbsolue(t.getYOrigine())); System.out.println("Position X Fin : " + posXAbsolue(t.getXArrivee())); System.out.println("Position Y Fin : " + posYAbsolue(t.getYArrivee())); System.out.println("Couleur Curseur : " + t.getColor()); System.out.println("Epaisseur : " + t.getEpaisseur()); */ //Si le t est une droite/point if (t.getType() == 1 || t.getType() == 0){ if(t.getForme() == 0) g.drawLine(posXAbsolue(t.getXOrigine()), posYAbsolue(t.getYOrigine()), posXAbsolue(t.getXArrivee()), posYAbsolue(t.getYArrivee())); //Dans le cas d'une forme carré, on va dessiner des carré aux points de départ/arrivée pour un effet pls propre else{ g.setStroke(new BasicStroke()); g.fillRect(posXAbsolue(t.getXOrigine()) - t.getEpaisseur()/2, posYAbsolue(t.getYOrigine()) - t.getEpaisseur()/2, t.getEpaisseur(), t.getEpaisseur()); g.fillRect(posXAbsolue(t.getXArrivee()) - t.getEpaisseur()/2, posYAbsolue(t.getYArrivee()) - t.getEpaisseur()/2, t.getEpaisseur(), t.getEpaisseur()); //Et on trace deux version du trait entre les points (en fait si on ne laisse qu'une seule des deux version, certains angles seront mal déssiné int[] x = {posXAbsolue(t.getXOrigine()) - t.getEpaisseur()/2, posXAbsolue(t.getXArrivee()) - t.getEpaisseur()/2, posXAbsolue(t.getXArrivee()) + t.getEpaisseur()/2, posXAbsolue(t.getXOrigine()) + t.getEpaisseur()/2 }; int[] y = {posYAbsolue(t.getYOrigine()) - t.getEpaisseur()/2, posYAbsolue(t.getYArrivee()) - t.getEpaisseur()/2, posYAbsolue(t.getYArrivee()) + t.getEpaisseur()/2, posYAbsolue(t.getYOrigine()) + t.getEpaisseur()/2 }; g.fillPolygon(x, y, 4); int[] x2 = {posXAbsolue(t.getXOrigine()) + t.getEpaisseur()/2, posXAbsolue(t.getXArrivee()) + t.getEpaisseur()/2, posXAbsolue(t.getXArrivee()) - t.getEpaisseur()/2, posXAbsolue(t.getXOrigine()) - t.getEpaisseur()/2 }; g.fillPolygon(x2, y, 4); } } //Si le t est un Rectangle else if (t.getType() == 2){ //On va faire une boucle qui dessin des triangle successifs selon l'epaisseur du curseur if(t.estRempli()){ g.fillRect(posXAbsolue(t.getXOrigine()), posYAbsolue(t.getYOrigine()), t.getLargeur(), t.getHauteur()); } else{ g.drawRect(posXAbsolue(posXAbsolue(t.getXOrigine()) - t.getEpaisseur()), posYAbsolue(t.getYOrigine()) - t.getEpaisseur(), t.getLargeur() + t.getEpaisseur(), t.getHauteur() + t.getEpaisseur()); } } //Si le t est un triangle else if (t.getType() == 3){ int[] x = {posXAbsolue(t.getXOrigine()), posXAbsolue(t.getXArrivee()), posXAbsolue(t.getX3())}; int[] y = {posYAbsolue(t.getYOrigine()), posYAbsolue(t.getYArrivee()), posYAbsolue(t.getY3())}; if(!t.estRempli()){ g.fillPolygon(x, y, 3); } else{ g.drawPolygon(x, y, 3); } } //Si le t est un Cercle else if (t.getType() == 4){ //On va faire une boucle qui dessin des triangle successifs selon l'epaisseur du curseur if(!t.estRempli()){ g.fillOval(posXAbsolue(t.getXOrigine()), posYAbsolue(t.getYOrigine()), t.getLargeur(), t.getHauteur()); } else{ g.drawOval(posXAbsolue(t.getXOrigine()), posYAbsolue(t.getYOrigine()), t.getLargeur(), t.getHauteur()); } } //Si le t est une image else if(t.getType() == 5){ try { Image img = ImageIO.read(new File(t.getPath())); g.drawImage(img, ecartHorizontal, ecartVertical, this); //Pour une image de fond //g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), this); } catch (IOException e) { e.printStackTrace(); } } } //DESSINONS LE FOND g.setStroke(new BasicStroke()); //Fond de la zone de dessin g.setColor(new Color(180,180,180));//Couleur de fond g.fillRect(0, 0, ecartHorizontal, this.getHeight());//On défini une couleur derriere le dessin pour eviter les glitch graphiques g.fillRect(ecartHorizontal + largeurDessin, 0, this.getWidth(), this.getHeight()); g.fillRect(ecartHorizontal - 1, 0, largeurDessin + 1, ecartVertical); g.fillRect(ecartHorizontal - 1, hauteurDessin + ecartVertical, largeurDessin + 1, ecartVertical+1); //Ombre du dessin g.setColor(new Color(220,220,220)); g.fillRect(ecartHorizontal + largeurDessin, ecartVertical + 5, 5, hauteurDessin); g.fillRect(ecartHorizontal + 5, ecartVertical + hauteurDessin, largeurDessin, 5); //ETAPE 3 : Afficher le curseur //Deux curseurs à afficher : le curseur négatif (pour plus de lisibilité) et le curseur normal //Forme du curseur en fonction de l'outil BasicStroke forme; if(curseur.getType() == 0){ forme = new BasicStroke(0); } else{ float[] dashArray = {2, 2}; forme = new BasicStroke(0, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 0, dashArray, 0); } g.setStroke(forme); //AFFICHAGE DE LA BASE DU CURSEUR //Calcul du rayon de la base int rayonBase; if (curseur.getEpaisseur() > 10) rayonBase = curseur.getEpaisseur() / 2; else rayonBase = 5; //Dessin de la base //Sous curseur negatif g.setColor(Color.white); g.drawLine(this.getPosX() - (curseur.getEpaisseur() / 2), this.getPosY() + 1, this.getPosX() + (curseur.getEpaisseur() / 2), this.getPosY() + 1); g.drawLine(this.getPosX() + 1, this.getPosY() - (curseur.getEpaisseur() / 2), this.getPosX() +1, this.getPosY()+ (curseur.getEpaisseur() / 2)); if (curseur.isDown()){ if(curseur.getForme() == 0) g.drawOval(this.getPosX() - rayonBase, this.getPosY() - rayonBase + 1, rayonBase * 2, rayonBase * 2); else g.drawRect(this.getPosX() - curseur.getEpaisseur()/2 + 1, this.getPosY() - curseur.getEpaisseur()/2 + 1, curseur.getEpaisseur(), curseur.getEpaisseur()); } //Curseur de la bonne couleur g.setColor(Color.black); g.drawLine(this.getPosX() - (curseur.getEpaisseur() / 2), this.getPosY(), this.getPosX() + (curseur.getEpaisseur() / 2), this.getPosY()); g.drawLine(this.getPosX(), this.getPosY() - (curseur.getEpaisseur() / 2), this.getPosX(), this.getPosY() + (curseur.getEpaisseur() / 2)); if (curseur.isDown()){ if(curseur.getForme() == 0) g.drawOval(this.getPosX() - rayonBase, this.getPosY() - rayonBase , rayonBase * 2, rayonBase * 2); else g.drawRect(this.getPosX() - curseur.getEpaisseur()/2, this.getPosY() - curseur.getEpaisseur()/2, curseur.getEpaisseur(), curseur.getEpaisseur()); } //Affichage de la fleche d'orientation //Determinons le point d'arrivée du trait symbolisant l'orientation int tailleTrait; if (curseur.getEpaisseur() > 40) tailleTrait = curseur.getEpaisseur(); else tailleTrait = 40; double posX2 = this.getPosX() + tailleTrait * Math.sin(curseur.getOrientation() * Math.PI / 180); double posY2 = this.getPosY() + tailleTrait * Math.cos(curseur.getOrientation() * Math.PI / 180); //Dessinons le trait g.setStroke(new BasicStroke(0)); g.drawLine(this.getPosX(), this.getPosY(), (int)posX2, (int)posY2); g.setColor(Color.white); g.drawLine(this.getPosX() - 1, this.getPosY() - 1, (int)posX2 - 1, (int)posY2 - 1); //DETERMINONS LA TAILLE DU JPANEL this.setPreferredSize(new Dimension(largeurDessin, hauteurDessin)); this.setMinimumSize(new Dimension(largeurDessin, hauteurDessin)); this.setMaximumSize(new Dimension(largeurDessin, hauteurDessin)); }
public void paintComponent(Graphics gd){ Graphics2D g = (Graphics2D)gd; //Calcul de l'ecart de la zone de dessin pour centrer le dessin ecartHorizontal = (this.getWidth() - largeurDessin)/2; ecartVertical = (this.getHeight() - hauteurDessin)/2; //ETAPE 1 : Afficher la zone de dessin g.setColor(background);//Couleur de fond du dessin g.fillRect(ecartHorizontal, ecartVertical, this.largeurDessin, this.hauteurDessin); //ETAPE 2 : Afficher les traceurs Traceur t; for (int i = 0; i < StockageDonnee.liste_dessin.size(); i ++){ t = StockageDonnee.liste_dessin.get(i); //Initialisons les propriétés de l'objet graphics g.setColor(t.getColor()); int cap; int join; if(t.getForme() == 0){ cap = BasicStroke.CAP_ROUND; join = BasicStroke.JOIN_ROUND; } else{ cap = BasicStroke.CAP_BUTT; join = BasicStroke.CAP_ROUND; } g.setStroke(new BasicStroke(t.getEpaisseur(), cap, join)); /*System.out.println("Position X Début : " + posXAbsolue(t.getXOrigine())); System.out.println("Position Y Début : " + posYAbsolue(t.getYOrigine())); System.out.println("Position X Fin : " + posXAbsolue(t.getXArrivee())); System.out.println("Position Y Fin : " + posYAbsolue(t.getYArrivee())); System.out.println("Couleur Curseur : " + t.getColor()); System.out.println("Epaisseur : " + t.getEpaisseur()); */ //Si le t est une droite/point if (t.getType() == 1 || t.getType() == 0){ if(t.getForme() == 0) g.drawLine(posXAbsolue(t.getXOrigine()), posYAbsolue(t.getYOrigine()), posXAbsolue(t.getXArrivee()), posYAbsolue(t.getYArrivee())); //Dans le cas d'une forme carré, on va dessiner des carré aux points de départ/arrivée pour un effet pls propre else{ g.setStroke(new BasicStroke()); g.fillRect(posXAbsolue(t.getXOrigine()) - t.getEpaisseur()/2, posYAbsolue(t.getYOrigine()) - t.getEpaisseur()/2, t.getEpaisseur(), t.getEpaisseur()); g.fillRect(posXAbsolue(t.getXArrivee()) - t.getEpaisseur()/2, posYAbsolue(t.getYArrivee()) - t.getEpaisseur()/2, t.getEpaisseur(), t.getEpaisseur()); //Et on trace deux version du trait entre les points (en fait si on ne laisse qu'une seule des deux version, certains angles seront mal déssiné int[] x = {posXAbsolue(t.getXOrigine()) - t.getEpaisseur()/2, posXAbsolue(t.getXArrivee()) - t.getEpaisseur()/2, posXAbsolue(t.getXArrivee()) + t.getEpaisseur()/2, posXAbsolue(t.getXOrigine()) + t.getEpaisseur()/2 }; int[] y = {posYAbsolue(t.getYOrigine()) - t.getEpaisseur()/2, posYAbsolue(t.getYArrivee()) - t.getEpaisseur()/2, posYAbsolue(t.getYArrivee()) + t.getEpaisseur()/2, posYAbsolue(t.getYOrigine()) + t.getEpaisseur()/2 }; g.fillPolygon(x, y, 4); int[] x2 = {posXAbsolue(t.getXOrigine()) + t.getEpaisseur()/2, posXAbsolue(t.getXArrivee()) + t.getEpaisseur()/2, posXAbsolue(t.getXArrivee()) - t.getEpaisseur()/2, posXAbsolue(t.getXOrigine()) - t.getEpaisseur()/2 }; g.fillPolygon(x2, y, 4); } } //Si le t est un Rectangle else if (t.getType() == 2){ //On va faire une boucle qui dessin des triangle successifs selon l'epaisseur du curseur if(t.estRempli()){ g.fillRect(posXAbsolue(t.getXOrigine()), posYAbsolue(t.getYOrigine()), t.getLargeur(), t.getHauteur()); } else{ g.drawRect(posXAbsolue(posXAbsolue(t.getXOrigine()) - t.getEpaisseur()), posYAbsolue(t.getYOrigine()) - t.getEpaisseur(), t.getLargeur() + t.getEpaisseur(), t.getHauteur() + t.getEpaisseur()); } } //Si le t est un triangle else if (t.getType() == 3){ int[] x = {posXAbsolue(t.getXOrigine()), posXAbsolue(t.getXArrivee()), posXAbsolue(t.getX3())}; int[] y = {posYAbsolue(t.getYOrigine()), posYAbsolue(t.getYArrivee()), posYAbsolue(t.getY3())}; if(!t.estRempli()){ g.fillPolygon(x, y, 3); } else{ g.drawPolygon(x, y, 3); } } //Si le t est un Cercle else if (t.getType() == 4){ //On va faire une boucle qui dessin des triangle successifs selon l'epaisseur du curseur if(!t.estRempli()){ g.fillOval(posXAbsolue(t.getXOrigine()), posYAbsolue(t.getYOrigine()), t.getLargeur(), t.getHauteur()); } else{ g.drawOval(posXAbsolue(t.getXOrigine()), posYAbsolue(t.getYOrigine()), t.getLargeur(), t.getHauteur()); } } //Si le t est une image else if(t.getType() == 5){ try { Image img = ImageIO.read(new File(t.getPath())); g.drawImage(img, ecartHorizontal, ecartVertical, this); //Pour une image de fond //g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), this); } catch (IOException e) { e.printStackTrace(); } } } //DESSINONS LE FOND g.setStroke(new BasicStroke()); //Fond de la zone de dessin g.setColor(new Color(180,180,180));//Couleur de fond g.fillRect(0, 0, ecartHorizontal, this.getHeight());//On défini une couleur derriere le dessin pour eviter les glitch graphiques g.fillRect(ecartHorizontal + largeurDessin, 0, this.getWidth(), this.getHeight()); g.fillRect(ecartHorizontal - 1, 0, largeurDessin + 1, ecartVertical); g.fillRect(ecartHorizontal - 1, hauteurDessin + ecartVertical, largeurDessin + 1, ecartVertical+1); //Ombre du dessin g.setColor(new Color(220,220,220)); g.fillRect(ecartHorizontal + largeurDessin, ecartVertical + 5, 5, hauteurDessin); g.fillRect(ecartHorizontal + 5, ecartVertical + hauteurDessin, largeurDessin, 5); //ETAPE 3 : Afficher le curseur //Deux curseurs à afficher : le curseur négatif (pour plus de lisibilité) et le curseur normal //Forme du curseur en fonction de l'outil BasicStroke forme; if(curseur.getType() == 0){ forme = new BasicStroke(0); } else{ float[] dashArray = {2, 2}; forme = new BasicStroke(0, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 0, dashArray, 0); } g.setStroke(forme); //AFFICHAGE DE LA BASE DU CURSEUR //Calcul du rayon de la base int rayonBase; if (curseur.getEpaisseur() > 10) rayonBase = curseur.getEpaisseur() / 2; else rayonBase = 5; //Dessin de la base //Sous curseur negatif g.setColor(Color.white); g.drawLine(this.getPosX() - (curseur.getEpaisseur() / 2), this.getPosY() + 1, this.getPosX() + (curseur.getEpaisseur() / 2), this.getPosY() + 1); g.drawLine(this.getPosX() + 1, this.getPosY() - (curseur.getEpaisseur() / 2), this.getPosX() +1, this.getPosY()+ (curseur.getEpaisseur() / 2)); if (curseur.isDown()){ if(curseur.getForme() == 0) g.drawOval(this.getPosX() - rayonBase, this.getPosY() - rayonBase + 1, rayonBase * 2, rayonBase * 2); else g.drawRect(this.getPosX() - curseur.getEpaisseur()/2 + 1, this.getPosY() - curseur.getEpaisseur()/2 + 1, curseur.getEpaisseur(), curseur.getEpaisseur()); } //Curseur de la bonne couleur g.setColor(Color.black); g.drawLine(this.getPosX() - (curseur.getEpaisseur() / 2), this.getPosY(), this.getPosX() + (curseur.getEpaisseur() / 2), this.getPosY()); g.drawLine(this.getPosX(), this.getPosY() - (curseur.getEpaisseur() / 2), this.getPosX(), this.getPosY() + (curseur.getEpaisseur() / 2)); if (curseur.isDown()){ if(curseur.getForme() == 0) g.drawOval(this.getPosX() - rayonBase, this.getPosY() - rayonBase , rayonBase * 2, rayonBase * 2); else g.drawRect(this.getPosX() - curseur.getEpaisseur()/2, this.getPosY() - curseur.getEpaisseur()/2, curseur.getEpaisseur(), curseur.getEpaisseur()); } //Affichage de la fleche d'orientation //Determinons le point d'arrivée du trait symbolisant l'orientation int tailleTrait; if (curseur.getEpaisseur() > 40) tailleTrait = curseur.getEpaisseur(); else tailleTrait = 40; double posX2 = this.getPosX() + tailleTrait * Math.sin(curseur.getOrientation() * Math.PI / 180); double posY2 = this.getPosY() + tailleTrait * Math.cos(curseur.getOrientation() * Math.PI / 180); //Dessinons le trait g.setStroke(new BasicStroke(0)); g.drawLine(this.getPosX(), this.getPosY(), (int)posX2, (int)posY2); g.setColor(Color.white); g.drawLine(this.getPosX() - 1, this.getPosY() - 1, (int)posX2 - 1, (int)posY2 - 1); //DETERMINONS LA TAILLE DU JPANEL this.setPreferredSize(new Dimension(largeurDessin, hauteurDessin)); this.setMinimumSize(new Dimension(largeurDessin, hauteurDessin)); this.setMaximumSize(new Dimension(largeurDessin, hauteurDessin)); }
diff --git a/core/src/main/java/org/apache/mahout/cf/taste/impl/eval/GenericRecommenderIRStatsEvaluator.java b/core/src/main/java/org/apache/mahout/cf/taste/impl/eval/GenericRecommenderIRStatsEvaluator.java index b142980cb..c432b42bd 100644 --- a/core/src/main/java/org/apache/mahout/cf/taste/impl/eval/GenericRecommenderIRStatsEvaluator.java +++ b/core/src/main/java/org/apache/mahout/cf/taste/impl/eval/GenericRecommenderIRStatsEvaluator.java @@ -1,208 +1,205 @@ /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.mahout.cf.taste.impl.eval; import org.apache.mahout.cf.taste.common.NoSuchUserException; import org.apache.mahout.cf.taste.common.TasteException; import org.apache.mahout.cf.taste.eval.DataModelBuilder; import org.apache.mahout.cf.taste.eval.IRStatistics; import org.apache.mahout.cf.taste.eval.RecommenderBuilder; import org.apache.mahout.cf.taste.eval.RecommenderIRStatsEvaluator; import org.apache.mahout.cf.taste.impl.common.FastByIDMap; import org.apache.mahout.cf.taste.impl.common.FastIDSet; import org.apache.mahout.cf.taste.impl.common.FullRunningAverage; import org.apache.mahout.cf.taste.impl.common.FullRunningAverageAndStdDev; import org.apache.mahout.cf.taste.impl.common.LongPrimitiveIterator; import org.apache.mahout.common.RandomUtils; import org.apache.mahout.cf.taste.impl.common.RunningAverage; import org.apache.mahout.cf.taste.impl.common.RunningAverageAndStdDev; import org.apache.mahout.cf.taste.impl.model.GenericDataModel; import org.apache.mahout.cf.taste.impl.model.GenericUserPreferenceArray; import org.apache.mahout.cf.taste.model.DataModel; import org.apache.mahout.cf.taste.model.Preference; import org.apache.mahout.cf.taste.model.PreferenceArray; import org.apache.mahout.cf.taste.recommender.RecommendedItem; import org.apache.mahout.cf.taste.recommender.Recommender; import org.apache.mahout.cf.taste.recommender.Rescorer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Random; /** * <p>For each user, these implementation determine the top <code>n</code> preferences, then evaluate the IR * statistics based on a {@link DataModel} that does not have these values. This number <code>n</code> is the "at" * value, as in "precision at 5". For example, this would mean precision evaluated by removing the top 5 preferences for * a user and then finding the percentage of those 5 items included in the top 5 recommendations for * that user.</p> */ public final class GenericRecommenderIRStatsEvaluator implements RecommenderIRStatsEvaluator { private static final Logger log = LoggerFactory.getLogger(GenericRecommenderIRStatsEvaluator.class); /** * Pass as "relevanceThreshold" argument to * {@link #evaluate(RecommenderBuilder, DataModelBuilder, DataModel, Rescorer, int, double, double)} * to have it attempt to compute a reasonable threshold. Note that this will impact performance. */ public static final double CHOOSE_THRESHOLD = Double.NaN; private final Random random; public GenericRecommenderIRStatsEvaluator() { random = RandomUtils.getRandom(); } @Override public IRStatistics evaluate(RecommenderBuilder recommenderBuilder, DataModelBuilder dataModelBuilder, DataModel dataModel, Rescorer<Long> rescorer, int at, double relevanceThreshold, double evaluationPercentage) throws TasteException { if (recommenderBuilder == null) { throw new IllegalArgumentException("recommenderBuilder is null"); } if (dataModel == null) { throw new IllegalArgumentException("dataModel is null"); } if (at < 1) { throw new IllegalArgumentException("at must be at least 1"); } if (Double.isNaN(evaluationPercentage) || evaluationPercentage <= 0.0 || evaluationPercentage > 1.0) { throw new IllegalArgumentException("Invalid evaluationPercentage: " + evaluationPercentage); } - if (Double.isNaN(relevanceThreshold)) { - throw new IllegalArgumentException("Invalid relevanceThreshold: " + evaluationPercentage); - } int numItems = dataModel.getNumItems(); RunningAverage precision = new FullRunningAverage(); RunningAverage recall = new FullRunningAverage(); RunningAverage fallOut = new FullRunningAverage(); LongPrimitiveIterator it = dataModel.getUserIDs(); while (it.hasNext()) { long userID = it.nextLong(); if (random.nextDouble() < evaluationPercentage) { long start = System.currentTimeMillis(); FastIDSet relevantItemIDs = new FastIDSet(at); PreferenceArray prefs = dataModel.getPreferencesFromUser(userID); int size = prefs.length(); if (size < 2 * at) { // Really not enough prefs to meaningfully evaluate this user continue; } // List some most-preferred items that would count as (most) "relevant" results double theRelevanceThreshold = Double.isNaN(relevanceThreshold) ? computeThreshold(prefs) : relevanceThreshold; prefs.sortByValueReversed(); for (int i = 0; i < size && relevantItemIDs.size() < at; i++) { if (prefs.getValue(i) >= theRelevanceThreshold) { relevantItemIDs.add(prefs.getItemID(i)); } } int numRelevantItems = relevantItemIDs.size(); if (numRelevantItems > 0) { FastByIDMap<PreferenceArray> trainingUsers = new FastByIDMap<PreferenceArray>(dataModel.getNumUsers()); LongPrimitiveIterator it2 = dataModel.getUserIDs(); while (it2.hasNext()) { processOtherUser(userID, relevantItemIDs, trainingUsers, it2.nextLong(), dataModel); } DataModel trainingModel = dataModelBuilder == null ? new GenericDataModel(trainingUsers) : dataModelBuilder.buildDataModel(trainingUsers); Recommender recommender = recommenderBuilder.buildRecommender(trainingModel); try { trainingModel.getPreferencesFromUser(userID); } catch (NoSuchUserException nsee) { continue; // Oops we excluded all prefs for the user -- just move on } int intersectionSize = 0; List<RecommendedItem> recommendedItems = recommender.recommend(userID, at, rescorer); for (RecommendedItem recommendedItem : recommendedItems) { if (relevantItemIDs.contains(recommendedItem.getItemID())) { intersectionSize++; } } int numRecommendedItems = recommendedItems.size(); if (numRecommendedItems > 0) { precision.addDatum((double) intersectionSize / (double) numRecommendedItems); } recall.addDatum((double) intersectionSize / (double) numRelevantItems); if (numRelevantItems < size) { fallOut.addDatum((double) (numRecommendedItems - intersectionSize) / (double) (numItems - numRelevantItems)); } long end = System.currentTimeMillis(); log.info("Evaluated with user " + userID + " in " + (end - start) + "ms"); log.info("Precision/recall/fall-out: {} / {} / {}", new Object[]{ precision.getAverage(), recall.getAverage(), fallOut.getAverage() }); } } } return new IRStatisticsImpl(precision.getAverage(), recall.getAverage(), fallOut.getAverage()); } private static void processOtherUser(long id, FastIDSet relevantItemIDs, FastByIDMap<PreferenceArray> trainingUsers, long userID2, DataModel dataModel) throws TasteException { PreferenceArray prefs2Array = dataModel.getPreferencesFromUser(userID2); if (id == userID2) { List<Preference> prefs2 = new ArrayList<Preference>(prefs2Array.length()); for (Preference pref : prefs2Array) { prefs2.add(pref); } for (Iterator<Preference> iterator = prefs2.iterator(); iterator.hasNext();) { Preference pref = iterator.next(); if (relevantItemIDs.contains(pref.getItemID())) { iterator.remove(); } } prefs2Array = new GenericUserPreferenceArray(prefs2); } trainingUsers.put(userID2, prefs2Array); } private static double computeThreshold(PreferenceArray prefs) { if (prefs.length() < 2) { // Not enough data points -- return a threshold that allows everything return Double.NEGATIVE_INFINITY; } RunningAverageAndStdDev stdDev = new FullRunningAverageAndStdDev(); int size = prefs.length(); for (int i = 0; i < size; i++) { stdDev.addDatum(prefs.getValue(i)); } return stdDev.getAverage() + stdDev.getStandardDeviation(); } }
true
true
public IRStatistics evaluate(RecommenderBuilder recommenderBuilder, DataModelBuilder dataModelBuilder, DataModel dataModel, Rescorer<Long> rescorer, int at, double relevanceThreshold, double evaluationPercentage) throws TasteException { if (recommenderBuilder == null) { throw new IllegalArgumentException("recommenderBuilder is null"); } if (dataModel == null) { throw new IllegalArgumentException("dataModel is null"); } if (at < 1) { throw new IllegalArgumentException("at must be at least 1"); } if (Double.isNaN(evaluationPercentage) || evaluationPercentage <= 0.0 || evaluationPercentage > 1.0) { throw new IllegalArgumentException("Invalid evaluationPercentage: " + evaluationPercentage); } if (Double.isNaN(relevanceThreshold)) { throw new IllegalArgumentException("Invalid relevanceThreshold: " + evaluationPercentage); } int numItems = dataModel.getNumItems(); RunningAverage precision = new FullRunningAverage(); RunningAverage recall = new FullRunningAverage(); RunningAverage fallOut = new FullRunningAverage(); LongPrimitiveIterator it = dataModel.getUserIDs(); while (it.hasNext()) { long userID = it.nextLong(); if (random.nextDouble() < evaluationPercentage) { long start = System.currentTimeMillis(); FastIDSet relevantItemIDs = new FastIDSet(at); PreferenceArray prefs = dataModel.getPreferencesFromUser(userID); int size = prefs.length(); if (size < 2 * at) { // Really not enough prefs to meaningfully evaluate this user continue; } // List some most-preferred items that would count as (most) "relevant" results double theRelevanceThreshold = Double.isNaN(relevanceThreshold) ? computeThreshold(prefs) : relevanceThreshold; prefs.sortByValueReversed(); for (int i = 0; i < size && relevantItemIDs.size() < at; i++) { if (prefs.getValue(i) >= theRelevanceThreshold) { relevantItemIDs.add(prefs.getItemID(i)); } } int numRelevantItems = relevantItemIDs.size(); if (numRelevantItems > 0) { FastByIDMap<PreferenceArray> trainingUsers = new FastByIDMap<PreferenceArray>(dataModel.getNumUsers()); LongPrimitiveIterator it2 = dataModel.getUserIDs(); while (it2.hasNext()) { processOtherUser(userID, relevantItemIDs, trainingUsers, it2.nextLong(), dataModel); } DataModel trainingModel = dataModelBuilder == null ? new GenericDataModel(trainingUsers) : dataModelBuilder.buildDataModel(trainingUsers); Recommender recommender = recommenderBuilder.buildRecommender(trainingModel); try { trainingModel.getPreferencesFromUser(userID); } catch (NoSuchUserException nsee) { continue; // Oops we excluded all prefs for the user -- just move on } int intersectionSize = 0; List<RecommendedItem> recommendedItems = recommender.recommend(userID, at, rescorer); for (RecommendedItem recommendedItem : recommendedItems) { if (relevantItemIDs.contains(recommendedItem.getItemID())) { intersectionSize++; } } int numRecommendedItems = recommendedItems.size(); if (numRecommendedItems > 0) { precision.addDatum((double) intersectionSize / (double) numRecommendedItems); } recall.addDatum((double) intersectionSize / (double) numRelevantItems); if (numRelevantItems < size) { fallOut.addDatum((double) (numRecommendedItems - intersectionSize) / (double) (numItems - numRelevantItems)); } long end = System.currentTimeMillis(); log.info("Evaluated with user " + userID + " in " + (end - start) + "ms"); log.info("Precision/recall/fall-out: {} / {} / {}", new Object[]{ precision.getAverage(), recall.getAverage(), fallOut.getAverage() }); } } } return new IRStatisticsImpl(precision.getAverage(), recall.getAverage(), fallOut.getAverage()); }
public IRStatistics evaluate(RecommenderBuilder recommenderBuilder, DataModelBuilder dataModelBuilder, DataModel dataModel, Rescorer<Long> rescorer, int at, double relevanceThreshold, double evaluationPercentage) throws TasteException { if (recommenderBuilder == null) { throw new IllegalArgumentException("recommenderBuilder is null"); } if (dataModel == null) { throw new IllegalArgumentException("dataModel is null"); } if (at < 1) { throw new IllegalArgumentException("at must be at least 1"); } if (Double.isNaN(evaluationPercentage) || evaluationPercentage <= 0.0 || evaluationPercentage > 1.0) { throw new IllegalArgumentException("Invalid evaluationPercentage: " + evaluationPercentage); } int numItems = dataModel.getNumItems(); RunningAverage precision = new FullRunningAverage(); RunningAverage recall = new FullRunningAverage(); RunningAverage fallOut = new FullRunningAverage(); LongPrimitiveIterator it = dataModel.getUserIDs(); while (it.hasNext()) { long userID = it.nextLong(); if (random.nextDouble() < evaluationPercentage) { long start = System.currentTimeMillis(); FastIDSet relevantItemIDs = new FastIDSet(at); PreferenceArray prefs = dataModel.getPreferencesFromUser(userID); int size = prefs.length(); if (size < 2 * at) { // Really not enough prefs to meaningfully evaluate this user continue; } // List some most-preferred items that would count as (most) "relevant" results double theRelevanceThreshold = Double.isNaN(relevanceThreshold) ? computeThreshold(prefs) : relevanceThreshold; prefs.sortByValueReversed(); for (int i = 0; i < size && relevantItemIDs.size() < at; i++) { if (prefs.getValue(i) >= theRelevanceThreshold) { relevantItemIDs.add(prefs.getItemID(i)); } } int numRelevantItems = relevantItemIDs.size(); if (numRelevantItems > 0) { FastByIDMap<PreferenceArray> trainingUsers = new FastByIDMap<PreferenceArray>(dataModel.getNumUsers()); LongPrimitiveIterator it2 = dataModel.getUserIDs(); while (it2.hasNext()) { processOtherUser(userID, relevantItemIDs, trainingUsers, it2.nextLong(), dataModel); } DataModel trainingModel = dataModelBuilder == null ? new GenericDataModel(trainingUsers) : dataModelBuilder.buildDataModel(trainingUsers); Recommender recommender = recommenderBuilder.buildRecommender(trainingModel); try { trainingModel.getPreferencesFromUser(userID); } catch (NoSuchUserException nsee) { continue; // Oops we excluded all prefs for the user -- just move on } int intersectionSize = 0; List<RecommendedItem> recommendedItems = recommender.recommend(userID, at, rescorer); for (RecommendedItem recommendedItem : recommendedItems) { if (relevantItemIDs.contains(recommendedItem.getItemID())) { intersectionSize++; } } int numRecommendedItems = recommendedItems.size(); if (numRecommendedItems > 0) { precision.addDatum((double) intersectionSize / (double) numRecommendedItems); } recall.addDatum((double) intersectionSize / (double) numRelevantItems); if (numRelevantItems < size) { fallOut.addDatum((double) (numRecommendedItems - intersectionSize) / (double) (numItems - numRelevantItems)); } long end = System.currentTimeMillis(); log.info("Evaluated with user " + userID + " in " + (end - start) + "ms"); log.info("Precision/recall/fall-out: {} / {} / {}", new Object[]{ precision.getAverage(), recall.getAverage(), fallOut.getAverage() }); } } } return new IRStatisticsImpl(precision.getAverage(), recall.getAverage(), fallOut.getAverage()); }
diff --git a/utils/ConvertToOmeTiff.java b/utils/ConvertToOmeTiff.java index b39056cf0..37ae062ea 100644 --- a/utils/ConvertToOmeTiff.java +++ b/utils/ConvertToOmeTiff.java @@ -1,45 +1,52 @@ // // ConvertToOmeTiff.java // import java.awt.image.BufferedImage; import java.util.Hashtable; import loci.formats.*; import loci.formats.out.TiffWriter; /** Converts the given files to OME-TIFF format. */ public class ConvertToOmeTiff { public static void main(String[] args) throws Exception { if (args.length == 0) { System.out.println("Usage: java ConvertToOmeTiff file1 file2 ..."); return; } ImageReader reader = new ImageReader(); TiffWriter writer = new TiffWriter(); // record metadata to OME-XML format OMEXMLMetadataStore store = new OMEXMLMetadataStore(); reader.setMetadataStore(store); for (int i=0; i<args.length; i++) { String id = args[i]; String outId = id + ".tif"; System.out.print("Converting " + id + " to " + outId + " "); int imageCount = reader.getImageCount(id); + // insert TiffData element into OME-XML + // currently handles only single series (single Image, single Pixels) String xml = store.dumpXML(); + int pix = xml.indexOf("<Pixels "); + int end = xml.indexOf("/>", pix); + xml = xml.substring(0, end) + + "><TiffData/></Pixels>" + xml.substring(end + 2); + // write out image planes for (int j=0; j<imageCount; j++) { BufferedImage plane = reader.openImage(id, j); Hashtable ifd = null; if (j == 0) { // save OME-XML metadata to TIFF file's first IFD ifd = new Hashtable(); TiffTools.putIFDValue(ifd, TiffTools.IMAGE_DESCRIPTION, xml); } // write plane to output file writer.saveImage(outId, plane, ifd, j == imageCount - 1); System.out.print("."); } System.out.println(" [done]"); } } }
false
true
public static void main(String[] args) throws Exception { if (args.length == 0) { System.out.println("Usage: java ConvertToOmeTiff file1 file2 ..."); return; } ImageReader reader = new ImageReader(); TiffWriter writer = new TiffWriter(); // record metadata to OME-XML format OMEXMLMetadataStore store = new OMEXMLMetadataStore(); reader.setMetadataStore(store); for (int i=0; i<args.length; i++) { String id = args[i]; String outId = id + ".tif"; System.out.print("Converting " + id + " to " + outId + " "); int imageCount = reader.getImageCount(id); String xml = store.dumpXML(); for (int j=0; j<imageCount; j++) { BufferedImage plane = reader.openImage(id, j); Hashtable ifd = null; if (j == 0) { // save OME-XML metadata to TIFF file's first IFD ifd = new Hashtable(); TiffTools.putIFDValue(ifd, TiffTools.IMAGE_DESCRIPTION, xml); } // write plane to output file writer.saveImage(outId, plane, ifd, j == imageCount - 1); System.out.print("."); } System.out.println(" [done]"); } }
public static void main(String[] args) throws Exception { if (args.length == 0) { System.out.println("Usage: java ConvertToOmeTiff file1 file2 ..."); return; } ImageReader reader = new ImageReader(); TiffWriter writer = new TiffWriter(); // record metadata to OME-XML format OMEXMLMetadataStore store = new OMEXMLMetadataStore(); reader.setMetadataStore(store); for (int i=0; i<args.length; i++) { String id = args[i]; String outId = id + ".tif"; System.out.print("Converting " + id + " to " + outId + " "); int imageCount = reader.getImageCount(id); // insert TiffData element into OME-XML // currently handles only single series (single Image, single Pixels) String xml = store.dumpXML(); int pix = xml.indexOf("<Pixels "); int end = xml.indexOf("/>", pix); xml = xml.substring(0, end) + "><TiffData/></Pixels>" + xml.substring(end + 2); // write out image planes for (int j=0; j<imageCount; j++) { BufferedImage plane = reader.openImage(id, j); Hashtable ifd = null; if (j == 0) { // save OME-XML metadata to TIFF file's first IFD ifd = new Hashtable(); TiffTools.putIFDValue(ifd, TiffTools.IMAGE_DESCRIPTION, xml); } // write plane to output file writer.saveImage(outId, plane, ifd, j == imageCount - 1); System.out.print("."); } System.out.println(" [done]"); } }
diff --git a/source/trunk/plugins/org.marketcetera.photon/src/main/java/org/marketcetera/photon/ApplicationWorkbenchAdvisor.java b/source/trunk/plugins/org.marketcetera.photon/src/main/java/org/marketcetera/photon/ApplicationWorkbenchAdvisor.java index 434e32839..d2f38bcb5 100755 --- a/source/trunk/plugins/org.marketcetera.photon/src/main/java/org/marketcetera/photon/ApplicationWorkbenchAdvisor.java +++ b/source/trunk/plugins/org.marketcetera.photon/src/main/java/org/marketcetera/photon/ApplicationWorkbenchAdvisor.java @@ -1,106 +1,116 @@ package org.marketcetera.photon; import java.net.URL; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Platform; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.ui.application.IWorkbenchConfigurer; import org.eclipse.ui.application.IWorkbenchWindowConfigurer; import org.eclipse.ui.application.WorkbenchAdvisor; import org.eclipse.ui.application.WorkbenchWindowAdvisor; import org.eclipse.ui.console.ConsolePlugin; import org.eclipse.ui.console.IConsole; import org.eclipse.ui.internal.ide.IDEInternalWorkbenchImages; import org.eclipse.ui.internal.ide.IDEWorkbenchPlugin; import org.eclipse.ui.internal.ide.model.WorkbenchAdapterBuilder; import org.osgi.framework.Bundle; /** * Class required by the RCP to initialize the workbench. * * @author gmiller * @author [email protected] */ public class ApplicationWorkbenchAdvisor extends WorkbenchAdvisor { /** * Does nothing more than return a new {@link ApplicationWorkbenchWindowAdvisor} * @see org.eclipse.ui.application.WorkbenchAdvisor#createWorkbenchWindowAdvisor(org.eclipse.ui.application.IWorkbenchWindowConfigurer) */ public WorkbenchWindowAdvisor createWorkbenchWindowAdvisor( IWorkbenchWindowConfigurer configurer) { return new ApplicationWorkbenchWindowAdvisor(configurer); } /* (non-Javadoc) * @see org.eclipse.ui.application.WorkbenchAdvisor#getInitialWindowPerspectiveId() */ public String getInitialWindowPerspectiveId() { return EquityPerspectiveFactory.ID; } /** * Creates a new MainConsole and adds it to the ConsoleManager * * @see org.eclipse.ui.application.WorkbenchAdvisor#initialize(org.eclipse.ui.application.IWorkbenchConfigurer) */ @Override public void initialize(IWorkbenchConfigurer configurer) { configurer.setSaveAndRestore(true); registerIdeAdapters(); declareIdeWorkbenchImages(); ConsolePlugin.getDefault().getConsoleManager().addConsoles( new IConsole[] { new MainConsole() }); } /** * Explicitly registers IDE- and resource-related adapters that RDT relies on. */ private void registerIdeAdapters() { WorkbenchAdapterBuilder.registerAdapters(); } /** * Declares shared images that RDT relies on. * <p> * In the context of the IDE, this is done by the <code>IDEWorkbenchAdvisor.declareWorkbenchImages()</code>. * In the context of an RCP app, however, <code>IDEWorkbenchAdvisor</code> is not used. In addition, we cannot * directly invoke the method since it has private access. We thus have to explicitly declare the few shared * IDE images that RDT needs here. */ private void declareIdeWorkbenchImages() { final String ICONS_PATH = "$nl$/icons/full/";//$NON-NLS-1$ final String PATH_ETOOL = ICONS_PATH + "etool16/"; // Enabled toolbar icons.//$NON-NLS-1$ + final String PATH_OBJECT = ICONS_PATH + "obj16/"; // Model object icons//$NON-NLS-1$ Bundle ideBundle = Platform.getBundle(IDEWorkbenchPlugin.IDE_WORKBENCH); declareIdeWorkbenchImage(ideBundle, IDEInternalWorkbenchImages.IMG_ETOOL_PROBLEM_CATEGORY, PATH_ETOOL + "problem_category.gif", true); //$NON-NLS-1$ + declareIdeWorkbenchImage(ideBundle, + IDEInternalWorkbenchImages.IMG_OBJS_ERROR_PATH, PATH_OBJECT + + "error_tsk.gif", true); //$NON-NLS-1$ + declareIdeWorkbenchImage(ideBundle, + IDEInternalWorkbenchImages.IMG_OBJS_WARNING_PATH, PATH_OBJECT + + "warn_tsk.gif", true); //$NON-NLS-1$ + declareIdeWorkbenchImage(ideBundle, + IDEInternalWorkbenchImages.IMG_OBJS_INFO_PATH, PATH_OBJECT + + "info_tsk.gif", true); //$NON-NLS-1$ } /** * Declares an IDE-specific workbench image. * * @param symbolicName * the symbolic name of the image * @param path * the path of the image file; this path is relative to the base * of the IDE plug-in * @param shared * <code>true</code> if this is a shared image, and * <code>false</code> if this is not a shared image * @see IWorkbenchConfigurer#declareImage */ private void declareIdeWorkbenchImage(Bundle ideBundle, String symbolicName, String path, boolean shared) { URL url = Platform.find(ideBundle, new Path(path)); ImageDescriptor desc = ImageDescriptor.createFromURL(url); getWorkbenchConfigurer().declareImage(symbolicName, desc, shared); } }
false
true
private void declareIdeWorkbenchImages() { final String ICONS_PATH = "$nl$/icons/full/";//$NON-NLS-1$ final String PATH_ETOOL = ICONS_PATH + "etool16/"; // Enabled toolbar icons.//$NON-NLS-1$ Bundle ideBundle = Platform.getBundle(IDEWorkbenchPlugin.IDE_WORKBENCH); declareIdeWorkbenchImage(ideBundle, IDEInternalWorkbenchImages.IMG_ETOOL_PROBLEM_CATEGORY, PATH_ETOOL + "problem_category.gif", true); //$NON-NLS-1$ }
private void declareIdeWorkbenchImages() { final String ICONS_PATH = "$nl$/icons/full/";//$NON-NLS-1$ final String PATH_ETOOL = ICONS_PATH + "etool16/"; // Enabled toolbar icons.//$NON-NLS-1$ final String PATH_OBJECT = ICONS_PATH + "obj16/"; // Model object icons//$NON-NLS-1$ Bundle ideBundle = Platform.getBundle(IDEWorkbenchPlugin.IDE_WORKBENCH); declareIdeWorkbenchImage(ideBundle, IDEInternalWorkbenchImages.IMG_ETOOL_PROBLEM_CATEGORY, PATH_ETOOL + "problem_category.gif", true); //$NON-NLS-1$ declareIdeWorkbenchImage(ideBundle, IDEInternalWorkbenchImages.IMG_OBJS_ERROR_PATH, PATH_OBJECT + "error_tsk.gif", true); //$NON-NLS-1$ declareIdeWorkbenchImage(ideBundle, IDEInternalWorkbenchImages.IMG_OBJS_WARNING_PATH, PATH_OBJECT + "warn_tsk.gif", true); //$NON-NLS-1$ declareIdeWorkbenchImage(ideBundle, IDEInternalWorkbenchImages.IMG_OBJS_INFO_PATH, PATH_OBJECT + "info_tsk.gif", true); //$NON-NLS-1$ }
diff --git a/src/org/openswing/swing/client/TextControl.java b/src/org/openswing/swing/client/TextControl.java index b16f015..fbce2ac 100644 --- a/src/org/openswing/swing/client/TextControl.java +++ b/src/org/openswing/swing/client/TextControl.java @@ -1,389 +1,390 @@ package org.openswing.swing.client; import javax.swing.JTextField; import javax.swing.UIManager; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.awt.Container; import org.openswing.swing.form.client.Form; import java.awt.event.*; import org.openswing.swing.message.receive.java.ValueObject; import javax.swing.JComponent; import java.awt.GridBagLayout; import java.awt.GridBagConstraints; import java.awt.Insets; import java.awt.FlowLayout; /** * <p>Title: OpenSwing Framework</p> * <p>Description: Text input control.</p> * <p>Copyright: Copyright (C) 2006 Mauro Carniel</p> * * <p> This file is part of OpenSwing Framework. * This library is free software; you can redistribute it and/or * modify it under the terms of the (LGPL) Lesser General Public * License as published by the Free Software Foundation; * * GNU LESSER GENERAL PUBLIC LICENSE * Version 2.1, February 1999 * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the Free * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * The author may be contacted at: * [email protected]</p> * * @author Mauro Carniel * @version 1.0 */ public class TextControl extends BaseInputControl implements InputControl { /** maximum number of characters */ private int maxCharacters = 255; /** flag used to translate the text on uppercase */ private boolean upperCase = false; /** flag used to trim the text */ private boolean trimText = false; /** flag used to right padding the text (related to maxCharacters property) */ private boolean rpadding = false; /** text field */ private TextBox textBox = new TextBox(); /** * Constructor. */ public TextControl() { this(10); } /** * Constructor. * @param columns number of visibile characters */ public TextControl(int columns) { textBox.setColumns(columns); textBox.setDisabledTextColor(UIManager.getColor("TextField.foreground")); this.setLayout(new GridBagLayout()); this.add(textBox, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0)); // setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0)); // this.add(textBox); addFocusListener(); addKeyListener(); initListeners(); } /** * Create a key listener to correcly set the content of the control. */ private void addKeyListener() { textBox.addKeyListener(new KeyAdapter() { public final void keyReleased(KeyEvent e) { e.consume(); } public final void keyTyped(KeyEvent e) { if (textBox.getText()!=null && textBox.getText().length()>=maxCharacters && e.getKeyChar()!='\b') { TextControl.this.setText(textBox.getText().substring(0,maxCharacters)); e.consume(); } - else if (textBox.getText()!=null && upperCase) { + else if (textBox.getText()!=null && + upperCase && + e.getKeyChar()>=' ') { TextControl.this.setText((textBox.getText()+String.valueOf(e.getKeyChar())).toUpperCase()); - if (e.getKeyChar()!='\b') - e.consume(); + e.consume(); } } public void keyPressed(KeyEvent e) { } }); } /** * Set maximum number of characters. * @param maxCharacters maximum number of characters */ public void setMaxCharacters(int maxCharacters) { this.maxCharacters = maxCharacters; } /** * @return maximum number of characters */ public int getMaxCharacters() { return maxCharacters; } /** * @return <code>true></code> to right padding the text (related to maxCharacters property) */ public boolean isRpadding() { return rpadding; } /** * @return <code>true></code> to trim the text */ public boolean isTrimText() { return trimText; } /** * @return <code>true></code> to translate the text on uppercase */ public boolean isUpperCase() { return upperCase; } /** * Set <code>true></code> to right padding the text (related to maxCharacters property). * @param rpadding <code>true></code> to right padding the text (related to maxCharacters property) */ public void setRpadding(boolean rpadding) { this.rpadding = rpadding; } /** * Set <code>true></code> to trim the text. * @param trimText <code>true></code> to trim the text */ public void setTrimText(boolean trimText) { this.trimText = trimText; } /** * Set <code>true></code> to translate the text on uppercase. * @param upperCase <code>true></code> to translate the text on uppercase */ public void setUpperCase(boolean upperCase) { this.upperCase = upperCase; } /** * Create a focus listener to correcly set the content of the control. */ private void addFocusListener() { textBox.addFocusListener(new FocusAdapter() { public void focusLost(FocusEvent e) { if (textBox.isEnabled() && textBox.isEditable()) { setText(textBox.getText()); } } }); } public final void setText(String text) { if (text==null) text = ""; if (upperCase) text = text.toUpperCase(); if (trimText) text = text.trim(); if (rpadding) { StringBuffer auxtext = new StringBuffer(text); for(int i=text.length();i<maxCharacters;i++) auxtext.append(" "); text = auxtext.toString(); } if (text.length()>maxCharacters) text = text.substring(0,maxCharacters); textBox.setText(text); } /** * Replace enabled setting with editable setting (this allow tab swithing). * @param enabled flag used to set abilitation of control */ public final void setEnabled(boolean enabled) { textBox.setEditable(enabled); textBox.setFocusable(enabled); } /** * @return current input control abilitation */ public final boolean isEnabled() { return textBox.isEditable(); } /** * @return value related to the input control */ public final Object getValue() { return textBox.getText(); } /** * @return input control text */ public final String getText() { return textBox.getText(); } /** * Set value to the input control. * @param value value to set into the input control */ public final void setValue(Object value) { setText((String)value); } /** * @return component inside this whose contains the value */ protected final JComponent getBindingComponent() { return textBox; } /** * Set input control visible characters. * @param columns visible characters */ public final void setColumns(int columns) { textBox.setColumns(columns); } /** * @return input control visibile characters */ public final int getColumns() { return textBox.getColumns(); } /** * Adds the specified focus listener to receive focus events from * this component when this component gains input focus. * If listener <code>l</code> is <code>null</code>, * no exception is thrown and no action is performed. * * @param l the focus listener * @see java.awt.event.FocusEvent * @see java.awt.event.FocusListener * @see #removeFocusListener * @see #getFocusListeners * @since JDK1.1 */ public final void addFocusListener(FocusListener listener) { try { textBox.addFocusListener(listener); } catch (Exception ex) { } } /** * Removes the specified focus listener so that it no longer * receives focus events from this component. This method performs * no function, nor does it throw an exception, if the listener * specified by the argument was not previously added to this component. * If listener <code>l</code> is <code>null</code>, * no exception is thrown and no action is performed. * * @param l the focus listener * @see java.awt.event.FocusEvent * @see java.awt.event.FocusListener * @see #addFocusListener * @see #getFocusListeners * @since JDK1.1 */ public final void removeFocusListener(FocusListener listener) { try { textBox.removeFocusListener(listener); } catch (Exception ex) { } } /** * Adds the specified action listener to receive * action events from this textfield. * * @param l the action listener to be added */ public final void addActionListener(ActionListener listener) { try { textBox.addActionListener(listener); } catch (Exception ex) { } } /** * Removes the specified action listener so that it no longer * receives action events from this textfield. * * @param l the action listener to be removed */ public final void removeActionListener(ActionListener listener) { try { textBox.removeActionListener(listener); } catch (Exception ex) { } } public void processKeyEvent(KeyEvent e) { textBox.processKeyEvent(e); } } /** * <p>Title: OpenSwing Framework</p> * <p>Description: Inner class used to redirect key event to the inner JTextField.</p> * <p>Copyright: Copyright (C) 2006 Mauro Carniel</p> * @author Mauro Carniel * @version 1.0 */ class TextBox extends JTextField { public void processKeyEvent(KeyEvent e) { super.processKeyEvent(e); } }
false
true
private void addKeyListener() { textBox.addKeyListener(new KeyAdapter() { public final void keyReleased(KeyEvent e) { e.consume(); } public final void keyTyped(KeyEvent e) { if (textBox.getText()!=null && textBox.getText().length()>=maxCharacters && e.getKeyChar()!='\b') { TextControl.this.setText(textBox.getText().substring(0,maxCharacters)); e.consume(); } else if (textBox.getText()!=null && upperCase) { TextControl.this.setText((textBox.getText()+String.valueOf(e.getKeyChar())).toUpperCase()); if (e.getKeyChar()!='\b') e.consume(); } } public void keyPressed(KeyEvent e) { } }); }
private void addKeyListener() { textBox.addKeyListener(new KeyAdapter() { public final void keyReleased(KeyEvent e) { e.consume(); } public final void keyTyped(KeyEvent e) { if (textBox.getText()!=null && textBox.getText().length()>=maxCharacters && e.getKeyChar()!='\b') { TextControl.this.setText(textBox.getText().substring(0,maxCharacters)); e.consume(); } else if (textBox.getText()!=null && upperCase && e.getKeyChar()>=' ') { TextControl.this.setText((textBox.getText()+String.valueOf(e.getKeyChar())).toUpperCase()); e.consume(); } } public void keyPressed(KeyEvent e) { } }); }
diff --git a/src/ui/Coordinate.java b/src/ui/Coordinate.java index 8d3b039..67cd04d 100644 --- a/src/ui/Coordinate.java +++ b/src/ui/Coordinate.java @@ -1,19 +1,20 @@ package ui; public class Coordinate { public int x; public int y; public Coordinate(int x, int y) { this.x = x; this.y = y; } @Override public boolean equals(Object a) { boolean t = false; - if ((((Coordinate) a).x == x) && (((Coordinate) a).y == y)) + if ((a instanceof Coordinate) && (((Coordinate) a).x == x) + && (((Coordinate) a).y == y)) t = true; return t; } }
true
true
public boolean equals(Object a) { boolean t = false; if ((((Coordinate) a).x == x) && (((Coordinate) a).y == y)) t = true; return t; }
public boolean equals(Object a) { boolean t = false; if ((a instanceof Coordinate) && (((Coordinate) a).x == x) && (((Coordinate) a).y == y)) t = true; return t; }
diff --git a/net.beaconcontroller.routing/src/main/java/net/beaconcontroller/routing/internal/Routing.java b/net.beaconcontroller.routing/src/main/java/net/beaconcontroller/routing/internal/Routing.java index f48bf1f..3139592 100644 --- a/net.beaconcontroller.routing/src/main/java/net/beaconcontroller/routing/internal/Routing.java +++ b/net.beaconcontroller.routing/src/main/java/net/beaconcontroller/routing/internal/Routing.java @@ -1,250 +1,260 @@ package net.beaconcontroller.routing.internal; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; import net.beaconcontroller.core.IBeaconProvider; import net.beaconcontroller.core.IOFMessageListener; import net.beaconcontroller.core.IOFSwitch; import net.beaconcontroller.core.io.OFMessageSafeOutStream; import net.beaconcontroller.devicemanager.Device; import net.beaconcontroller.devicemanager.IDeviceManager; import net.beaconcontroller.devicemanager.IDeviceManagerAware; import net.beaconcontroller.routing.IRoutingEngine; import net.beaconcontroller.routing.Link; import net.beaconcontroller.routing.Route; import org.openflow.io.OFMessageInStream; import org.openflow.protocol.OFFlowMod; import org.openflow.protocol.OFMatch; import org.openflow.protocol.OFMessage; import org.openflow.protocol.OFPacketIn; import org.openflow.protocol.OFPacketOut; import org.openflow.protocol.OFPort; import org.openflow.protocol.OFType; import org.openflow.protocol.action.OFAction; import org.openflow.protocol.action.OFActionOutput; import org.openflow.protocol.factory.OFMessageFactory; import org.openflow.util.HexString; import org.openflow.util.U16; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author David Erickson ([email protected]) */ public class Routing implements IOFMessageListener, IDeviceManagerAware { protected static Logger log = LoggerFactory.getLogger(Routing.class); protected IBeaconProvider beaconProvider; protected IDeviceManager deviceManager; protected IRoutingEngine routingEngine; public void startUp() { beaconProvider.addOFMessageListener(OFType.PACKET_IN, this); } public void shutDown() { beaconProvider.removeOFMessageListener(OFType.PACKET_IN, this); } @Override public String getName() { return "routing"; } @Override public Command receive(IOFSwitch sw, OFMessage msg) { OFPacketIn pi = (OFPacketIn) msg; OFMatch match = new OFMatch(); match.loadFromPacket(pi.getPacketData(), pi.getInPort()); // Check if we have the location of the destination Device dstDevice = deviceManager.getDeviceByDataLayerAddress(match.getDataLayerDestination()); if (dstDevice != null) { // does a route exist? Route route = routingEngine.getRoute(sw.getId(), dstDevice.getSw().getId()); if (route != null) { // set the route if (log.isTraceEnabled()) log.trace("Pushing route match={} route={} destination={}:{}", new Object[] {match, route, dstDevice.getSw(), dstDevice.getSwPort()}); OFMessageInStream in = sw.getInputStream(); pushRoute(in.getMessageFactory(), match, route, dstDevice, pi.getBufferId()); // send the packet if its not buffered if (pi.getBufferId() == 0xffffffff) { pushPacket(in.getMessageFactory(), sw, match, pi); } return Command.STOP; } else { if (log.isTraceEnabled()) { log.trace("No route found from {}:{} to device {}", new Object[] { HexString.toHexString(sw.getId()), pi.getInPort(), dstDevice }); } } } else { if (log.isTraceEnabled()) { // filter multicast destinations if ((match.getDataLayerDestination()[0] & 0x1) == 0) { log.trace("Unable to locate device with address {}", HexString.toHexString(match .getDataLayerDestination())); } } } return Command.CONTINUE; } /** * Push routes from back to front * @param factory * @param match * @param route * @param dstDevice */ public void pushRoute(OFMessageFactory factory, OFMatch match, Route route, Device dstDevice, int bufferId) { OFFlowMod fm = (OFFlowMod) factory.getMessage(OFType.FLOW_MOD); OFActionOutput action = new OFActionOutput(); List<OFAction> actions = new ArrayList<OFAction>(); actions.add(action); fm.setIdleTimeout((short)5) .setBufferId(0xffffffff) .setMatch(match.clone()) .setActions(actions) .setLengthU(OFFlowMod.MINIMUM_LENGTH+OFActionOutput.MINIMUM_LENGTH); IOFSwitch sw = beaconProvider.getSwitches().get(route.getId().getDst()); OFMessageSafeOutStream out = sw.getOutputStream(); // to prevent NoClassDefFoundError ((OFActionOutput)fm.getActions().get(0)).setPort(dstDevice.getSwPort()); for (int i = route.getPath().size() - 1; i >= 0; --i) { Link link = route.getPath().get(i); fm.getMatch().setInputPort(link.getInPort()); try { out.write(fm); } catch (IOException e) { log.error("Failure writing flow mod", e); } try { fm = fm.clone(); } catch (CloneNotSupportedException e) { log.error("Failure cloning flow mod", e); } // setup for the next loop iteration ((OFActionOutput)fm.getActions().get(0)).setPort(link.getOutPort()); if (i > 0) { sw = beaconProvider.getSwitches().get(route.getPath().get(i-1).getDst()); } else { sw = beaconProvider.getSwitches().get(route.getId().getSrc()); } + if (sw == null) { + if (log.isWarnEnabled()) { + log.warn( + "Unable to push route, switch at DPID {} not available", + (i > 0) ? HexString.toHexString(route.getPath() + .get(i - 1).getDst()) : HexString + .toHexString(route.getId().getSrc())); + } + return; + } out = sw.getOutputStream(); } // set the original match for the first switch, and buffer id fm.setMatch(match) .setBufferId(bufferId); try { out.write(fm); } catch (IOException e) { log.error("Failure writing flow mod", e); } } public void pushPacket(OFMessageFactory factory, IOFSwitch sw, OFMatch match, OFPacketIn pi) { OFPacketOut po = (OFPacketOut) factory.getMessage(OFType.PACKET_OUT); po.setBufferId(pi.getBufferId()); po.setInPort(pi.getInPort()); // set actions List<OFAction> actions = new ArrayList<OFAction>(); actions.add(new OFActionOutput(OFPort.OFPP_TABLE.getValue(), (short) 0)); po.setActions(actions) .setActionsLength((short) OFActionOutput.MINIMUM_LENGTH); byte[] packetData = pi.getPacketData(); po.setLength(U16.t(OFPacketOut.MINIMUM_LENGTH + po.getActionsLength() + packetData.length)); po.setPacketData(packetData); try { sw.getOutputStream().write(po); } catch (IOException e) { log.error("Failure writing packet out", e); } } /** * @param beaconProvider the beaconProvider to set */ public void setBeaconProvider(IBeaconProvider beaconProvider) { this.beaconProvider = beaconProvider; } /** * @param routingEngine the routingEngine to set */ public void setRoutingEngine(IRoutingEngine routingEngine) { this.routingEngine = routingEngine; } /** * @param deviceManager the deviceManager to set */ public void setDeviceManager(IDeviceManager deviceManager) { this.deviceManager = deviceManager; } @Override public void deviceAdded(Device device) { // NOOP } @Override public void deviceRemoved(Device device) { // NOOP } @Override public void deviceMoved(Device device, IOFSwitch oldSw, Short oldPort, IOFSwitch sw, Short port) { // Build flow mod to delete based on destination mac == device mac OFMatch match = new OFMatch(); match.setDataLayerDestination(device.getDataLayerAddress()); match.setWildcards(OFMatch.OFPFW_ALL ^ OFMatch.OFPFW_DL_DST); OFFlowMod fm = (OFFlowMod) sw.getInputStream().getMessageFactory() .getMessage(OFType.FLOW_MOD); fm.setCommand(OFFlowMod.OFPFC_DELETE) .setOutPort((short) OFPort.OFPP_NONE.getValue()) .setMatch(match) .setActions(Collections.EMPTY_LIST) .setLength(U16.t(OFFlowMod.MINIMUM_LENGTH)); // Flush to all switches for (IOFSwitch outSw : beaconProvider.getSwitches().values()) { try { outSw.getOutputStream().write(fm); } catch (IOException e) { log.error("Failure sending flow mod delete for moved device", e); } } } @Override public void deviceNetworkAddressAdded(Device device, Set<Integer> networkAddresses, Integer networkAddress) { // NOOP } @Override public void deviceNetworkAddressRemoved(Device device, Set<Integer> networkAddresses, Integer networkAddress) { // NOOP } }
true
true
public void pushRoute(OFMessageFactory factory, OFMatch match, Route route, Device dstDevice, int bufferId) { OFFlowMod fm = (OFFlowMod) factory.getMessage(OFType.FLOW_MOD); OFActionOutput action = new OFActionOutput(); List<OFAction> actions = new ArrayList<OFAction>(); actions.add(action); fm.setIdleTimeout((short)5) .setBufferId(0xffffffff) .setMatch(match.clone()) .setActions(actions) .setLengthU(OFFlowMod.MINIMUM_LENGTH+OFActionOutput.MINIMUM_LENGTH); IOFSwitch sw = beaconProvider.getSwitches().get(route.getId().getDst()); OFMessageSafeOutStream out = sw.getOutputStream(); // to prevent NoClassDefFoundError ((OFActionOutput)fm.getActions().get(0)).setPort(dstDevice.getSwPort()); for (int i = route.getPath().size() - 1; i >= 0; --i) { Link link = route.getPath().get(i); fm.getMatch().setInputPort(link.getInPort()); try { out.write(fm); } catch (IOException e) { log.error("Failure writing flow mod", e); } try { fm = fm.clone(); } catch (CloneNotSupportedException e) { log.error("Failure cloning flow mod", e); } // setup for the next loop iteration ((OFActionOutput)fm.getActions().get(0)).setPort(link.getOutPort()); if (i > 0) { sw = beaconProvider.getSwitches().get(route.getPath().get(i-1).getDst()); } else { sw = beaconProvider.getSwitches().get(route.getId().getSrc()); } out = sw.getOutputStream(); } // set the original match for the first switch, and buffer id fm.setMatch(match) .setBufferId(bufferId); try { out.write(fm); } catch (IOException e) { log.error("Failure writing flow mod", e); } }
public void pushRoute(OFMessageFactory factory, OFMatch match, Route route, Device dstDevice, int bufferId) { OFFlowMod fm = (OFFlowMod) factory.getMessage(OFType.FLOW_MOD); OFActionOutput action = new OFActionOutput(); List<OFAction> actions = new ArrayList<OFAction>(); actions.add(action); fm.setIdleTimeout((short)5) .setBufferId(0xffffffff) .setMatch(match.clone()) .setActions(actions) .setLengthU(OFFlowMod.MINIMUM_LENGTH+OFActionOutput.MINIMUM_LENGTH); IOFSwitch sw = beaconProvider.getSwitches().get(route.getId().getDst()); OFMessageSafeOutStream out = sw.getOutputStream(); // to prevent NoClassDefFoundError ((OFActionOutput)fm.getActions().get(0)).setPort(dstDevice.getSwPort()); for (int i = route.getPath().size() - 1; i >= 0; --i) { Link link = route.getPath().get(i); fm.getMatch().setInputPort(link.getInPort()); try { out.write(fm); } catch (IOException e) { log.error("Failure writing flow mod", e); } try { fm = fm.clone(); } catch (CloneNotSupportedException e) { log.error("Failure cloning flow mod", e); } // setup for the next loop iteration ((OFActionOutput)fm.getActions().get(0)).setPort(link.getOutPort()); if (i > 0) { sw = beaconProvider.getSwitches().get(route.getPath().get(i-1).getDst()); } else { sw = beaconProvider.getSwitches().get(route.getId().getSrc()); } if (sw == null) { if (log.isWarnEnabled()) { log.warn( "Unable to push route, switch at DPID {} not available", (i > 0) ? HexString.toHexString(route.getPath() .get(i - 1).getDst()) : HexString .toHexString(route.getId().getSrc())); } return; } out = sw.getOutputStream(); } // set the original match for the first switch, and buffer id fm.setMatch(match) .setBufferId(bufferId); try { out.write(fm); } catch (IOException e) { log.error("Failure writing flow mod", e); } }
diff --git a/io-impl/impl/src/main/java/org/cytoscape/io/internal/util/vizmap/CalculatorConverter.java b/io-impl/impl/src/main/java/org/cytoscape/io/internal/util/vizmap/CalculatorConverter.java index 85f5cd3fd..6244409d8 100644 --- a/io-impl/impl/src/main/java/org/cytoscape/io/internal/util/vizmap/CalculatorConverter.java +++ b/io-impl/impl/src/main/java/org/cytoscape/io/internal/util/vizmap/CalculatorConverter.java @@ -1,497 +1,497 @@ package org.cytoscape.io.internal.util.vizmap; /* * #%L * Cytoscape IO Impl (io-impl) * $Id:$ * $HeadURL:$ * %% * Copyright (C) 2010 - 2013 The Cytoscape Consortium * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.math.BigDecimal; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import org.cytoscape.io.internal.util.vizmap.model.AttributeType; import org.cytoscape.io.internal.util.vizmap.model.ContinuousMapping; import org.cytoscape.io.internal.util.vizmap.model.ContinuousMappingPoint; import org.cytoscape.io.internal.util.vizmap.model.Dependency; import org.cytoscape.io.internal.util.vizmap.model.DiscreteMapping; import org.cytoscape.io.internal.util.vizmap.model.DiscreteMappingEntry; import org.cytoscape.io.internal.util.vizmap.model.PassthroughMapping; import org.cytoscape.io.internal.util.vizmap.model.VisualProperty; import org.cytoscape.io.internal.util.vizmap.model.VisualStyle; import org.cytoscape.model.CyEdge; import org.cytoscape.model.CyNetwork; import org.cytoscape.model.CyNode; import org.cytoscape.model.CyIdentifiable; /** * Converter for Cytoscape 2.x calculators, which are serialized as a properties file * (session_vizmap.props file in the .cys file). * @author Christian * @param <T> */ public class CalculatorConverter { /** This type corresponds to java.lang.Boolean. */ public static final byte TYPE_BOOLEAN = 1; /** This type corresponds to java.lang.Double. */ public static final byte TYPE_FLOATING_POINT = 2; /** This type corresponds to java.lang.Integer. */ public static final byte TYPE_INTEGER = 3; /** This type corresponds to java.lang.String. */ public static final byte TYPE_STRING = 4; /** This type corresponds to an attribute which has not been defined. */ public static final byte TYPE_UNDEFINED = -1; /** * This type corresponds to a 'simple' list. * <P> * A 'simple' list is defined as follows: * <UL> * <LI>All items within the list are of the same type, and are chosen from * one of the following: <CODE>Boolean</CODE>, <CODE>Integer</CODE>, * <CODE>Double</CODE> or <CODE>String</CODE>. * </UL> */ public static final byte TYPE_SIMPLE_LIST = -2; private String propsKey; private String legacyPropsKey; private String key; private String legacyKey; private String visualPropertyId; private Class<? extends CyIdentifiable> targetType; private static final Map<Class<? extends CyIdentifiable>, Map<String, CalculatorConverter>> converters; /** old_style -> new_style */ private static final Map<String, String> oldLineStyles; /** old_color -> new_color */ private static final Map<String, String> oldArrowColors; static { converters = new HashMap<Class<? extends CyIdentifiable>, Map<String, CalculatorConverter>>(); converters.put(CyNode.class, new HashMap<String, CalculatorConverter>()); converters.put(CyEdge.class, new HashMap<String, CalculatorConverter>()); converters.put(CyNetwork.class, new HashMap<String, CalculatorConverter>()); oldLineStyles = new HashMap<String, String>(); oldLineStyles.put("", "SOLID"); oldLineStyles.put("LINE", "SOLID"); oldLineStyles.put("DASHED", "EQUAL_DASH"); oldArrowColors = new HashMap<String, String>(); oldArrowColors.put("WHITE", "255,255,255"); oldArrowColors.put("BLACK", "0,0,0"); } CalculatorConverter(final String propsKey, String legacyPropsKey) { this.propsKey = propsKey; // Make legacy key null if it's actually the same as the new key, so we know it was never an old key legacyPropsKey = propsKey.equalsIgnoreCase(legacyPropsKey) ? null : legacyPropsKey; this.legacyPropsKey = legacyPropsKey; this.key = propsKey.split("\\.")[2]; this.legacyKey = legacyPropsKey != null ? legacyPropsKey.split("\\.")[2] : null; this.visualPropertyId = parseVisualPropertyId(key); this.targetType = parseTargetDataType(key); } public void convert(VisualStyle vs, String propsValue, Properties props) { if (isDependency(propsKey)) { setDependency(vs, propsValue); } else if (isDefaultProperty(propsKey)) { // e.g. "globalAppearanceCalculator.MyStyle.defaultBackgroundColor" setDefaultProperty(vs, propsValue); } else if (isMappingFunction(propsKey)) { // e.g. "edgeAppearanceCalculator.MyStyle.edgeColorCalculator" setMappingFunction(vs, propsValue, props); } } // Accessors -------------- /** * @return The key used in the Visual Lexicon lookup. */ public String getVisualPropertyId() { return visualPropertyId; } // Private methods -------------- private String updateLegacyValue(String value) { if (value != null) { if (legacyPropsKey != null) { // The value is from older calculators and need to be updated! if (key.matches("(?i)(default)?(node|edge)LineStyle(Calculator)?")) { // Convert the former line type (e.g. LINE_1, LINE_2, DASHED_1) to // current line style String[] vv = value.split("_"); if (vv.length == 2) return oldLineStyles.get(vv[0]); } else if (key.matches("(?i)(default)?(node|edge)LineWidth(Calculator)?")) { // Convert the former line type to current line width String[] vv = value.split("_"); if (vv.length == 2) return vv[1]; } else if (key.matches("(?i)(default)?Edge(Source|Target)ArrowColor(Calculator)?")) { // Convert the former arrow property value (e.g. NONE, // WHITE_DIAMOND, BLACK_DIAMOND) to color if (!value.equalsIgnoreCase("NONE")) { String[] vv = value.split("_"); if (vv.length == 2) return oldArrowColors.get(vv[0]); } } else if (key.matches("(?i)(default)?Edge(Source|Target)ArrowShape(Calculator)?")) { // Convert the former arrow property value to shape if (value.equalsIgnoreCase("NONE")) { return "NONE"; } else { String[] vv = value.split("_"); if (vv.length == 2) return vv[1]; } } else { return value; } } else { // No need to update the value return value; } } return null; } /** * @param props * All the visual properties * @param mapperName * Example: "MyStyle-Edge Color-Discrete Mapper" * @return A {@link org.cytoscape.io.internal.util.vizmap.model.DiscreteMapping}, * {@link org.cytoscape.io.internal.util.vizmap.model.ContinuousMapping} or * {@link org.cytoscape.io.internal.util.vizmap.model.PassThroughMapping} object */ private Object getMappingFunction(Properties props, String mapperName, VisualProperty vp) { String baseKey = null; String functionType = null; while (functionType == null) { // e.g. "edgeColorCalculator.MyStyle-Edge Color-Discrete Mapper.mapping." baseKey = (legacyKey != null ? legacyKey : key) + "." + mapperName + ".mapping."; functionType = props.getProperty(baseKey + "type"); if (functionType == null) { // Try with Cytoscape v2.3 calculator names... if (baseKey.startsWith("nodeFillColorCalculator.")) { legacyKey = "nodeColorCalculator"; } else if (baseKey.startsWith("edgeSourceArrowCalculator.") || baseKey.startsWith("edgeTargetArrowCalculator.")) { legacyKey = "edgeArrowCalculator"; } else { return null; } } } String attrName = props.getProperty(baseKey + "controller"); if (attrName == null) return null; // "ID" is actually the "name" column!!! if ("ID".equalsIgnoreCase(attrName)) attrName = "name"; if ("DiscreteMapping".equalsIgnoreCase(functionType)) { String controllerTypeProp = props.getProperty(baseKey + "controllerType"); byte controllerType = controllerTypeProp != null ? Byte.parseByte(controllerTypeProp) : TYPE_STRING; AttributeType attrType = null; if (attrName.equals("has_nested_network")) { // Force to boolean (in Cy2, this attribute is a "yes\no" string type) attrType = AttributeType.BOOLEAN; } else { switch (controllerType) { case TYPE_BOOLEAN: attrType = AttributeType.BOOLEAN; break; case TYPE_FLOATING_POINT: attrType = AttributeType.FLOAT; break; case TYPE_INTEGER: attrType = AttributeType.INTEGER; break; default: attrType = AttributeType.STRING; break; } } DiscreteMapping dm = new DiscreteMapping(); dm.setAttributeName(attrName); dm.setAttributeType(attrType); String entryKey = baseKey + "map."; for (String sk : props.stringPropertyNames()) { if (sk.contains(entryKey)) { - String attrValue = sk.replaceAll(entryKey, ""); + String attrValue = sk.replace(entryKey, ""); String sv = props.getProperty(sk); String value = getValue(sv); if (attrName.equals("has_nested_network")) attrValue = attrValue.matches("(?i)yes|true") ? "true" : "false"; DiscreteMappingEntry entry = new DiscreteMappingEntry(); entry.setAttributeValue(attrValue); entry.setValue(value); dm.getDiscreteMappingEntry().add(entry); } } return dm; } else if ("ContinuousMapping".equalsIgnoreCase(functionType)) { ContinuousMapping cm = new ContinuousMapping(); cm.setAttributeName(attrName); cm.setAttributeType(AttributeType.FLOAT); int boundaryValues = 0; try { String s = props.getProperty(baseKey + "boundaryvalues"); boundaryValues = Integer.parseInt(s); } catch (NumberFormatException nfe) { // TODO: warning } for (int i = 0; i < boundaryValues; i++) { try { BigDecimal value = new BigDecimal(props.getProperty(baseKey + "bv" + i + ".domainvalue")); String lesser = getValue(props.getProperty(baseKey + "bv" + i + ".lesser")); String equal = getValue(props.getProperty(baseKey + "bv" + i + ".equal")); String greater = getValue(props.getProperty(baseKey + "bv" + i + ".greater")); ContinuousMappingPoint point = new ContinuousMappingPoint(); point.setAttrValue(value); point.setLesserValue(lesser); point.setEqualValue(equal); point.setGreaterValue(greater); cm.getContinuousMappingPoint().add(point); } catch (Exception e) { // TODO: warning } } return cm; } else if ("PassThroughMapping".equalsIgnoreCase(functionType)) { PassthroughMapping pm = new PassthroughMapping(); pm.setAttributeName(attrName); // Cy2 doesn't write the "controllerType" property for PassThroughMappings, so just set STRING // (it should work, anyway). pm.setAttributeType(AttributeType.STRING); return pm; } return null; } private void setDefaultProperty(VisualStyle vs, String sValue) { VisualProperty vp = getVisualProperty(vs); String value = getValue(sValue); vp.setDefault(value); } private void setMappingFunction(VisualStyle vs, String sValue, Properties props) { VisualProperty vp = getVisualProperty(vs); Object mapping = getMappingFunction(props, sValue, vp); if (mapping instanceof PassthroughMapping) vp.setPassthroughMapping((PassthroughMapping) mapping); else if (mapping instanceof ContinuousMapping) vp.setContinuousMapping((ContinuousMapping) mapping); else if (mapping instanceof DiscreteMapping) vp.setDiscreteMapping((DiscreteMapping) mapping); } private void setDependency(VisualStyle vs, String sValue) { Dependency d = new Dependency(); d.setName(visualPropertyId); d.setValue(new Boolean(sValue.trim())); if (targetType == CyNetwork.class) { vs.getNetwork().getDependency().add(d); } else if (targetType == CyNode.class) { vs.getNode().getDependency().add(d); } else if (targetType == CyEdge.class) { vs.getEdge().getDependency().add(d); } } /** * Get or create a new Visual Property for the passed Visual Style. * It checks if the property already exists in Network, Nodes or Edges, according to the dataType. If it does not * exist, the property is created and added to the style. * @param vs * @return */ private VisualProperty getVisualProperty(VisualStyle vs) { VisualProperty vp = null; List<VisualProperty> vpList = null; if (targetType == CyNetwork.class) { vpList = vs.getNetwork().getVisualProperty(); } else if (targetType == CyNode.class) { vpList = vs.getNode().getVisualProperty(); } else if (targetType == CyEdge.class) { vpList = vs.getEdge().getVisualProperty(); } for (VisualProperty v : vpList) { if (v.getName().equalsIgnoreCase(visualPropertyId)) { // The Visual Property has already been created... vp = v; break; } } if (vp == null) { // The Visual Property has not been created yet... vp = new VisualProperty(); vp.setName(visualPropertyId); vpList.add(vp); } return vp; } private String getValue(String sValue) { if (sValue != null) sValue = updateLegacyValue(sValue); return sValue; } // static parsing methods -------------- /** * @param key the Properties key * @return The name of the visual style or null if the property key doesn't or shouldn't have it */ public static String parseStyleName(String key) { String styleName = null; if (key != null) { String[] tokens = key.split("\\."); if (tokens.length > 2 && tokens[0].matches("(node|edge|global)[a-zA-Z]+Calculator")) { // It seems to be a valid entry... if (tokens.length == 3) { String t3 = tokens[2]; if (t3.matches("nodeSizeLocked|arrowColorMatchesEdge|nodeLabelColorFromNodeColor|" + "defaultNodeShowNestedNetwork|nodeCustomGraphicsSizeSync|" + "((node|edge)LabelColor)|" + "((node|edge)[a-zA-Z]+Calculator)|" + "(default(Node|Edge|Background|SloppySelection)[a-zA-Z0-9]+)")) { // It looks like the second token is the style name! styleName = tokens[1]; } } } } return styleName; } static boolean isConvertible(String propsKey) { return isDefaultProperty(propsKey) || isDependency(propsKey) || isMappingFunction(propsKey); } static boolean isDefaultProperty(String key) { boolean b = false; if (key != null) { // Globals b |= key.matches("globalAppearanceCalculator\\.[^\\.]+\\.default[a-zA-Z]+Color"); // Nodes b |= key.matches("nodeAppearanceCalculator\\.[^\\.]+\\.default(Node|NODE)\\w+"); // Edges b |= key.matches("edgeAppearanceCalculator\\.[^\\.]+\\.default(Edge|EDGE)[a-zA-Z_]+"); } return b; } static boolean isMappingFunction(String key) { boolean b = false; if (key != null) { b |= key.matches("(?i)(node|edge)AppearanceCalculator\\.[^\\.]+\\." + "\\1((CustomGraphics(Position)?\\d+)|LabelColor|([a-zA-Z_]+Calculator))"); } return b; } static boolean isDependency(String key) { boolean b = false; if (key != null) { // We need to distinguish node dependencies from edge dependencies because in // some old versions of vizmap.props (e.g. 2.5 era) we would see a dependency // (e.g. nodeSizeLocked) listed under both nodeAppearanceCalculator and // edgeAppearanceCalculator, which means two Dependency objects get mapped // to the same "nodeSizeLocked" VisualPropertyDependency. b |= key.matches("nodeAppearanceCalculator\\.[^\\.]+\\." + "(nodeSizeLocked|nodeLabelColorFromNodeColor|nodeCustomGraphicsSizeSync)"); b |= key.matches("edgeAppearanceCalculator\\.[^\\.]+\\.arrowColorMatchesEdge"); } return b; } static Class<? extends CyIdentifiable> parseTargetDataType(String calcKey) { calcKey = calcKey.toLowerCase(); if (calcKey.contains("node")) return CyNode.class; if (calcKey.contains("edge")) return CyEdge.class; return CyNetwork.class; } static String parseVisualPropertyId(String calcKey) { if (calcKey != null) { return calcKey.replaceAll("(?i)default|calculator|uniform", "").toLowerCase().trim(); } return calcKey; } @Override public String toString() { return "CalculatorConverter [propsKey=" + propsKey + ", legacyPropsKey=" + legacyPropsKey + ", key=" + key + ", legacyKey=" + legacyKey + ", visualPropertyId=" + visualPropertyId + ", targetType=" + targetType + "]"; } }
true
true
private Object getMappingFunction(Properties props, String mapperName, VisualProperty vp) { String baseKey = null; String functionType = null; while (functionType == null) { // e.g. "edgeColorCalculator.MyStyle-Edge Color-Discrete Mapper.mapping." baseKey = (legacyKey != null ? legacyKey : key) + "." + mapperName + ".mapping."; functionType = props.getProperty(baseKey + "type"); if (functionType == null) { // Try with Cytoscape v2.3 calculator names... if (baseKey.startsWith("nodeFillColorCalculator.")) { legacyKey = "nodeColorCalculator"; } else if (baseKey.startsWith("edgeSourceArrowCalculator.") || baseKey.startsWith("edgeTargetArrowCalculator.")) { legacyKey = "edgeArrowCalculator"; } else { return null; } } } String attrName = props.getProperty(baseKey + "controller"); if (attrName == null) return null; // "ID" is actually the "name" column!!! if ("ID".equalsIgnoreCase(attrName)) attrName = "name"; if ("DiscreteMapping".equalsIgnoreCase(functionType)) { String controllerTypeProp = props.getProperty(baseKey + "controllerType"); byte controllerType = controllerTypeProp != null ? Byte.parseByte(controllerTypeProp) : TYPE_STRING; AttributeType attrType = null; if (attrName.equals("has_nested_network")) { // Force to boolean (in Cy2, this attribute is a "yes\no" string type) attrType = AttributeType.BOOLEAN; } else { switch (controllerType) { case TYPE_BOOLEAN: attrType = AttributeType.BOOLEAN; break; case TYPE_FLOATING_POINT: attrType = AttributeType.FLOAT; break; case TYPE_INTEGER: attrType = AttributeType.INTEGER; break; default: attrType = AttributeType.STRING; break; } } DiscreteMapping dm = new DiscreteMapping(); dm.setAttributeName(attrName); dm.setAttributeType(attrType); String entryKey = baseKey + "map."; for (String sk : props.stringPropertyNames()) { if (sk.contains(entryKey)) { String attrValue = sk.replaceAll(entryKey, ""); String sv = props.getProperty(sk); String value = getValue(sv); if (attrName.equals("has_nested_network")) attrValue = attrValue.matches("(?i)yes|true") ? "true" : "false"; DiscreteMappingEntry entry = new DiscreteMappingEntry(); entry.setAttributeValue(attrValue); entry.setValue(value); dm.getDiscreteMappingEntry().add(entry); } } return dm; } else if ("ContinuousMapping".equalsIgnoreCase(functionType)) { ContinuousMapping cm = new ContinuousMapping(); cm.setAttributeName(attrName); cm.setAttributeType(AttributeType.FLOAT); int boundaryValues = 0; try { String s = props.getProperty(baseKey + "boundaryvalues"); boundaryValues = Integer.parseInt(s); } catch (NumberFormatException nfe) { // TODO: warning } for (int i = 0; i < boundaryValues; i++) { try { BigDecimal value = new BigDecimal(props.getProperty(baseKey + "bv" + i + ".domainvalue")); String lesser = getValue(props.getProperty(baseKey + "bv" + i + ".lesser")); String equal = getValue(props.getProperty(baseKey + "bv" + i + ".equal")); String greater = getValue(props.getProperty(baseKey + "bv" + i + ".greater")); ContinuousMappingPoint point = new ContinuousMappingPoint(); point.setAttrValue(value); point.setLesserValue(lesser); point.setEqualValue(equal); point.setGreaterValue(greater); cm.getContinuousMappingPoint().add(point); } catch (Exception e) { // TODO: warning } } return cm; } else if ("PassThroughMapping".equalsIgnoreCase(functionType)) { PassthroughMapping pm = new PassthroughMapping(); pm.setAttributeName(attrName); // Cy2 doesn't write the "controllerType" property for PassThroughMappings, so just set STRING // (it should work, anyway). pm.setAttributeType(AttributeType.STRING); return pm; } return null; }
private Object getMappingFunction(Properties props, String mapperName, VisualProperty vp) { String baseKey = null; String functionType = null; while (functionType == null) { // e.g. "edgeColorCalculator.MyStyle-Edge Color-Discrete Mapper.mapping." baseKey = (legacyKey != null ? legacyKey : key) + "." + mapperName + ".mapping."; functionType = props.getProperty(baseKey + "type"); if (functionType == null) { // Try with Cytoscape v2.3 calculator names... if (baseKey.startsWith("nodeFillColorCalculator.")) { legacyKey = "nodeColorCalculator"; } else if (baseKey.startsWith("edgeSourceArrowCalculator.") || baseKey.startsWith("edgeTargetArrowCalculator.")) { legacyKey = "edgeArrowCalculator"; } else { return null; } } } String attrName = props.getProperty(baseKey + "controller"); if (attrName == null) return null; // "ID" is actually the "name" column!!! if ("ID".equalsIgnoreCase(attrName)) attrName = "name"; if ("DiscreteMapping".equalsIgnoreCase(functionType)) { String controllerTypeProp = props.getProperty(baseKey + "controllerType"); byte controllerType = controllerTypeProp != null ? Byte.parseByte(controllerTypeProp) : TYPE_STRING; AttributeType attrType = null; if (attrName.equals("has_nested_network")) { // Force to boolean (in Cy2, this attribute is a "yes\no" string type) attrType = AttributeType.BOOLEAN; } else { switch (controllerType) { case TYPE_BOOLEAN: attrType = AttributeType.BOOLEAN; break; case TYPE_FLOATING_POINT: attrType = AttributeType.FLOAT; break; case TYPE_INTEGER: attrType = AttributeType.INTEGER; break; default: attrType = AttributeType.STRING; break; } } DiscreteMapping dm = new DiscreteMapping(); dm.setAttributeName(attrName); dm.setAttributeType(attrType); String entryKey = baseKey + "map."; for (String sk : props.stringPropertyNames()) { if (sk.contains(entryKey)) { String attrValue = sk.replace(entryKey, ""); String sv = props.getProperty(sk); String value = getValue(sv); if (attrName.equals("has_nested_network")) attrValue = attrValue.matches("(?i)yes|true") ? "true" : "false"; DiscreteMappingEntry entry = new DiscreteMappingEntry(); entry.setAttributeValue(attrValue); entry.setValue(value); dm.getDiscreteMappingEntry().add(entry); } } return dm; } else if ("ContinuousMapping".equalsIgnoreCase(functionType)) { ContinuousMapping cm = new ContinuousMapping(); cm.setAttributeName(attrName); cm.setAttributeType(AttributeType.FLOAT); int boundaryValues = 0; try { String s = props.getProperty(baseKey + "boundaryvalues"); boundaryValues = Integer.parseInt(s); } catch (NumberFormatException nfe) { // TODO: warning } for (int i = 0; i < boundaryValues; i++) { try { BigDecimal value = new BigDecimal(props.getProperty(baseKey + "bv" + i + ".domainvalue")); String lesser = getValue(props.getProperty(baseKey + "bv" + i + ".lesser")); String equal = getValue(props.getProperty(baseKey + "bv" + i + ".equal")); String greater = getValue(props.getProperty(baseKey + "bv" + i + ".greater")); ContinuousMappingPoint point = new ContinuousMappingPoint(); point.setAttrValue(value); point.setLesserValue(lesser); point.setEqualValue(equal); point.setGreaterValue(greater); cm.getContinuousMappingPoint().add(point); } catch (Exception e) { // TODO: warning } } return cm; } else if ("PassThroughMapping".equalsIgnoreCase(functionType)) { PassthroughMapping pm = new PassthroughMapping(); pm.setAttributeName(attrName); // Cy2 doesn't write the "controllerType" property for PassThroughMappings, so just set STRING // (it should work, anyway). pm.setAttributeType(AttributeType.STRING); return pm; } return null; }
diff --git a/org.emftext.sdk/src/org/emftext/sdk/finders/GenPackageInRegistryFinder.java b/org.emftext.sdk/src/org/emftext/sdk/finders/GenPackageInRegistryFinder.java index 7ecaeeb82..95ae4ba91 100644 --- a/org.emftext.sdk/src/org/emftext/sdk/finders/GenPackageInRegistryFinder.java +++ b/org.emftext.sdk/src/org/emftext/sdk/finders/GenPackageInRegistryFinder.java @@ -1,169 +1,172 @@ /******************************************************************************* * Copyright (c) 2006-2011 * Software Technology Group, Dresden University of Technology * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Software Technology Group - TU Dresden, Germany * - initial API and implementation ******************************************************************************/ package org.emftext.sdk.finders; import java.util.Collection; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.Map; import org.eclipse.core.runtime.Assert; import org.eclipse.emf.codegen.ecore.genmodel.GenModel; import org.eclipse.emf.codegen.ecore.genmodel.GenPackage; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.plugin.EcorePlugin; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.ecore.resource.ResourceSet; import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl; import org.emftext.sdk.EMFTextSDKPlugin; import org.emftext.sdk.concretesyntax.GenPackageDependentElement; /** * A finder that looks up generator packages in the EMF package * registry. This implementation queries the registry once at its first usage * and loads and caches all valid generator packages. */ public class GenPackageInRegistryFinder implements IGenPackageFinder { private static final Map<String, GenPackageInRegistry> cache = new HashMap<String, GenPackageInRegistry>(); private static boolean isInitialized = false; private static void init() { synchronized (GenPackageInRegistryFinder.class) { if (!isInitialized) { //search all registered generator models final Map<String, URI> packageNsURIToGenModelLocationMap = EcorePlugin.getEPackageNsURIToGenModelLocationMap(); for (String nextNS : packageNsURIToGenModelLocationMap.keySet()) { URI genModelURI = packageNsURIToGenModelLocationMap.get(nextNS); try { final ResourceSet rs = new ResourceSetImpl(); Resource genModelResource = rs.getResource(genModelURI, true); if (genModelResource == null) { continue; } final EList<EObject> contents = genModelResource.getContents(); if (contents == null || contents.size() == 0) { continue; } GenModel genModel = (GenModel) contents.get(0); for (GenPackage genPackage : genModel.getGenPackages()) { if (genPackage != null && !genPackage.eIsProxy()) { String nsURI = genPackage.getNSURI(); final GenPackageInRegistry result = new GenPackageInRegistry(genPackage); cache.put(nsURI, result); registerSubGenPackages(genPackage); } } } catch (Exception e) { String uriString = genModelURI.toString(); // ignore FileNotFoundException caused by the org.eclipse.m2m.qvt.oml plug-in // this plug-in does not contain the generator models it registers // this is a workaround for Eclipse Bug 288208 // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=288208 // // do also ignore FileNotFoundException caused by some ATL plug-ins // this is a workaround for Eclipse Bug 315376 // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=315376 // // do also ignore FileNotFoundException caused by some xText plug-ins // this is a workaround for Eclipse Bug 315986 // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=315986 // // do also ignore FileNotFoundException caused by CDO // this is a workaround for Eclipse Bug 317821 // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=317821 // // do also ignore FileNotFoundException caused by MOFScript // This is a workaround for Eclipse Bug 322642 // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=322642 // // do also ignore FileNotFoundException caused by OCL Tools // This is a workaround for Eclipse Bug 322886 // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=322886 // // do also ignore FileNotFoundException caused by some pure::variants plug-ins + // // do also ignore FileNotFoundException caused by Acceleo plug-ins + // This is a workaround for Eclipse Bug 350348 + // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=350348 if (!uriString.startsWith("platform:/plugin/com.ps.consul.eclipse.ecore/src/pvmeta.genmodel") && !uriString.startsWith("platform:/plugin/com.ps.consul.eclipse.ecore/src/pvmodel.genmodel") && !uriString.startsWith("platform:/plugin/org.eclipse.emf.cdo/model/resource.genmodel") && !uriString.startsWith("platform:/plugin/org.eclipse.emf.mwe2.language/model/Mwe2.genmodel") && !uriString.startsWith("platform:/plugin/org.eclipse.m2m.qvt.oml") && !uriString.startsWith("platform:/plugin/org.eclipse.m2m.atl.profiler.exportmodel/model/exportmodel.genmodel") && !uriString.startsWith("platform:/plugin/org.eclipse.m2m.atl.profiler.model/model/ATL-Profiler.genmodel") && !uriString.startsWith("platform:/plugin/org.eclipse.mofscript.model/src/model/mofscriptmodel.genmodel") && !uriString.startsWith("platform:/plugin/org.eclipse.ocl.examples.xtext.completeocl/org.eclipse.ocl.examples.xtext.completeocl/model/CompleteOCLCST.genmodel") && !uriString.startsWith("platform:/plugin/org.eclipse.xtext/model/xtext.genmodel") && !uriString.startsWith("platform:/plugin/org.eclipse.xtext.builder/model/BuilderState.genmodel") && !uriString.startsWith("platform:/plugin/org.eclipse.xtext.xbase/org/eclipse/xtext/xbase/Xbase.genmodel") && !uriString.startsWith("platform:/plugin/org.eclipse.acceleo.ide.ui/model/AcceleoWizardModel.genmodel") ) { EMFTextSDKPlugin.logWarning("Exception while looking up generator model (" + nextNS + ") at " + uriString + " in the registry.", e); } } } isInitialized = true; } } } private static void registerSubGenPackages(GenPackage parentPackage) { for(GenPackage genPackage : parentPackage.getSubGenPackages()) { if (genPackage != null && !genPackage.eIsProxy()) { String nsURI = genPackage.getNSURI(); final GenPackageInRegistry result = new GenPackageInRegistry(genPackage); cache.put(nsURI, result); registerSubGenPackages(genPackage); } } } /** * An implementation of the IResolvedGenPackage that is used to * return generator package found in the EMF registry. */ private static class GenPackageInRegistry implements IResolvedGenPackage { private GenPackage genPackage; public GenPackageInRegistry(GenPackage genPackage) { Assert.isNotNull(genPackage); this.genPackage = genPackage; } public boolean hasChanged() { return false; } public GenPackage getResult() { return genPackage; } } public GenPackageResolveResult findGenPackages(String nsURI, String locationHint, GenPackageDependentElement container, Resource resource, boolean resolveFuzzy) { init(); Collection<IResolvedGenPackage> result = new LinkedHashSet<IResolvedGenPackage>(); for (String nextNsURI : cache.keySet()) { if (nextNsURI == null) { continue; } if (nextNsURI.equals(nsURI) || resolveFuzzy) { result.add(cache.get(nextNsURI)); } } return new GenPackageResolveResult(result); } }
false
true
private static void init() { synchronized (GenPackageInRegistryFinder.class) { if (!isInitialized) { //search all registered generator models final Map<String, URI> packageNsURIToGenModelLocationMap = EcorePlugin.getEPackageNsURIToGenModelLocationMap(); for (String nextNS : packageNsURIToGenModelLocationMap.keySet()) { URI genModelURI = packageNsURIToGenModelLocationMap.get(nextNS); try { final ResourceSet rs = new ResourceSetImpl(); Resource genModelResource = rs.getResource(genModelURI, true); if (genModelResource == null) { continue; } final EList<EObject> contents = genModelResource.getContents(); if (contents == null || contents.size() == 0) { continue; } GenModel genModel = (GenModel) contents.get(0); for (GenPackage genPackage : genModel.getGenPackages()) { if (genPackage != null && !genPackage.eIsProxy()) { String nsURI = genPackage.getNSURI(); final GenPackageInRegistry result = new GenPackageInRegistry(genPackage); cache.put(nsURI, result); registerSubGenPackages(genPackage); } } } catch (Exception e) { String uriString = genModelURI.toString(); // ignore FileNotFoundException caused by the org.eclipse.m2m.qvt.oml plug-in // this plug-in does not contain the generator models it registers // this is a workaround for Eclipse Bug 288208 // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=288208 // // do also ignore FileNotFoundException caused by some ATL plug-ins // this is a workaround for Eclipse Bug 315376 // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=315376 // // do also ignore FileNotFoundException caused by some xText plug-ins // this is a workaround for Eclipse Bug 315986 // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=315986 // // do also ignore FileNotFoundException caused by CDO // this is a workaround for Eclipse Bug 317821 // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=317821 // // do also ignore FileNotFoundException caused by MOFScript // This is a workaround for Eclipse Bug 322642 // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=322642 // // do also ignore FileNotFoundException caused by OCL Tools // This is a workaround for Eclipse Bug 322886 // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=322886 // // do also ignore FileNotFoundException caused by some pure::variants plug-ins // do also ignore FileNotFoundException caused by Acceleo plug-ins if (!uriString.startsWith("platform:/plugin/com.ps.consul.eclipse.ecore/src/pvmeta.genmodel") && !uriString.startsWith("platform:/plugin/com.ps.consul.eclipse.ecore/src/pvmodel.genmodel") && !uriString.startsWith("platform:/plugin/org.eclipse.emf.cdo/model/resource.genmodel") && !uriString.startsWith("platform:/plugin/org.eclipse.emf.mwe2.language/model/Mwe2.genmodel") && !uriString.startsWith("platform:/plugin/org.eclipse.m2m.qvt.oml") && !uriString.startsWith("platform:/plugin/org.eclipse.m2m.atl.profiler.exportmodel/model/exportmodel.genmodel") && !uriString.startsWith("platform:/plugin/org.eclipse.m2m.atl.profiler.model/model/ATL-Profiler.genmodel") && !uriString.startsWith("platform:/plugin/org.eclipse.mofscript.model/src/model/mofscriptmodel.genmodel") && !uriString.startsWith("platform:/plugin/org.eclipse.ocl.examples.xtext.completeocl/org.eclipse.ocl.examples.xtext.completeocl/model/CompleteOCLCST.genmodel") && !uriString.startsWith("platform:/plugin/org.eclipse.xtext/model/xtext.genmodel") && !uriString.startsWith("platform:/plugin/org.eclipse.xtext.builder/model/BuilderState.genmodel") && !uriString.startsWith("platform:/plugin/org.eclipse.xtext.xbase/org/eclipse/xtext/xbase/Xbase.genmodel") && !uriString.startsWith("platform:/plugin/org.eclipse.acceleo.ide.ui/model/AcceleoWizardModel.genmodel") ) { EMFTextSDKPlugin.logWarning("Exception while looking up generator model (" + nextNS + ") at " + uriString + " in the registry.", e); } } } isInitialized = true; } } }
private static void init() { synchronized (GenPackageInRegistryFinder.class) { if (!isInitialized) { //search all registered generator models final Map<String, URI> packageNsURIToGenModelLocationMap = EcorePlugin.getEPackageNsURIToGenModelLocationMap(); for (String nextNS : packageNsURIToGenModelLocationMap.keySet()) { URI genModelURI = packageNsURIToGenModelLocationMap.get(nextNS); try { final ResourceSet rs = new ResourceSetImpl(); Resource genModelResource = rs.getResource(genModelURI, true); if (genModelResource == null) { continue; } final EList<EObject> contents = genModelResource.getContents(); if (contents == null || contents.size() == 0) { continue; } GenModel genModel = (GenModel) contents.get(0); for (GenPackage genPackage : genModel.getGenPackages()) { if (genPackage != null && !genPackage.eIsProxy()) { String nsURI = genPackage.getNSURI(); final GenPackageInRegistry result = new GenPackageInRegistry(genPackage); cache.put(nsURI, result); registerSubGenPackages(genPackage); } } } catch (Exception e) { String uriString = genModelURI.toString(); // ignore FileNotFoundException caused by the org.eclipse.m2m.qvt.oml plug-in // this plug-in does not contain the generator models it registers // this is a workaround for Eclipse Bug 288208 // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=288208 // // do also ignore FileNotFoundException caused by some ATL plug-ins // this is a workaround for Eclipse Bug 315376 // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=315376 // // do also ignore FileNotFoundException caused by some xText plug-ins // this is a workaround for Eclipse Bug 315986 // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=315986 // // do also ignore FileNotFoundException caused by CDO // this is a workaround for Eclipse Bug 317821 // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=317821 // // do also ignore FileNotFoundException caused by MOFScript // This is a workaround for Eclipse Bug 322642 // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=322642 // // do also ignore FileNotFoundException caused by OCL Tools // This is a workaround for Eclipse Bug 322886 // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=322886 // // do also ignore FileNotFoundException caused by some pure::variants plug-ins // // do also ignore FileNotFoundException caused by Acceleo plug-ins // This is a workaround for Eclipse Bug 350348 // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=350348 if (!uriString.startsWith("platform:/plugin/com.ps.consul.eclipse.ecore/src/pvmeta.genmodel") && !uriString.startsWith("platform:/plugin/com.ps.consul.eclipse.ecore/src/pvmodel.genmodel") && !uriString.startsWith("platform:/plugin/org.eclipse.emf.cdo/model/resource.genmodel") && !uriString.startsWith("platform:/plugin/org.eclipse.emf.mwe2.language/model/Mwe2.genmodel") && !uriString.startsWith("platform:/plugin/org.eclipse.m2m.qvt.oml") && !uriString.startsWith("platform:/plugin/org.eclipse.m2m.atl.profiler.exportmodel/model/exportmodel.genmodel") && !uriString.startsWith("platform:/plugin/org.eclipse.m2m.atl.profiler.model/model/ATL-Profiler.genmodel") && !uriString.startsWith("platform:/plugin/org.eclipse.mofscript.model/src/model/mofscriptmodel.genmodel") && !uriString.startsWith("platform:/plugin/org.eclipse.ocl.examples.xtext.completeocl/org.eclipse.ocl.examples.xtext.completeocl/model/CompleteOCLCST.genmodel") && !uriString.startsWith("platform:/plugin/org.eclipse.xtext/model/xtext.genmodel") && !uriString.startsWith("platform:/plugin/org.eclipse.xtext.builder/model/BuilderState.genmodel") && !uriString.startsWith("platform:/plugin/org.eclipse.xtext.xbase/org/eclipse/xtext/xbase/Xbase.genmodel") && !uriString.startsWith("platform:/plugin/org.eclipse.acceleo.ide.ui/model/AcceleoWizardModel.genmodel") ) { EMFTextSDKPlugin.logWarning("Exception while looking up generator model (" + nextNS + ") at " + uriString + " in the registry.", e); } } } isInitialized = true; } } }
diff --git a/tests/native-media/src/com/example/nativemedia/NativeMedia.java b/tests/native-media/src/com/example/nativemedia/NativeMedia.java index 01636d2..82d579d 100644 --- a/tests/native-media/src/com/example/nativemedia/NativeMedia.java +++ b/tests/native-media/src/com/example/nativemedia/NativeMedia.java @@ -1,396 +1,398 @@ /* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.nativemedia; import android.app.Activity; import android.graphics.SurfaceTexture; import android.media.MediaPlayer; import android.os.Bundle; import android.util.Log; import android.view.Surface; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.Spinner; import java.io.IOException; import android.content.Context; import android.graphics.SurfaceTexture; import android.media.MediaPlayer.OnPreparedListener; import android.media.MediaPlayer; public class NativeMedia extends Activity { static final String TAG = "NativeMedia"; String mSourceString = null; String mSinkString = null; // member variables for Java media player MediaPlayer mMediaPlayer; boolean mMediaPlayerIsPrepared = false; SurfaceView mSurfaceView1; SurfaceHolder mSurfaceHolder1; // member variables for native media player boolean mIsPlayingStreaming = false; SurfaceView mSurfaceView2; SurfaceHolder mSurfaceHolder2; VideoSink mSelectedVideoSink; VideoSink mJavaMediaPlayerVideoSink; VideoSink mNativeMediaPlayerVideoSink; SurfaceHolderVideoSink mSurfaceHolder1VideoSink, mSurfaceHolder2VideoSink; GLViewVideoSink mGLView1VideoSink, mGLView2VideoSink; /** Called when the activity is first created. */ @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); mGLView1 = (MyGLSurfaceView) findViewById(R.id.glsurfaceview1); mGLView2 = (MyGLSurfaceView) findViewById(R.id.glsurfaceview2); //setContentView(mGLView); //setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); // initialize native media system createEngine(); // set up the Surface 1 video sink mSurfaceView1 = (SurfaceView) findViewById(R.id.surfaceview1); mSurfaceHolder1 = mSurfaceView1.getHolder(); mSurfaceHolder1.addCallback(new SurfaceHolder.Callback() { public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { - Log.v(TAG, "surfaceChanged format=" + format + ", width=" + width + ", height=" + height); + Log.v(TAG, "surfaceChanged format=" + format + ", width=" + width + ", height=" + + height); } public void surfaceCreated(SurfaceHolder holder) { Log.v(TAG, "surfaceCreated"); setSurface(holder.getSurface()); } public void surfaceDestroyed(SurfaceHolder holder) { Log.v(TAG, "surfaceDestroyed"); } }); // set up the Surface 2 video sink mSurfaceView2 = (SurfaceView) findViewById(R.id.surfaceview2); mSurfaceHolder2 = mSurfaceView2.getHolder(); mSurfaceHolder2.addCallback(new SurfaceHolder.Callback() { public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { - Log.v(TAG, "surfaceChanged format=" + format + ", width=" + width + ", height=" + height); + Log.v(TAG, "surfaceChanged format=" + format + ", width=" + width + ", height=" + + height); } public void surfaceCreated(SurfaceHolder holder) { Log.v(TAG, "surfaceCreated"); setSurface(holder.getSurface()); } public void surfaceDestroyed(SurfaceHolder holder) { Log.v(TAG, "surfaceDestroyed"); } }); // create Java media player mMediaPlayer = new MediaPlayer(); // set up Java media player listeners mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { public void onPrepared(MediaPlayer mediaPlayer) { int width = mediaPlayer.getVideoWidth(); int height = mediaPlayer.getVideoHeight(); Log.v(TAG, "onPrepared width=" + width + ", height=" + height); if (width != 0 && height != 0 && mJavaMediaPlayerVideoSink != null) { mJavaMediaPlayerVideoSink.setFixedSize(width, height); } mMediaPlayerIsPrepared = true; mediaPlayer.start(); } }); mMediaPlayer.setOnVideoSizeChangedListener(new MediaPlayer.OnVideoSizeChangedListener() { public void onVideoSizeChanged(MediaPlayer mediaPlayer, int width, int height) { Log.v(TAG, "onVideoSizeChanged width=" + width + ", height=" + height); if (width != 0 && height != 0 && mJavaMediaPlayerVideoSink != null) { mJavaMediaPlayerVideoSink.setFixedSize(width, height); } } }); // initialize content source spinner Spinner sourceSpinner = (Spinner) findViewById(R.id.source_spinner); ArrayAdapter<CharSequence> sourceAdapter = ArrayAdapter.createFromResource( this, R.array.source_array, android.R.layout.simple_spinner_item); sourceAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); sourceSpinner.setAdapter(sourceAdapter); sourceSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { mSourceString = parent.getItemAtPosition(pos).toString(); Log.v(TAG, "onItemSelected " + mSourceString); } public void onNothingSelected(AdapterView parent) { Log.v(TAG, "onNothingSelected"); mSourceString = null; } }); // initialize video sink spinner Spinner sinkSpinner = (Spinner) findViewById(R.id.sink_spinner); ArrayAdapter<CharSequence> sinkAdapter = ArrayAdapter.createFromResource( this, R.array.sink_array, android.R.layout.simple_spinner_item); sinkAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); sinkSpinner.setAdapter(sinkAdapter); sinkSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { mSinkString = parent.getItemAtPosition(pos).toString(); Log.v(TAG, "onItemSelected " + mSinkString); if ("Surface 1".equals(mSinkString)) { if (mSurfaceHolder1VideoSink == null) { mSurfaceHolder1VideoSink = new SurfaceHolderVideoSink(mSurfaceHolder1); } mSelectedVideoSink = mSurfaceHolder1VideoSink; } else if ("Surface 2".equals(mSinkString)) { if (mSurfaceHolder2VideoSink == null) { mSurfaceHolder2VideoSink = new SurfaceHolderVideoSink(mSurfaceHolder2); } mSelectedVideoSink = mSurfaceHolder2VideoSink; } else if ("SurfaceTexture 1".equals(mSinkString)) { if (mGLView1VideoSink == null) { mGLView1VideoSink = new GLViewVideoSink(mGLView1); } mSelectedVideoSink = mGLView1VideoSink; } else if ("SurfaceTexture 2".equals(mSinkString)) { if (mGLView2VideoSink == null) { mGLView2VideoSink = new GLViewVideoSink(mGLView2); } mSelectedVideoSink = mGLView2VideoSink; } } public void onNothingSelected(AdapterView parent) { Log.v(TAG, "onNothingSelected"); mSinkString = null; mSelectedVideoSink = null; } }); // initialize button click handlers // Java MediaPlayer start/pause ((Button) findViewById(R.id.start_java)).setOnClickListener(new View.OnClickListener() { public void onClick(View view) { if (mJavaMediaPlayerVideoSink == null) { if (mSelectedVideoSink == null) { return; } mSelectedVideoSink.useAsSinkForJava(mMediaPlayer); mJavaMediaPlayerVideoSink = mSelectedVideoSink; } if (!mMediaPlayerIsPrepared) { if (mSourceString != null) { try { mMediaPlayer.setDataSource(mSourceString); } catch (IOException e) { Log.e(TAG, "IOException " + e); } mMediaPlayer.prepareAsync(); } } else if (mMediaPlayer.isPlaying()) { mMediaPlayer.pause(); } else { mMediaPlayer.start(); } } }); // native MediaPlayer start/pause ((Button) findViewById(R.id.start_native)).setOnClickListener(new View.OnClickListener() { boolean created = false; public void onClick(View view) { if (!created) { if (mNativeMediaPlayerVideoSink == null) { if (mSelectedVideoSink == null) { return; } mSelectedVideoSink.useAsSinkForNative(); mNativeMediaPlayerVideoSink = mSelectedVideoSink; } if (mSourceString != null) { created = createStreamingMediaPlayer(mSourceString); } } if (created) { mIsPlayingStreaming = !mIsPlayingStreaming; setPlayingStreamingMediaPlayer(mIsPlayingStreaming); } } }); // Java MediaPlayer rewind ((Button) findViewById(R.id.rewind_java)).setOnClickListener(new View.OnClickListener() { public void onClick(View view) { if (mMediaPlayerIsPrepared) { mMediaPlayer.seekTo(0); } } }); // native MediaPlayer rewind ((Button) findViewById(R.id.rewind_native)).setOnClickListener(new View.OnClickListener() { public void onClick(View view) { if (mNativeMediaPlayerVideoSink != null) { rewindStreamingMediaPlayer(); } } }); } /** Called when the activity is about to be paused. */ @Override protected void onPause() { mIsPlayingStreaming = false; setPlayingStreamingMediaPlayer(false); mGLView1.onPause(); mGLView2.onPause(); super.onPause(); } @Override protected void onResume() { super.onResume(); mGLView1.onResume(); mGLView2.onResume(); } /** Called when the activity is about to be destroyed. */ @Override protected void onDestroy() { shutdown(); super.onDestroy(); } private MyGLSurfaceView mGLView1, mGLView2; /** Native methods, implemented in jni folder */ public static native void createEngine(); public static native boolean createStreamingMediaPlayer(String filename); public static native void setPlayingStreamingMediaPlayer(boolean isPlaying); public static native void shutdown(); public static native void setSurface(Surface surface); public static native void setSurfaceTexture(SurfaceTexture surfaceTexture); public static native void rewindStreamingMediaPlayer(); /** Load jni .so on initialization */ static { System.loadLibrary("native-media-jni"); } // VideoSink abstracts out the difference between Surface and SurfaceTexture // aka SurfaceHolder and GLSurfaceView static abstract class VideoSink { abstract void setFixedSize(int width, int height); abstract void useAsSinkForJava(MediaPlayer mediaPlayer); abstract void useAsSinkForNative(); } static class SurfaceHolderVideoSink extends VideoSink { private final SurfaceHolder mSurfaceHolder; SurfaceHolderVideoSink(SurfaceHolder surfaceHolder) { mSurfaceHolder = surfaceHolder; } void setFixedSize(int width, int height) { mSurfaceHolder.setFixedSize(width, height); } void useAsSinkForJava(MediaPlayer mediaPlayer) { mediaPlayer.setDisplay(mSurfaceHolder); } void useAsSinkForNative() { setSurface(mSurfaceHolder.getSurface()); } } static class GLViewVideoSink extends VideoSink { private final MyGLSurfaceView mMyGLSurfaceView; GLViewVideoSink(MyGLSurfaceView myGLSurfaceView) { mMyGLSurfaceView = myGLSurfaceView; } void setFixedSize(int width, int height) { } void useAsSinkForJava(MediaPlayer mediaPlayer) { SurfaceTexture st = mMyGLSurfaceView.getSurfaceTexture(); Surface s = new Surface(st); mediaPlayer.setSurface(s); s.release(); } void useAsSinkForNative() { setSurfaceTexture(mMyGLSurfaceView.getSurfaceTexture()); } } }
false
true
public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); mGLView1 = (MyGLSurfaceView) findViewById(R.id.glsurfaceview1); mGLView2 = (MyGLSurfaceView) findViewById(R.id.glsurfaceview2); //setContentView(mGLView); //setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); // initialize native media system createEngine(); // set up the Surface 1 video sink mSurfaceView1 = (SurfaceView) findViewById(R.id.surfaceview1); mSurfaceHolder1 = mSurfaceView1.getHolder(); mSurfaceHolder1.addCallback(new SurfaceHolder.Callback() { public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { Log.v(TAG, "surfaceChanged format=" + format + ", width=" + width + ", height=" + height); } public void surfaceCreated(SurfaceHolder holder) { Log.v(TAG, "surfaceCreated"); setSurface(holder.getSurface()); } public void surfaceDestroyed(SurfaceHolder holder) { Log.v(TAG, "surfaceDestroyed"); } }); // set up the Surface 2 video sink mSurfaceView2 = (SurfaceView) findViewById(R.id.surfaceview2); mSurfaceHolder2 = mSurfaceView2.getHolder(); mSurfaceHolder2.addCallback(new SurfaceHolder.Callback() { public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { Log.v(TAG, "surfaceChanged format=" + format + ", width=" + width + ", height=" + height); } public void surfaceCreated(SurfaceHolder holder) { Log.v(TAG, "surfaceCreated"); setSurface(holder.getSurface()); } public void surfaceDestroyed(SurfaceHolder holder) { Log.v(TAG, "surfaceDestroyed"); } }); // create Java media player mMediaPlayer = new MediaPlayer(); // set up Java media player listeners mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { public void onPrepared(MediaPlayer mediaPlayer) { int width = mediaPlayer.getVideoWidth(); int height = mediaPlayer.getVideoHeight(); Log.v(TAG, "onPrepared width=" + width + ", height=" + height); if (width != 0 && height != 0 && mJavaMediaPlayerVideoSink != null) { mJavaMediaPlayerVideoSink.setFixedSize(width, height); } mMediaPlayerIsPrepared = true; mediaPlayer.start(); } }); mMediaPlayer.setOnVideoSizeChangedListener(new MediaPlayer.OnVideoSizeChangedListener() { public void onVideoSizeChanged(MediaPlayer mediaPlayer, int width, int height) { Log.v(TAG, "onVideoSizeChanged width=" + width + ", height=" + height); if (width != 0 && height != 0 && mJavaMediaPlayerVideoSink != null) { mJavaMediaPlayerVideoSink.setFixedSize(width, height); } } }); // initialize content source spinner Spinner sourceSpinner = (Spinner) findViewById(R.id.source_spinner); ArrayAdapter<CharSequence> sourceAdapter = ArrayAdapter.createFromResource( this, R.array.source_array, android.R.layout.simple_spinner_item); sourceAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); sourceSpinner.setAdapter(sourceAdapter); sourceSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { mSourceString = parent.getItemAtPosition(pos).toString(); Log.v(TAG, "onItemSelected " + mSourceString); } public void onNothingSelected(AdapterView parent) { Log.v(TAG, "onNothingSelected"); mSourceString = null; } }); // initialize video sink spinner Spinner sinkSpinner = (Spinner) findViewById(R.id.sink_spinner); ArrayAdapter<CharSequence> sinkAdapter = ArrayAdapter.createFromResource( this, R.array.sink_array, android.R.layout.simple_spinner_item); sinkAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); sinkSpinner.setAdapter(sinkAdapter); sinkSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { mSinkString = parent.getItemAtPosition(pos).toString(); Log.v(TAG, "onItemSelected " + mSinkString); if ("Surface 1".equals(mSinkString)) { if (mSurfaceHolder1VideoSink == null) { mSurfaceHolder1VideoSink = new SurfaceHolderVideoSink(mSurfaceHolder1); } mSelectedVideoSink = mSurfaceHolder1VideoSink; } else if ("Surface 2".equals(mSinkString)) { if (mSurfaceHolder2VideoSink == null) { mSurfaceHolder2VideoSink = new SurfaceHolderVideoSink(mSurfaceHolder2); } mSelectedVideoSink = mSurfaceHolder2VideoSink; } else if ("SurfaceTexture 1".equals(mSinkString)) { if (mGLView1VideoSink == null) { mGLView1VideoSink = new GLViewVideoSink(mGLView1); } mSelectedVideoSink = mGLView1VideoSink; } else if ("SurfaceTexture 2".equals(mSinkString)) { if (mGLView2VideoSink == null) { mGLView2VideoSink = new GLViewVideoSink(mGLView2); } mSelectedVideoSink = mGLView2VideoSink; } } public void onNothingSelected(AdapterView parent) { Log.v(TAG, "onNothingSelected"); mSinkString = null; mSelectedVideoSink = null; } }); // initialize button click handlers // Java MediaPlayer start/pause ((Button) findViewById(R.id.start_java)).setOnClickListener(new View.OnClickListener() { public void onClick(View view) { if (mJavaMediaPlayerVideoSink == null) { if (mSelectedVideoSink == null) { return; } mSelectedVideoSink.useAsSinkForJava(mMediaPlayer); mJavaMediaPlayerVideoSink = mSelectedVideoSink; } if (!mMediaPlayerIsPrepared) { if (mSourceString != null) { try { mMediaPlayer.setDataSource(mSourceString); } catch (IOException e) { Log.e(TAG, "IOException " + e); } mMediaPlayer.prepareAsync(); } } else if (mMediaPlayer.isPlaying()) { mMediaPlayer.pause(); } else { mMediaPlayer.start(); } } }); // native MediaPlayer start/pause ((Button) findViewById(R.id.start_native)).setOnClickListener(new View.OnClickListener() { boolean created = false; public void onClick(View view) { if (!created) { if (mNativeMediaPlayerVideoSink == null) { if (mSelectedVideoSink == null) { return; } mSelectedVideoSink.useAsSinkForNative(); mNativeMediaPlayerVideoSink = mSelectedVideoSink; } if (mSourceString != null) { created = createStreamingMediaPlayer(mSourceString); } } if (created) { mIsPlayingStreaming = !mIsPlayingStreaming; setPlayingStreamingMediaPlayer(mIsPlayingStreaming); } } }); // Java MediaPlayer rewind ((Button) findViewById(R.id.rewind_java)).setOnClickListener(new View.OnClickListener() { public void onClick(View view) { if (mMediaPlayerIsPrepared) { mMediaPlayer.seekTo(0); } } }); // native MediaPlayer rewind ((Button) findViewById(R.id.rewind_native)).setOnClickListener(new View.OnClickListener() { public void onClick(View view) { if (mNativeMediaPlayerVideoSink != null) { rewindStreamingMediaPlayer(); } } }); }
public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); mGLView1 = (MyGLSurfaceView) findViewById(R.id.glsurfaceview1); mGLView2 = (MyGLSurfaceView) findViewById(R.id.glsurfaceview2); //setContentView(mGLView); //setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); // initialize native media system createEngine(); // set up the Surface 1 video sink mSurfaceView1 = (SurfaceView) findViewById(R.id.surfaceview1); mSurfaceHolder1 = mSurfaceView1.getHolder(); mSurfaceHolder1.addCallback(new SurfaceHolder.Callback() { public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { Log.v(TAG, "surfaceChanged format=" + format + ", width=" + width + ", height=" + height); } public void surfaceCreated(SurfaceHolder holder) { Log.v(TAG, "surfaceCreated"); setSurface(holder.getSurface()); } public void surfaceDestroyed(SurfaceHolder holder) { Log.v(TAG, "surfaceDestroyed"); } }); // set up the Surface 2 video sink mSurfaceView2 = (SurfaceView) findViewById(R.id.surfaceview2); mSurfaceHolder2 = mSurfaceView2.getHolder(); mSurfaceHolder2.addCallback(new SurfaceHolder.Callback() { public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { Log.v(TAG, "surfaceChanged format=" + format + ", width=" + width + ", height=" + height); } public void surfaceCreated(SurfaceHolder holder) { Log.v(TAG, "surfaceCreated"); setSurface(holder.getSurface()); } public void surfaceDestroyed(SurfaceHolder holder) { Log.v(TAG, "surfaceDestroyed"); } }); // create Java media player mMediaPlayer = new MediaPlayer(); // set up Java media player listeners mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { public void onPrepared(MediaPlayer mediaPlayer) { int width = mediaPlayer.getVideoWidth(); int height = mediaPlayer.getVideoHeight(); Log.v(TAG, "onPrepared width=" + width + ", height=" + height); if (width != 0 && height != 0 && mJavaMediaPlayerVideoSink != null) { mJavaMediaPlayerVideoSink.setFixedSize(width, height); } mMediaPlayerIsPrepared = true; mediaPlayer.start(); } }); mMediaPlayer.setOnVideoSizeChangedListener(new MediaPlayer.OnVideoSizeChangedListener() { public void onVideoSizeChanged(MediaPlayer mediaPlayer, int width, int height) { Log.v(TAG, "onVideoSizeChanged width=" + width + ", height=" + height); if (width != 0 && height != 0 && mJavaMediaPlayerVideoSink != null) { mJavaMediaPlayerVideoSink.setFixedSize(width, height); } } }); // initialize content source spinner Spinner sourceSpinner = (Spinner) findViewById(R.id.source_spinner); ArrayAdapter<CharSequence> sourceAdapter = ArrayAdapter.createFromResource( this, R.array.source_array, android.R.layout.simple_spinner_item); sourceAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); sourceSpinner.setAdapter(sourceAdapter); sourceSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { mSourceString = parent.getItemAtPosition(pos).toString(); Log.v(TAG, "onItemSelected " + mSourceString); } public void onNothingSelected(AdapterView parent) { Log.v(TAG, "onNothingSelected"); mSourceString = null; } }); // initialize video sink spinner Spinner sinkSpinner = (Spinner) findViewById(R.id.sink_spinner); ArrayAdapter<CharSequence> sinkAdapter = ArrayAdapter.createFromResource( this, R.array.sink_array, android.R.layout.simple_spinner_item); sinkAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); sinkSpinner.setAdapter(sinkAdapter); sinkSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { mSinkString = parent.getItemAtPosition(pos).toString(); Log.v(TAG, "onItemSelected " + mSinkString); if ("Surface 1".equals(mSinkString)) { if (mSurfaceHolder1VideoSink == null) { mSurfaceHolder1VideoSink = new SurfaceHolderVideoSink(mSurfaceHolder1); } mSelectedVideoSink = mSurfaceHolder1VideoSink; } else if ("Surface 2".equals(mSinkString)) { if (mSurfaceHolder2VideoSink == null) { mSurfaceHolder2VideoSink = new SurfaceHolderVideoSink(mSurfaceHolder2); } mSelectedVideoSink = mSurfaceHolder2VideoSink; } else if ("SurfaceTexture 1".equals(mSinkString)) { if (mGLView1VideoSink == null) { mGLView1VideoSink = new GLViewVideoSink(mGLView1); } mSelectedVideoSink = mGLView1VideoSink; } else if ("SurfaceTexture 2".equals(mSinkString)) { if (mGLView2VideoSink == null) { mGLView2VideoSink = new GLViewVideoSink(mGLView2); } mSelectedVideoSink = mGLView2VideoSink; } } public void onNothingSelected(AdapterView parent) { Log.v(TAG, "onNothingSelected"); mSinkString = null; mSelectedVideoSink = null; } }); // initialize button click handlers // Java MediaPlayer start/pause ((Button) findViewById(R.id.start_java)).setOnClickListener(new View.OnClickListener() { public void onClick(View view) { if (mJavaMediaPlayerVideoSink == null) { if (mSelectedVideoSink == null) { return; } mSelectedVideoSink.useAsSinkForJava(mMediaPlayer); mJavaMediaPlayerVideoSink = mSelectedVideoSink; } if (!mMediaPlayerIsPrepared) { if (mSourceString != null) { try { mMediaPlayer.setDataSource(mSourceString); } catch (IOException e) { Log.e(TAG, "IOException " + e); } mMediaPlayer.prepareAsync(); } } else if (mMediaPlayer.isPlaying()) { mMediaPlayer.pause(); } else { mMediaPlayer.start(); } } }); // native MediaPlayer start/pause ((Button) findViewById(R.id.start_native)).setOnClickListener(new View.OnClickListener() { boolean created = false; public void onClick(View view) { if (!created) { if (mNativeMediaPlayerVideoSink == null) { if (mSelectedVideoSink == null) { return; } mSelectedVideoSink.useAsSinkForNative(); mNativeMediaPlayerVideoSink = mSelectedVideoSink; } if (mSourceString != null) { created = createStreamingMediaPlayer(mSourceString); } } if (created) { mIsPlayingStreaming = !mIsPlayingStreaming; setPlayingStreamingMediaPlayer(mIsPlayingStreaming); } } }); // Java MediaPlayer rewind ((Button) findViewById(R.id.rewind_java)).setOnClickListener(new View.OnClickListener() { public void onClick(View view) { if (mMediaPlayerIsPrepared) { mMediaPlayer.seekTo(0); } } }); // native MediaPlayer rewind ((Button) findViewById(R.id.rewind_native)).setOnClickListener(new View.OnClickListener() { public void onClick(View view) { if (mNativeMediaPlayerVideoSink != null) { rewindStreamingMediaPlayer(); } } }); }
diff --git a/spring-boot/src/main/java/org/springframework/boot/logging/logback/LogbackLoggingSystem.java b/spring-boot/src/main/java/org/springframework/boot/logging/logback/LogbackLoggingSystem.java index 5d402b261e..26f555f223 100644 --- a/spring-boot/src/main/java/org/springframework/boot/logging/logback/LogbackLoggingSystem.java +++ b/spring-boot/src/main/java/org/springframework/boot/logging/logback/LogbackLoggingSystem.java @@ -1,102 +1,106 @@ /* * Copyright 2012-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.logging.logback; import java.net.URL; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.slf4j.ILoggerFactory; import org.slf4j.Logger; import org.slf4j.bridge.SLF4JBridgeHandler; import org.slf4j.impl.StaticLoggerBinder; import org.springframework.boot.logging.AbstractLoggingSystem; import org.springframework.boot.logging.LogLevel; import org.springframework.boot.logging.LoggingSystem; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; import org.springframework.util.ResourceUtils; import org.springframework.util.StringUtils; import org.springframework.util.SystemPropertyUtils; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.util.ContextInitializer; /** * {@link LoggingSystem} for for <a href="http://logback.qos.ch">logback</a>. * * @author Phillip Webb * @author Dave Syer */ public class LogbackLoggingSystem extends AbstractLoggingSystem { private static final Map<LogLevel, Level> LEVELS; static { Map<LogLevel, Level> levels = new HashMap<LogLevel, Level>(); levels.put(LogLevel.TRACE, Level.TRACE); levels.put(LogLevel.DEBUG, Level.DEBUG); levels.put(LogLevel.INFO, Level.INFO); levels.put(LogLevel.WARN, Level.WARN); levels.put(LogLevel.ERROR, Level.ERROR); levels.put(LogLevel.FATAL, Level.ERROR); LEVELS = Collections.unmodifiableMap(levels); } public LogbackLoggingSystem(ClassLoader classLoader) { super(classLoader, "logback-test.groovy", "logback-test.xml", "logback.groovy", "logback.xml"); } @Override public void beforeInitialize() { super.beforeInitialize(); if (ClassUtils.isPresent("org.slf4j.bridge.SLF4JBridgeHandler", getClassLoader())) { SLF4JBridgeHandler.removeHandlersForRootLogger(); SLF4JBridgeHandler.install(); } } @Override public void initialize(String configLocation) { Assert.notNull(configLocation, "ConfigLocation must not be null"); String resolvedLocation = SystemPropertyUtils.resolvePlaceholders(configLocation); ILoggerFactory factory = StaticLoggerBinder.getSingleton().getLoggerFactory(); - Assert.isInstanceOf(ILoggerFactory.class, factory); + Assert.isInstanceOf( + LoggerContext.class, + factory, + "LoggerFactory is not a Logback LoggerContext but Logback is on the classpath. Either remove Logback or the competing implementation (" + + factory.getClass() + ")"); LoggerContext context = (LoggerContext) factory; context.stop(); try { URL url = ResourceUtils.getURL(resolvedLocation); new ContextInitializer(context).configureByResource(url); } catch (Exception ex) { throw new IllegalStateException("Could not initialize logging from " + configLocation, ex); } } @Override public void setLogLevel(String loggerName, LogLevel level) { ILoggerFactory factory = StaticLoggerBinder.getSingleton().getLoggerFactory(); Logger logger = factory .getLogger(StringUtils.isEmpty(loggerName) ? Logger.ROOT_LOGGER_NAME : loggerName); ((ch.qos.logback.classic.Logger) logger).setLevel(LEVELS.get(level)); } }
true
true
public void initialize(String configLocation) { Assert.notNull(configLocation, "ConfigLocation must not be null"); String resolvedLocation = SystemPropertyUtils.resolvePlaceholders(configLocation); ILoggerFactory factory = StaticLoggerBinder.getSingleton().getLoggerFactory(); Assert.isInstanceOf(ILoggerFactory.class, factory); LoggerContext context = (LoggerContext) factory; context.stop(); try { URL url = ResourceUtils.getURL(resolvedLocation); new ContextInitializer(context).configureByResource(url); } catch (Exception ex) { throw new IllegalStateException("Could not initialize logging from " + configLocation, ex); } }
public void initialize(String configLocation) { Assert.notNull(configLocation, "ConfigLocation must not be null"); String resolvedLocation = SystemPropertyUtils.resolvePlaceholders(configLocation); ILoggerFactory factory = StaticLoggerBinder.getSingleton().getLoggerFactory(); Assert.isInstanceOf( LoggerContext.class, factory, "LoggerFactory is not a Logback LoggerContext but Logback is on the classpath. Either remove Logback or the competing implementation (" + factory.getClass() + ")"); LoggerContext context = (LoggerContext) factory; context.stop(); try { URL url = ResourceUtils.getURL(resolvedLocation); new ContextInitializer(context).configureByResource(url); } catch (Exception ex) { throw new IllegalStateException("Could not initialize logging from " + configLocation, ex); } }
diff --git a/update/org.eclipse.update.scheduler/src/org/eclipse/update/internal/scheduler/AutomaticUpdatesJob.java b/update/org.eclipse.update.scheduler/src/org/eclipse/update/internal/scheduler/AutomaticUpdatesJob.java index 3878f7558..bbc01928a 100644 --- a/update/org.eclipse.update.scheduler/src/org/eclipse/update/internal/scheduler/AutomaticUpdatesJob.java +++ b/update/org.eclipse.update.scheduler/src/org/eclipse/update/internal/scheduler/AutomaticUpdatesJob.java @@ -1,188 +1,188 @@ /******************************************************************************* * Copyright (c) 2000, 2004 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.update.internal.scheduler; import java.util.ArrayList; import org.eclipse.core.runtime.*; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.wizard.WizardDialog; import org.eclipse.swt.custom.BusyIndicator; import org.eclipse.swt.widgets.Display; import org.eclipse.update.core.IFeature; import org.eclipse.update.internal.core.*; import org.eclipse.update.internal.operations.UpdateUtils; import org.eclipse.update.internal.ui.wizards.*; import org.eclipse.update.operations.*; import org.eclipse.update.search.*; public class AutomaticUpdatesJob extends Job { private class AutomaticSearchResultCollector implements IUpdateSearchResultCollector { public void accept(IFeature feature) { IInstallFeatureOperation operation = OperationsManager .getOperationFactory() .createInstallOperation(null, feature, null, null, null); updates.add(operation); } } // job family public static final Object family = new Object(); private IUpdateSearchResultCollector resultCollector; private static final IStatus OK_STATUS = new Status( IStatus.OK, UpdateScheduler.getPluginId(), IStatus.OK, "", //$NON-NLS-1$ null); private UpdateSearchRequest searchRequest; private ArrayList updates; public AutomaticUpdatesJob() { super(UpdateScheduler.getString("AutomaticUpdatesJob.AutomaticUpdateSearch")); //$NON-NLS-1$ updates = new ArrayList(); setPriority(Job.DECORATE); } /** * Returns the standard display to be used. The method first checks, if * the thread calling this method has an associated disaply. If so, this * display is returned. Otherwise the method returns the default display. */ public static Display getStandardDisplay() { Display display; display = Display.getCurrent(); if (display == null) display = Display.getDefault(); return display; } public boolean belongsTo(Object family) { return AutomaticUpdatesJob.family == family; } public IStatus run(IProgressMonitor monitor) { if (UpdateCore.DEBUG) { UpdateCore.debug("Automatic update search started."); //$NON-NLS-1$ } searchRequest = UpdateUtils.createNewUpdatesRequest(null); try { if (resultCollector == null) resultCollector = new AutomaticSearchResultCollector(); searchRequest.performSearch(resultCollector, monitor); if (UpdateCore.DEBUG) { UpdateCore.debug("Automatic update search finished - " //$NON-NLS-1$ + updates.size() + " results."); //$NON-NLS-1$ } if (updates.size() > 0) { - boolean download = UpdateCore.getPlugin().getPluginPreferences().getBoolean(UpdateScheduler.P_DOWNLOAD); + boolean download = UpdateScheduler.getDefault().getPluginPreferences().getBoolean(UpdateScheduler.P_DOWNLOAD); // silently download if download enabled if (download) { if (UpdateCore.DEBUG) { UpdateCore.debug("Automatic download of updates started."); //$NON-NLS-1$ } for (int i=0; i<updates.size(); i++) { IInstallFeatureOperation op = (IInstallFeatureOperation)updates.get(i); IFeature feature = op.getFeature(); UpdateUtils.downloadFeatureContent(feature, null, monitor); } if (UpdateCore.DEBUG) { UpdateCore.debug("Automatic download of updates finished."); //$NON-NLS-1$ } } // prompt the user if (!InstallWizard.isRunning()) { if (download) { getStandardDisplay().asyncExec(new Runnable() { public void run() { asyncNotifyDownloadUser(); } }); } else { getStandardDisplay().asyncExec(new Runnable() { public void run() { asyncNotifyUser(); } }); } } return Job.ASYNC_FINISH; } } catch (CoreException e) { return e.getStatus(); } return OK_STATUS; } private void asyncNotifyUser() { // ask the user to install updates getStandardDisplay().beep(); if (MessageDialog .openQuestion( UpdateScheduler.getActiveWorkbenchShell(), UpdateScheduler.getString("AutomaticUpdatesJob.EclipseUpdates1"), //$NON-NLS-1$ UpdateScheduler.getString("AutomaticUpdatesJob.UpdatesAvailable"))) { //$NON-NLS-1$ BusyIndicator.showWhile(getStandardDisplay(), new Runnable() { public void run() { openInstallWizard(); } }); } // notify the manager that the job is done done(OK_STATUS); } private void asyncNotifyDownloadUser() { // ask the user to install updates getStandardDisplay().beep(); if (MessageDialog .openQuestion( UpdateScheduler.getActiveWorkbenchShell(), UpdateScheduler.getString("AutomaticUpdatesJob.EclipseUpdates2"), //$NON-NLS-1$ UpdateScheduler.getString("AutomaticUpdatesJob.UpdatesDownloaded"))) { //$NON-NLS-1$ BusyIndicator.showWhile(getStandardDisplay(), new Runnable() { public void run() { openInstallWizard(); } }); } else { // Don't discard downloaded data, as next time we compare timestamps. // discard all the downloaded data from cache (may include old data as well) //Utilities.flushLocalFile(); } // notify the manager that the job is done done(OK_STATUS); } private void openInstallWizard() { if (InstallWizard.isRunning()) // job ends and a new one is rescheduled return; InstallWizard wizard = new InstallWizard(searchRequest, updates); WizardDialog dialog = new ResizableInstallWizardDialog( UpdateScheduler.getActiveWorkbenchShell(), wizard, UpdateScheduler.getString("AutomaticUpdatesJob.Updates")); //$NON-NLS-1$ dialog.create(); dialog.open(); } }
true
true
public IStatus run(IProgressMonitor monitor) { if (UpdateCore.DEBUG) { UpdateCore.debug("Automatic update search started."); //$NON-NLS-1$ } searchRequest = UpdateUtils.createNewUpdatesRequest(null); try { if (resultCollector == null) resultCollector = new AutomaticSearchResultCollector(); searchRequest.performSearch(resultCollector, monitor); if (UpdateCore.DEBUG) { UpdateCore.debug("Automatic update search finished - " //$NON-NLS-1$ + updates.size() + " results."); //$NON-NLS-1$ } if (updates.size() > 0) { boolean download = UpdateCore.getPlugin().getPluginPreferences().getBoolean(UpdateScheduler.P_DOWNLOAD); // silently download if download enabled if (download) { if (UpdateCore.DEBUG) { UpdateCore.debug("Automatic download of updates started."); //$NON-NLS-1$ } for (int i=0; i<updates.size(); i++) { IInstallFeatureOperation op = (IInstallFeatureOperation)updates.get(i); IFeature feature = op.getFeature(); UpdateUtils.downloadFeatureContent(feature, null, monitor); } if (UpdateCore.DEBUG) { UpdateCore.debug("Automatic download of updates finished."); //$NON-NLS-1$ } } // prompt the user if (!InstallWizard.isRunning()) { if (download) { getStandardDisplay().asyncExec(new Runnable() { public void run() { asyncNotifyDownloadUser(); } }); } else { getStandardDisplay().asyncExec(new Runnable() { public void run() { asyncNotifyUser(); } }); } } return Job.ASYNC_FINISH; } } catch (CoreException e) { return e.getStatus(); } return OK_STATUS; }
public IStatus run(IProgressMonitor monitor) { if (UpdateCore.DEBUG) { UpdateCore.debug("Automatic update search started."); //$NON-NLS-1$ } searchRequest = UpdateUtils.createNewUpdatesRequest(null); try { if (resultCollector == null) resultCollector = new AutomaticSearchResultCollector(); searchRequest.performSearch(resultCollector, monitor); if (UpdateCore.DEBUG) { UpdateCore.debug("Automatic update search finished - " //$NON-NLS-1$ + updates.size() + " results."); //$NON-NLS-1$ } if (updates.size() > 0) { boolean download = UpdateScheduler.getDefault().getPluginPreferences().getBoolean(UpdateScheduler.P_DOWNLOAD); // silently download if download enabled if (download) { if (UpdateCore.DEBUG) { UpdateCore.debug("Automatic download of updates started."); //$NON-NLS-1$ } for (int i=0; i<updates.size(); i++) { IInstallFeatureOperation op = (IInstallFeatureOperation)updates.get(i); IFeature feature = op.getFeature(); UpdateUtils.downloadFeatureContent(feature, null, monitor); } if (UpdateCore.DEBUG) { UpdateCore.debug("Automatic download of updates finished."); //$NON-NLS-1$ } } // prompt the user if (!InstallWizard.isRunning()) { if (download) { getStandardDisplay().asyncExec(new Runnable() { public void run() { asyncNotifyDownloadUser(); } }); } else { getStandardDisplay().asyncExec(new Runnable() { public void run() { asyncNotifyUser(); } }); } } return Job.ASYNC_FINISH; } } catch (CoreException e) { return e.getStatus(); } return OK_STATUS; }
diff --git a/server/src/main/java/us/codecraft/blackhole/forward/MultiUDPReceiver.java b/server/src/main/java/us/codecraft/blackhole/forward/MultiUDPReceiver.java index 244b688..8aff094 100755 --- a/server/src/main/java/us/codecraft/blackhole/forward/MultiUDPReceiver.java +++ b/server/src/main/java/us/codecraft/blackhole/forward/MultiUDPReceiver.java @@ -1,217 +1,217 @@ package us.codecraft.blackhole.forward; import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.nio.channels.DatagramChannel; import java.util.Arrays; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.xbill.DNS.Message; import org.xbill.DNS.Record; import org.xbill.DNS.Section; import org.xbill.DNS.Type; import us.codecraft.blackhole.antipollution.BlackListService; import us.codecraft.blackhole.antipollution.SafeHostService; import us.codecraft.blackhole.cache.CacheManager; import us.codecraft.blackhole.config.Configure; /** * @author [email protected] * @date Jan 16, 2013 */ @Component public class MultiUDPReceiver implements InitializingBean { private Map<Integer, ForwardAnswer> answers = new ConcurrentHashMap<Integer, ForwardAnswer>(); private DatagramChannel datagramChannel; private ExecutorService processExecutors = Executors.newFixedThreadPool(4); private final static int PORT_RECEIVE = 40311; @Autowired private CacheManager cacheManager; @Autowired private BlackListService blackListService; @Autowired private DNSHostsContainer dnsHostsContainer; @Autowired private ConnectionTimer connectionTimer; @Autowired private SafeHostService safeBoxService; private Logger logger = Logger.getLogger(getClass()); @Autowired private Configure configure; /** * */ public MultiUDPReceiver() { super(); } private byte[] removeFakeAddress(Message message, byte[] bytes) { Record[] answers = message.getSectionArray(Section.ANSWER); boolean changed = false; for (Record answer : answers) { String address = StringUtils.removeEnd(answer.rdataToString(), "."); if ((answer.getType() == Type.A || answer.getType() == Type.AAAA) && blackListService.inBlacklist(address)) { if (!changed) { // copy on write message = (Message) message.clone(); } message.removeRecord(answer, Section.ANSWER); changed = true; } } if (message.getQuestion().getType() == Type.A && (message.getSectionArray(Section.ANSWER) == null || message .getSectionArray(Section.ANSWER).length == 0) && (message.getSectionArray(Section.ADDITIONAL) == null || message .getSectionArray(Section.ADDITIONAL).length == 0) && (message.getSectionArray(Section.AUTHORITY) == null || message .getSectionArray(Section.AUTHORITY).length == 0)) { logger.info("remove message " + message.getQuestion()); return null; } if (changed) { return message.toWire(); } return bytes; } public void registerReceiver(Integer id, ForwardAnswer forwardAnswer) { answers.put(id, forwardAnswer); } public ForwardAnswer getAnswer(Integer id) { return answers.get(id); } public void removeAnswer(Integer id) { answers.remove(id); } private void receive() { final ByteBuffer byteBuffer = ByteBuffer.allocate(512); while (true) { try { byteBuffer.clear(); final SocketAddress remoteAddress = datagramChannel .receive(byteBuffer); processExecutors.submit(new Runnable() { @Override public void run() { try { handleAnswer(byteBuffer, remoteAddress); } catch (Throwable e) { logger.warn("forward exception " + e); } } }); } catch (Throwable e) { logger.warn("receive exception" + e); } } } /* * (non-Javadoc) * * @see * org.springframework.beans.factory.InitializingBean#afterPropertiesSet() */ @Override public void afterPropertiesSet() throws Exception { datagramChannel = DatagramChannel.open(); datagramChannel.socket().bind(new InetSocketAddress(PORT_RECEIVE)); new Thread(new Runnable() { @Override public void run() { receive(); } }).start(); } private void addToBlacklist(Message message) { for (Record answer : message.getSectionArray(Section.ANSWER)) { String address = StringUtils.removeEnd(answer.rdataToString(), "."); if (!blackListService.inBlacklist(address)) { logger.info("detected dns poisoning, add address " + address + " to blacklist"); blackListService.addToBlacklist(address); } } } private void handleAnswer(ByteBuffer byteBuffer, SocketAddress remoteAddress) throws IOException { byte[] answer = Arrays.copyOfRange(byteBuffer.array(), 0, byteBuffer.remaining()); final Message message = new Message(answer); // fake dns server return an answer, it must be dns pollution if (remoteAddress.equals(configure.getFakeDnsServer())) { addToBlacklist(message); String domain = StringUtils.removeEnd(message.getQuestion() .getName().toString(), "."); safeBoxService.setPoisoned(domain); return; } if (logger.isDebugEnabled()) { logger.debug("get message from " + remoteAddress + "\n" + message); } final ForwardAnswer forwardAnswer = getAnswer(message.getHeader() .getID()); if (forwardAnswer == null) { logger.warn("Oops!Received some unexpected messages! "); return; } dnsHostsContainer.registerTimeCost(remoteAddress, System.currentTimeMillis() - forwardAnswer.getStartTime()); if (forwardAnswer.getAnswer() == null) { byte[] result = removeFakeAddress(message, answer); if (result != null) { forwardAnswer.setAnswer(result); try { forwardAnswer.getLock().lockInterruptibly(); forwardAnswer.getCondition().signalAll(); } catch (InterruptedException e) { } finally { forwardAnswer.getLock().unlock(); } } } - connectionTimer.checkConnectTimeForAnswer(forwardAnswer.getQuery(), - message); + // connectionTimer.checkConnectTimeForAnswer(forwardAnswer.getQuery(), + // message); } /** * @return the datagramChannel */ public DatagramChannel getDatagramChannel() { return datagramChannel; } }
true
true
private void handleAnswer(ByteBuffer byteBuffer, SocketAddress remoteAddress) throws IOException { byte[] answer = Arrays.copyOfRange(byteBuffer.array(), 0, byteBuffer.remaining()); final Message message = new Message(answer); // fake dns server return an answer, it must be dns pollution if (remoteAddress.equals(configure.getFakeDnsServer())) { addToBlacklist(message); String domain = StringUtils.removeEnd(message.getQuestion() .getName().toString(), "."); safeBoxService.setPoisoned(domain); return; } if (logger.isDebugEnabled()) { logger.debug("get message from " + remoteAddress + "\n" + message); } final ForwardAnswer forwardAnswer = getAnswer(message.getHeader() .getID()); if (forwardAnswer == null) { logger.warn("Oops!Received some unexpected messages! "); return; } dnsHostsContainer.registerTimeCost(remoteAddress, System.currentTimeMillis() - forwardAnswer.getStartTime()); if (forwardAnswer.getAnswer() == null) { byte[] result = removeFakeAddress(message, answer); if (result != null) { forwardAnswer.setAnswer(result); try { forwardAnswer.getLock().lockInterruptibly(); forwardAnswer.getCondition().signalAll(); } catch (InterruptedException e) { } finally { forwardAnswer.getLock().unlock(); } } } connectionTimer.checkConnectTimeForAnswer(forwardAnswer.getQuery(), message); }
private void handleAnswer(ByteBuffer byteBuffer, SocketAddress remoteAddress) throws IOException { byte[] answer = Arrays.copyOfRange(byteBuffer.array(), 0, byteBuffer.remaining()); final Message message = new Message(answer); // fake dns server return an answer, it must be dns pollution if (remoteAddress.equals(configure.getFakeDnsServer())) { addToBlacklist(message); String domain = StringUtils.removeEnd(message.getQuestion() .getName().toString(), "."); safeBoxService.setPoisoned(domain); return; } if (logger.isDebugEnabled()) { logger.debug("get message from " + remoteAddress + "\n" + message); } final ForwardAnswer forwardAnswer = getAnswer(message.getHeader() .getID()); if (forwardAnswer == null) { logger.warn("Oops!Received some unexpected messages! "); return; } dnsHostsContainer.registerTimeCost(remoteAddress, System.currentTimeMillis() - forwardAnswer.getStartTime()); if (forwardAnswer.getAnswer() == null) { byte[] result = removeFakeAddress(message, answer); if (result != null) { forwardAnswer.setAnswer(result); try { forwardAnswer.getLock().lockInterruptibly(); forwardAnswer.getCondition().signalAll(); } catch (InterruptedException e) { } finally { forwardAnswer.getLock().unlock(); } } } // connectionTimer.checkConnectTimeForAnswer(forwardAnswer.getQuery(), // message); }
diff --git a/src/main/java/com/cloudbees/plugins/credentials/common/StandardCertificateCredentials.java b/src/main/java/com/cloudbees/plugins/credentials/common/StandardCertificateCredentials.java index dcb8ce8..a09c3c6 100644 --- a/src/main/java/com/cloudbees/plugins/credentials/common/StandardCertificateCredentials.java +++ b/src/main/java/com/cloudbees/plugins/credentials/common/StandardCertificateCredentials.java @@ -1,94 +1,94 @@ /* * The MIT License * * Copyright (c) 2011-2013, CloudBees, Inc., Stephen Connolly. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.cloudbees.plugins.credentials.common; import com.cloudbees.plugins.credentials.CredentialsNameProvider; import com.cloudbees.plugins.credentials.NameWith; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.annotations.NonNull; import hudson.Util; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.cert.Certificate; import java.security.cert.X509Certificate; import java.util.Enumeration; /** * Credentials that have an ID, description, keystore and password, for example client certificates for SSL. * * @since 1.7 */ @Recommended(since = "1.7") @NameWith(value = StandardCertificateCredentials.NameProvider.class, priority = 8) public interface StandardCertificateCredentials extends StandardCredentials, CertificateCredentials { /** * Our name provider. * * @since 1.7 */ public static class NameProvider extends CredentialsNameProvider<StandardCertificateCredentials> { /** * {@inheritDoc} */ @NonNull @Override public String getName(@NonNull StandardCertificateCredentials c) { String description = Util.fixEmptyAndTrim(c.getDescription()); String subjectDN = getSubjectDN(c.getKeyStore()); return (subjectDN == null ? c.getDescriptor().getDisplayName() : subjectDN) + (description != null ? " (" + description + ")" : ""); } /** * Returns the Subject DN of the first key with an x509 certificate in its certificate chain. * * @param keyStore the keystore. * @return the subject DN or {@code null} */ @CheckForNull public static String getSubjectDN(@NonNull KeyStore keyStore) { keyStore.getClass(); // throw NPE if null try { for (Enumeration<String> enumeration = keyStore.aliases(); enumeration.hasMoreElements(); ) { String alias = enumeration.nextElement(); if (keyStore.isKeyEntry(alias)) { Certificate[] certificateChain = keyStore.getCertificateChain(alias); - if (certificateChain.length > 0) { + if (certificateChain != null && certificateChain.length > 0) { Certificate certificate = certificateChain[0]; if (certificate instanceof X509Certificate) { X509Certificate x509 = (X509Certificate) certificate; return x509.getSubjectDN().getName(); } } } } } catch (KeyStoreException e) { // ignore } return null; } } }
true
true
public static String getSubjectDN(@NonNull KeyStore keyStore) { keyStore.getClass(); // throw NPE if null try { for (Enumeration<String> enumeration = keyStore.aliases(); enumeration.hasMoreElements(); ) { String alias = enumeration.nextElement(); if (keyStore.isKeyEntry(alias)) { Certificate[] certificateChain = keyStore.getCertificateChain(alias); if (certificateChain.length > 0) { Certificate certificate = certificateChain[0]; if (certificate instanceof X509Certificate) { X509Certificate x509 = (X509Certificate) certificate; return x509.getSubjectDN().getName(); } } } } } catch (KeyStoreException e) { // ignore } return null; }
public static String getSubjectDN(@NonNull KeyStore keyStore) { keyStore.getClass(); // throw NPE if null try { for (Enumeration<String> enumeration = keyStore.aliases(); enumeration.hasMoreElements(); ) { String alias = enumeration.nextElement(); if (keyStore.isKeyEntry(alias)) { Certificate[] certificateChain = keyStore.getCertificateChain(alias); if (certificateChain != null && certificateChain.length > 0) { Certificate certificate = certificateChain[0]; if (certificate instanceof X509Certificate) { X509Certificate x509 = (X509Certificate) certificate; return x509.getSubjectDN().getName(); } } } } } catch (KeyStoreException e) { // ignore } return null; }
diff --git a/src/episode_3/SimpleOGLRenderer.java b/src/episode_3/SimpleOGLRenderer.java index a9e6302..55ea7b3 100644 --- a/src/episode_3/SimpleOGLRenderer.java +++ b/src/episode_3/SimpleOGLRenderer.java @@ -1,77 +1,80 @@ /* * Copyright (c) 2012, Oskar Veerhoek * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are those * of the authors and should not be interpreted as representing official policies, * either expressed or implied, of the FreeBSD Project. */ package episode_3; import org.lwjgl.LWJGLException; import org.lwjgl.opengl.Display; import org.lwjgl.opengl.DisplayMode; import static org.lwjgl.opengl.GL11.*; /** * Shows some basic shape drawing. * * @author Oskar */ public class SimpleOGLRenderer { public static void main(String[] args) { try { Display.setDisplayMode(new DisplayMode(640, 480)); Display.setTitle("Hello, LWJGL!"); Display.create(); } catch (LWJGLException e) { e.printStackTrace(); + Display.destroy(); + System.exit(1); } glMatrixMode(GL_PROJECTION); glOrtho(0, 640, 480, 0, 1, -1); glMatrixMode(GL_MODELVIEW); while (!Display.isCloseRequested()) { glClear(GL_COLOR_BUFFER_BIT); // Start rendering rectangles glBegin(GL_QUADS); glVertex2i(400, 400); // Upper-left glVertex2i(450, 400); // Upper-right glVertex2i(450, 450); // Bottom-right glVertex2i(400, 450); // Bottom-left // Stop rendering rectangles glEnd(); // Start rendering lines glBegin(GL_LINES); glVertex2i(100, 100); glVertex2i(200, 200); // Stop rendering lines glEnd(); Display.update(); Display.sync(60); } Display.destroy(); + System.exit(0); } }
false
true
public static void main(String[] args) { try { Display.setDisplayMode(new DisplayMode(640, 480)); Display.setTitle("Hello, LWJGL!"); Display.create(); } catch (LWJGLException e) { e.printStackTrace(); } glMatrixMode(GL_PROJECTION); glOrtho(0, 640, 480, 0, 1, -1); glMatrixMode(GL_MODELVIEW); while (!Display.isCloseRequested()) { glClear(GL_COLOR_BUFFER_BIT); // Start rendering rectangles glBegin(GL_QUADS); glVertex2i(400, 400); // Upper-left glVertex2i(450, 400); // Upper-right glVertex2i(450, 450); // Bottom-right glVertex2i(400, 450); // Bottom-left // Stop rendering rectangles glEnd(); // Start rendering lines glBegin(GL_LINES); glVertex2i(100, 100); glVertex2i(200, 200); // Stop rendering lines glEnd(); Display.update(); Display.sync(60); } Display.destroy(); }
public static void main(String[] args) { try { Display.setDisplayMode(new DisplayMode(640, 480)); Display.setTitle("Hello, LWJGL!"); Display.create(); } catch (LWJGLException e) { e.printStackTrace(); Display.destroy(); System.exit(1); } glMatrixMode(GL_PROJECTION); glOrtho(0, 640, 480, 0, 1, -1); glMatrixMode(GL_MODELVIEW); while (!Display.isCloseRequested()) { glClear(GL_COLOR_BUFFER_BIT); // Start rendering rectangles glBegin(GL_QUADS); glVertex2i(400, 400); // Upper-left glVertex2i(450, 400); // Upper-right glVertex2i(450, 450); // Bottom-right glVertex2i(400, 450); // Bottom-left // Stop rendering rectangles glEnd(); // Start rendering lines glBegin(GL_LINES); glVertex2i(100, 100); glVertex2i(200, 200); // Stop rendering lines glEnd(); Display.update(); Display.sync(60); } Display.destroy(); System.exit(0); }
diff --git a/src/org/carballude/sherlock/controller/revealers/TVE.java b/src/org/carballude/sherlock/controller/revealers/TVE.java index 28f429e..4847df2 100644 --- a/src/org/carballude/sherlock/controller/revealers/TVE.java +++ b/src/org/carballude/sherlock/controller/revealers/TVE.java @@ -1,152 +1,157 @@ package org.carballude.sherlock.controller.revealers; import java.io.IOException; import java.net.MalformedURLException; import org.carballude.sherlock.controller.excepions.InvalidLinkException; import org.carballude.utilities.HTML; public class TVE implements Revealer { private boolean isTVEALaCarta(String url) { return url.contains("www.rtve.es") && url.contains("/alacarta/"); } private boolean isRTVELink(String url) { return url.contains("www.rtve.es") && url.contains("/mediateca/audios/"); } @Override public String revealLink(String link) throws MalformedURLException, IOException, InvalidLinkException { if(isTVEALaCarta(link)) return getTVEALaCarta(link); if(isRTVELink(link)) return getRTVELink(link); String id = getId(link); - String url = generateVideoXmlUrl(id); String source = ""; try { + source = HTML.HTMLSource(link); + String url = ""; + if(source.contains("id='videoplayer")) + url = generateVideoXmlUrl(source.split("id='videoplayer")[1].split("'")[0]); + else + url = generateVideoXmlUrl(id); source = HTML.HTMLSource(url); } catch (IOException e) { if (source.isEmpty()) { source = HTML.HTMLSource(link); if (source.contains("<div id=\"video")) return getTVEALaCarta("http://www.rtve.es/alacarta/#" + HTML.HTMLSource(link).split("<div id=\"video")[1].split("\"")[0]); if (source.contains("<div id=\"vid")) return getTVEALaCarta("http://www.rtve.es/alacarta/#" + HTML.HTMLSource(link).split("<div id=\"vid")[1].split("\"")[0]); } } if (xmlHasFileAddress(source)) return lookForFileTagInXml(source); if (xmlHasAnAssetXmlAddress(source)) return lookForFileWithAnAssetDataVideoXmlAddress(source); throw new InvalidLinkException(); } private String getRTVELink(String rtveLink) throws InvalidLinkException, MalformedURLException, IOException { String id = getId(rtveLink); String url = generateAudioXmlUrl(id); String source = HTML.HTMLSource(url); if (xmlHasFileAddress(source)) return lookForFileTagInXml(source); if (xmlHasAnAssetXmlAddress(source)) return lookForFileWithAnAssetDataAudioXmlAddress(source); return null; } private String lookForFileWithAnAssetDataAudioXmlAddress(String source) throws MalformedURLException, IOException { return generateAssetMp3Url(getAssetXmlDefaultLocation(HTML.HTMLSource(generateAssetDataAudioIdXmlUrl(getAssetId(source))))); } private String generateAssetDataAudioIdXmlUrl(String id) { return "http://www.rtve.es/scd/CONTENTS/ASSET_DATA_AUDIO/" + id.charAt(5) + "/" + id.charAt(4) + "/" + id.charAt(3) + "/" + id.charAt(2) + "/ASSET_DATA_AUDIO-" + id + ".xml"; } private String generateAssetMp3Url(String xmlDefaultLocation) { return "http://www.rtve.es/resources/TE_NGVA/mp3/" + xmlDefaultLocation.split("/mp3/")[1]; } private String generateAudioXmlUrl(String id) { return "http://www.rtve.es/swf/data/es/audios/audio/" + id.charAt(id.length() - 1) + "/" + id.charAt(id.length() - 2) + "/" + id.charAt(id.length() - 3) + "/" + id.charAt(id.length() - 4) + "/" + id + ".xml"; } private String getTVEALaCarta(String link) throws MalformedURLException, IOException, InvalidLinkException { if(link.contains("/alacarta/audios/")){ String source = HTML.HTMLSource(link); return source.split("<link rel=\"audio_src\" href=\"")[1].split("\"")[0]; } String chunks[]; if (link.contains("#")) chunks = link.split("#"); else chunks = link.split("/"); String url = generateVideoXmlUrl(chunks[chunks.length - 1]); String source = HTML.HTMLSource(url); if (xmlHasFileAddress(source)) return lookForFileTagInXml(source); if (xmlHasAnAssetXmlAddress(source)) return lookForFileWithAnAssetDataVideoXmlAddress(source); throw new InvalidLinkException(); } private String getId(String link) throws InvalidLinkException { String[] aux = link.split("/"); String id = aux[aux.length - 1].split("\\.")[0]; for (int i = 0; i < id.length(); i++) if (!Character.isDigit(id.charAt(i))) throw new InvalidLinkException(); return id; } private String generateVideoXmlUrl(String id) { return "http://www.rtve.es/swf/data/es/videos/video/" + id.charAt(id.length() - 1) + "/" + id.charAt(id.length() - 2) + "/" + id.charAt(id.length() - 3) + "/" + id.charAt(id.length() - 4) + "/" + id + ".xml"; } private boolean xmlHasFileAddress(String source) { return source.contains("<file>") && source.contains("</file>"); } private String lookForFileTagInXml(String source) { return getFileFromXmlAddress(source); } private String getFileFromXmlAddress(String source) { if (!xmlHasFileAddress(source)) throw new IllegalArgumentException(); return source.split("<file>")[1].split("</file>")[0]; } private boolean xmlHasAnAssetXmlAddress(String source) { return source.contains("<file/>") && source.contains("assetDataId::"); } private String lookForFileWithAnAssetDataVideoXmlAddress(String source) throws MalformedURLException, IOException { String assetRelativeLocation = getAssetXmlDefaultLocation(HTML.HTMLSource(generateAssetDataVideoIdXmlUrl(getAssetId(source)))); if (assetRelativeLocation.contains("/flv/")) return generateAssetDownloadLocation("flv", assetRelativeLocation); if (assetRelativeLocation.contains("/mp4/")) return generateAssetDownloadLocation("mp4", assetRelativeLocation); throw new IOException(); } private String getAssetXmlDefaultLocation(String source) { return source.split("defaultLocation=\"")[1].split("\"")[0]; } private String getAssetId(String source) { return source.split("assetDataId::")[1].substring(0, 6); } private String generateAssetDownloadLocation(String format, String relativeLocation) { return "http://www.rtve.es/resources/TE_NGVA/" + format + "/" + relativeLocation.split("/" + format + "/")[1]; } private String generateAssetDataVideoIdXmlUrl(String id) { return "http://www.rtve.es/scd/CONTENTS/ASSET_DATA_VIDEO/" + id.charAt(5) + "/" + id.charAt(4) + "/" + id.charAt(3) + "/" + id.charAt(2) + "/ASSET_DATA_VIDEO-" + id + ".xml"; } }
false
true
public String revealLink(String link) throws MalformedURLException, IOException, InvalidLinkException { if(isTVEALaCarta(link)) return getTVEALaCarta(link); if(isRTVELink(link)) return getRTVELink(link); String id = getId(link); String url = generateVideoXmlUrl(id); String source = ""; try { source = HTML.HTMLSource(url); } catch (IOException e) { if (source.isEmpty()) { source = HTML.HTMLSource(link); if (source.contains("<div id=\"video")) return getTVEALaCarta("http://www.rtve.es/alacarta/#" + HTML.HTMLSource(link).split("<div id=\"video")[1].split("\"")[0]); if (source.contains("<div id=\"vid")) return getTVEALaCarta("http://www.rtve.es/alacarta/#" + HTML.HTMLSource(link).split("<div id=\"vid")[1].split("\"")[0]); } } if (xmlHasFileAddress(source)) return lookForFileTagInXml(source); if (xmlHasAnAssetXmlAddress(source)) return lookForFileWithAnAssetDataVideoXmlAddress(source); throw new InvalidLinkException(); }
public String revealLink(String link) throws MalformedURLException, IOException, InvalidLinkException { if(isTVEALaCarta(link)) return getTVEALaCarta(link); if(isRTVELink(link)) return getRTVELink(link); String id = getId(link); String source = ""; try { source = HTML.HTMLSource(link); String url = ""; if(source.contains("id='videoplayer")) url = generateVideoXmlUrl(source.split("id='videoplayer")[1].split("'")[0]); else url = generateVideoXmlUrl(id); source = HTML.HTMLSource(url); } catch (IOException e) { if (source.isEmpty()) { source = HTML.HTMLSource(link); if (source.contains("<div id=\"video")) return getTVEALaCarta("http://www.rtve.es/alacarta/#" + HTML.HTMLSource(link).split("<div id=\"video")[1].split("\"")[0]); if (source.contains("<div id=\"vid")) return getTVEALaCarta("http://www.rtve.es/alacarta/#" + HTML.HTMLSource(link).split("<div id=\"vid")[1].split("\"")[0]); } } if (xmlHasFileAddress(source)) return lookForFileTagInXml(source); if (xmlHasAnAssetXmlAddress(source)) return lookForFileWithAnAssetDataVideoXmlAddress(source); throw new InvalidLinkException(); }
diff --git a/src/directi/androidteam/training/chatclient/Chat/ChatFragment.java b/src/directi/androidteam/training/chatclient/Chat/ChatFragment.java index db1cd4e..b6a1d1f 100644 --- a/src/directi/androidteam/training/chatclient/Chat/ChatFragment.java +++ b/src/directi/androidteam/training/chatclient/Chat/ChatFragment.java @@ -1,175 +1,176 @@ package directi.androidteam.training.chatclient.Chat; import android.os.Bundle; import android.support.v4.app.ListFragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import directi.androidteam.training.StanzaStore.MessageStanza; import directi.androidteam.training.chatclient.R; import directi.androidteam.training.chatclient.Roster.RosterItem; import directi.androidteam.training.chatclient.Roster.RosterManager; import java.util.Vector; /** * Created with IntelliJ IDEA. * User: vinayak * Date: 11/9/12 * Time: 6:01 PM * To change this template use File | Settings | File Templates. */ public class ChatFragment extends ListFragment { private Vector<ChatListItem> chatListItems; private ChatListAdaptor adaptor; private String buddyid="talk.to"; private String myAccountUID; public String getMyAccountUID() { return myAccountUID; } public ChatFragment() { } public ChatFragment(String from) { this.buddyid = from; } @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); if(getArguments()!=null){ buddyid = (String)getArguments().get("from"); chatListItems = toChatListItemList(MyFragmentManager.getInstance().getFragList(buddyid)); myAccountUID = (String)getArguments().get("accountUID"); } else if(!buddyid.equals(("talk.to"))) chatListItems = toChatListItemList(MyFragmentManager.getInstance().getFragList(buddyid)); else chatListItems = new Vector<ChatListItem>(); } @Override public void onActivityCreated(Bundle savedInstanceState){ super.onActivityCreated(savedInstanceState); adaptor = new ChatListAdaptor(getActivity(), chatListItems); ListView lv = getListView(); LayoutInflater linf = getLayoutInflater(savedInstanceState); ViewGroup header = (ViewGroup)linf.inflate(R.layout.chatlistheader,lv,false); lv.addHeaderView(header,null,false); TextView tv = (TextView)(header.findViewById(R.id.chatfragment_jid)); tv.setText(buddyid); ImageView imageView = (ImageView) (header.findViewById(R.id.chatfragment_image)); TextView status = (TextView)(header.findViewById(R.id.chatfragment_status)); RosterItem re = RosterManager.getInstance().getRosterItem(myAccountUID, buddyid); - imageView.setImageBitmap(re.getAvatar()); + if(imageView!=null && re!=null) + imageView.setImageBitmap(re.getAvatar()); ImageView presence = (ImageView)(header.findViewById(R.id.chatfragment_availability_image)); ImageView closeWindow = (ImageView)(header.findViewById(R.id.chatlistheader_close)); closeWindow.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { MyFragmentManager.getInstance().removeFragEntry(buddyid); sendGoneMsg(); closeFragment(buddyid); } }); if(re!=null){ status.setText(re.getStatus()); if(re.getPresence().equals("dnd")){ presence.setImageResource(R.drawable.red); } else if(re.getPresence().equals("chat")){ presence.setImageResource(R.drawable.green); } else if(re.getPresence().equals("away")){ presence.setImageResource(R.drawable.yellow); } } else status.setText("null"); setListAdapter(adaptor); } private void sendGoneMsg() { MessageStanza messageStanza = new MessageStanza(buddyid); messageStanza.formGoneMsg(); messageStanza.send(getMyAccountUID()); } public static ChatFragment getInstance(String from){ ChatFragment chatFragment = new ChatFragment(from); Bundle args = new Bundle(); args.putString("from", from); chatFragment.setArguments(args); return chatFragment; } public void addChatItem(MessageStanza message, boolean b){ if(chatListItems==null) { return; } ChatListItem cli = new ChatListItem(message); if(b && chatListItems.size()>0) chatListItems.remove(chatListItems.size()-1); //added - 3/10 chatListItems.add(cli); PacketStatusManager.getInstance().pushCliPacket(cli); ChatBox.adaptorNotify(this); } public void notifyAdaptor(){ adaptor.notifyDataSetChanged(); if(isVisible() || isResumed()) { //added ListView lv = getListView(); lv.setFocusable(true); if(lv.getChildCount()>0){ lv.getChildAt(lv.getChildCount()-1).setFocusable(true); lv.setSelection(lv.getChildCount()-1); } } } @Override public void onResume(){ super.onResume(); notifyAdaptor(); } @Override public void onPause(){ super.onPause(); } private synchronized Vector<ChatListItem> toChatListItemList(Vector<MessageStanza> list){ Vector<ChatListItem> chatItemList = new Vector<ChatListItem>(); Object[] objects = list.toArray(); for (Object object : objects) { ChatListItem cli = new ChatListItem((MessageStanza) object); chatItemList.add(cli); } return chatItemList; } private void closeFragment(String jid){ if(MyFragmentManager.getInstance().getSizeofActiveChats()==0) ChatBox.finishActivity(); else { // ChatBox.notifyFragmentAdaptorInSameThread(); ChatBox.removeFragmentviaFragManager(jid); ChatBox.notifyFragmentAdaptorInSameThread(); } } }
true
true
public void onActivityCreated(Bundle savedInstanceState){ super.onActivityCreated(savedInstanceState); adaptor = new ChatListAdaptor(getActivity(), chatListItems); ListView lv = getListView(); LayoutInflater linf = getLayoutInflater(savedInstanceState); ViewGroup header = (ViewGroup)linf.inflate(R.layout.chatlistheader,lv,false); lv.addHeaderView(header,null,false); TextView tv = (TextView)(header.findViewById(R.id.chatfragment_jid)); tv.setText(buddyid); ImageView imageView = (ImageView) (header.findViewById(R.id.chatfragment_image)); TextView status = (TextView)(header.findViewById(R.id.chatfragment_status)); RosterItem re = RosterManager.getInstance().getRosterItem(myAccountUID, buddyid); imageView.setImageBitmap(re.getAvatar()); ImageView presence = (ImageView)(header.findViewById(R.id.chatfragment_availability_image)); ImageView closeWindow = (ImageView)(header.findViewById(R.id.chatlistheader_close)); closeWindow.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { MyFragmentManager.getInstance().removeFragEntry(buddyid); sendGoneMsg(); closeFragment(buddyid); } }); if(re!=null){ status.setText(re.getStatus()); if(re.getPresence().equals("dnd")){ presence.setImageResource(R.drawable.red); } else if(re.getPresence().equals("chat")){ presence.setImageResource(R.drawable.green); } else if(re.getPresence().equals("away")){ presence.setImageResource(R.drawable.yellow); } } else status.setText("null"); setListAdapter(adaptor); }
public void onActivityCreated(Bundle savedInstanceState){ super.onActivityCreated(savedInstanceState); adaptor = new ChatListAdaptor(getActivity(), chatListItems); ListView lv = getListView(); LayoutInflater linf = getLayoutInflater(savedInstanceState); ViewGroup header = (ViewGroup)linf.inflate(R.layout.chatlistheader,lv,false); lv.addHeaderView(header,null,false); TextView tv = (TextView)(header.findViewById(R.id.chatfragment_jid)); tv.setText(buddyid); ImageView imageView = (ImageView) (header.findViewById(R.id.chatfragment_image)); TextView status = (TextView)(header.findViewById(R.id.chatfragment_status)); RosterItem re = RosterManager.getInstance().getRosterItem(myAccountUID, buddyid); if(imageView!=null && re!=null) imageView.setImageBitmap(re.getAvatar()); ImageView presence = (ImageView)(header.findViewById(R.id.chatfragment_availability_image)); ImageView closeWindow = (ImageView)(header.findViewById(R.id.chatlistheader_close)); closeWindow.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { MyFragmentManager.getInstance().removeFragEntry(buddyid); sendGoneMsg(); closeFragment(buddyid); } }); if(re!=null){ status.setText(re.getStatus()); if(re.getPresence().equals("dnd")){ presence.setImageResource(R.drawable.red); } else if(re.getPresence().equals("chat")){ presence.setImageResource(R.drawable.green); } else if(re.getPresence().equals("away")){ presence.setImageResource(R.drawable.yellow); } } else status.setText("null"); setListAdapter(adaptor); }
diff --git a/src/unit-tests/java/com/forum/web/controller/QuestionControllerTest.java b/src/unit-tests/java/com/forum/web/controller/QuestionControllerTest.java index 5926600..18f55d4 100644 --- a/src/unit-tests/java/com/forum/web/controller/QuestionControllerTest.java +++ b/src/unit-tests/java/com/forum/web/controller/QuestionControllerTest.java @@ -1,42 +1,42 @@ package com.forum.web.controller; import com.forum.service.QuestionService; import org.junit.Test; import org.springframework.web.servlet.ModelAndView; import java.util.HashMap; import java.util.Map; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; public class QuestionControllerTest { private QuestionController questionController; @Test public void shouldShowPostQuestionPage(){ this.questionController = new QuestionController(null); ModelAndView questionPageModelAndView = questionController.postQuestion(); assertThat(questionPageModelAndView.getViewName() ,is("postQuestion")); } @Test public void shouldReturnPostedQuestion(){ QuestionService mockedQuestionService = mock(QuestionService.class); Map<String, String> params = new HashMap<String, String>(); - params.put("title", "Question Title"); - params.put("description", "Question Description"); + params.put("questionTitle", "Question Title"); + params.put("editor", "Question Description"); mockedQuestionService.createQuestion(params); this.questionController = new QuestionController(mockedQuestionService); ModelAndView questionModelAndView = questionController.showPostedQuestion(params); String questionTitle = (String)questionModelAndView.getModel().get("questionTitle"); String questionDescription = (String)questionModelAndView.getModel().get("questionDescription"); assertThat(questionTitle, is("Question Title")); assertThat(questionDescription, is("Question Description")); } }
true
true
public void shouldReturnPostedQuestion(){ QuestionService mockedQuestionService = mock(QuestionService.class); Map<String, String> params = new HashMap<String, String>(); params.put("title", "Question Title"); params.put("description", "Question Description"); mockedQuestionService.createQuestion(params); this.questionController = new QuestionController(mockedQuestionService); ModelAndView questionModelAndView = questionController.showPostedQuestion(params); String questionTitle = (String)questionModelAndView.getModel().get("questionTitle"); String questionDescription = (String)questionModelAndView.getModel().get("questionDescription"); assertThat(questionTitle, is("Question Title")); assertThat(questionDescription, is("Question Description")); }
public void shouldReturnPostedQuestion(){ QuestionService mockedQuestionService = mock(QuestionService.class); Map<String, String> params = new HashMap<String, String>(); params.put("questionTitle", "Question Title"); params.put("editor", "Question Description"); mockedQuestionService.createQuestion(params); this.questionController = new QuestionController(mockedQuestionService); ModelAndView questionModelAndView = questionController.showPostedQuestion(params); String questionTitle = (String)questionModelAndView.getModel().get("questionTitle"); String questionDescription = (String)questionModelAndView.getModel().get("questionDescription"); assertThat(questionTitle, is("Question Title")); assertThat(questionDescription, is("Question Description")); }
diff --git a/java/client/src/org/openqa/selenium/chrome/ChromeDriverService.java b/java/client/src/org/openqa/selenium/chrome/ChromeDriverService.java index f3b3fa174..e5ad91fc2 100644 --- a/java/client/src/org/openqa/selenium/chrome/ChromeDriverService.java +++ b/java/client/src/org/openqa/selenium/chrome/ChromeDriverService.java @@ -1,269 +1,270 @@ // Copyright 2011 Google Inc. All Rights Reserved. package org.openqa.selenium.chrome; import org.openqa.selenium.WebDriverException; import org.openqa.selenium.browserlaunchers.AsyncExecute; import org.openqa.selenium.net.PortProber; import org.openqa.selenium.net.UrlChecker; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.net.MalformedURLException; import java.net.URL; import java.util.concurrent.locks.ReentrantLock; import static com.google.common.base.Preconditions.*; import static java.util.concurrent.TimeUnit.SECONDS; import static org.openqa.selenium.os.CommandLine.findExecutable; /** * Manages the life and death of a chromedriver server. */ public class ChromeDriverService { /** * System property that defines the location of the chromedriver executable * that will be used by the {@link #createDefaultService() default service}. */ public static final String CHROME_DRIVER_EXE_PROPERTY = "webdriver.chrome.driver"; /** * Used to spawn a new child process when this service is {@link #start() started}. */ private final ProcessBuilder processBuilder; /** * The base URL for the managed server. */ private final URL url; /** * Controls access to {@link #process}. */ private final ReentrantLock lock = new ReentrantLock(); /** * A reference to the current child process. Will be {@code null} whenever * this service is not running. Protected by {@link #lock}. */ private Process process = null; /** * @param executable The chromedriver executable. * @param port Which port to start the chromedriver on. * @throws IOException If an I/O error occurs. */ private ChromeDriverService(File executable, int port) throws IOException { this.processBuilder = new ProcessBuilder( executable.getCanonicalPath(), String.format("--port=%d", port)); url = new URL(String.format("http://localhost:%d", port)); } /** * @return The base URL for the managed chromedriver server. */ public URL getUrl() { return url; } /** * Configures and returns a new {@link ChromeDriverService} using the default * configuration. In this configuration, the service will use the * chromedriver executable identified by the * {@link #CHROME_DRIVER_EXE_PROPERTY} system property. Each service created * by this method will be configured to use a free port on the current * system. * * @return A new ChromeDriverService using the default configuration. */ public static ChromeDriverService createDefaultService() { String defaultPath = findExecutable("chromedriver"); String exePath = System.getProperty(CHROME_DRIVER_EXE_PROPERTY, defaultPath); checkState(exePath != null, - "The path to the chromedriver executable must be set by the %s system property", + "The path to the chromedriver executable must be set by the %s system property;" + + " fore more information, see http://code.google.com/p/selenium/wiki/ChromeDriver", CHROME_DRIVER_EXE_PROPERTY); File exe = new File(exePath); checkState(exe.exists(), "The %s system property defined chromedriver executable does not exist: %s", CHROME_DRIVER_EXE_PROPERTY, exe.getAbsolutePath()); checkState(!exe.isDirectory(), "The %s system property defined chromedriver executable is a directory: %s", CHROME_DRIVER_EXE_PROPERTY, exe.getAbsolutePath()); // TODO(jleyba): Check file.canExecute() once we support Java 1.6 //checkState(exe.canExecute(), // "The %s system property defined chromedriver is not executable: %s", // CHROME_DRIVER_EXE_PROPERTY, exe.getAbsolutePath()); return new Builder() .usingChromeDriverExecutable(exe) .usingAnyFreePort() .build(); } /** * Checks whether the chromedriver child proces is currently running. * * @return Whether the chromedriver child process is still running. */ public boolean isRunning() { lock.lock(); try { if (process == null) { return false; } process.exitValue(); return false; } catch (IllegalThreadStateException e) { return true; } finally { lock.unlock(); } } /** * Starts this service if it is not already running. This method will * block until the server has been fully started and is ready to handle * commands. * * @throws IOException If an error occurs while spawning the child process. * @see #stop() */ public void start() throws IOException { lock.lock(); try { if (process != null) { return; } process = processBuilder.start(); pipe(process.getErrorStream(), System.err); pipe(process.getInputStream(), System.out); URL status = new URL(url.toString() + "/status"); URL healthz = new URL(url.toString() + "/healthz"); new UrlChecker().waitUntilAvailable(20, SECONDS, status, healthz); } catch (UrlChecker.TimeoutException e) { throw new WebDriverException("Timed out waiting for ChromeDriver server to start.", e); } finally { lock.unlock(); } } // http://stackoverflow.com/questions/60302 private static void pipe(final InputStream src, final PrintStream dest) { new Thread(new Runnable() { public void run() { try { byte[] buffer = new byte[1024]; for (int n = 0; n != -1; n = src.read(buffer)) { dest.write(buffer, 0, n); } } catch (IOException e) { // Do nothing. } } }).start(); } /** * Stops this service is it is currently running. This method will attempt to * block until the server has been fully shutdown. * * @see #start() */ public void stop() { lock.lock(); try { if (process == null) { return; } URL killUrl = new URL(url.toString() + "/shutdown"); new UrlChecker().waitUntilUnavailable(3, SECONDS, killUrl); AsyncExecute.killProcess(process); } catch (MalformedURLException e) { throw new WebDriverException(e); } catch (UrlChecker.TimeoutException e) { throw new WebDriverException("Timed out waiting for ChromeDriver server to shutdown.", e); } finally { process = null; lock.unlock(); } } /** * Builder used to configure new {@link ChromeDriverService} instances. */ public static class Builder { private int port = 0; private File exe = null; /** * Sets which chromedriver executable the builder will use. * * @param file The executable to use. * @return A self reference. */ public Builder usingChromeDriverExecutable(File file) { checkNotNull(file); checkArgument(file.exists(), "Specified chromedriver executable does not exist: %s", file.getPath()); checkArgument(!file.isDirectory(), "Specified chromedriver executable is a directory: %s", file.getPath()); // TODO(jleyba): Check file.canExecute() once we support Java 1.6 // checkArgument(file.canExecute(), "File is not executable: %s", file.getPath()); this.exe = file; return this; } /** * Sets which port the chromedriver server should be started on. A value of * 0 indicates that any free port may be used. * * @param port The port to use; must be non-negative. * @return A self reference. */ public Builder usingPort(int port) { checkArgument(port >= 0, "Invalid port number: %d", port); this.port = port; return this; } /** * Configures the chromedriver server to start on any available port. * * @return A self reference. */ public Builder usingAnyFreePort() { this.port = 0; return this; } /** * Creates a new binary to manage the chromedriver server. Before creating * a new binary, the builder will check that either the user defined the * location of the chromedriver executable through * {@link #usingChromeDriverExecutable(File) the API} or with the * {@code webdriver.chrome.driver} system property. * * @return The new binary. */ public ChromeDriverService build() { if (port == 0) { port = PortProber.findFreePort(); } checkState(exe != null, "Path to the chromedriver executable not specified"); try { return new ChromeDriverService(exe, port); } catch (IOException e) { throw new WebDriverException(e); } } } }
true
true
public static ChromeDriverService createDefaultService() { String defaultPath = findExecutable("chromedriver"); String exePath = System.getProperty(CHROME_DRIVER_EXE_PROPERTY, defaultPath); checkState(exePath != null, "The path to the chromedriver executable must be set by the %s system property", CHROME_DRIVER_EXE_PROPERTY); File exe = new File(exePath); checkState(exe.exists(), "The %s system property defined chromedriver executable does not exist: %s", CHROME_DRIVER_EXE_PROPERTY, exe.getAbsolutePath()); checkState(!exe.isDirectory(), "The %s system property defined chromedriver executable is a directory: %s", CHROME_DRIVER_EXE_PROPERTY, exe.getAbsolutePath()); // TODO(jleyba): Check file.canExecute() once we support Java 1.6 //checkState(exe.canExecute(), // "The %s system property defined chromedriver is not executable: %s", // CHROME_DRIVER_EXE_PROPERTY, exe.getAbsolutePath()); return new Builder() .usingChromeDriverExecutable(exe) .usingAnyFreePort() .build(); }
public static ChromeDriverService createDefaultService() { String defaultPath = findExecutable("chromedriver"); String exePath = System.getProperty(CHROME_DRIVER_EXE_PROPERTY, defaultPath); checkState(exePath != null, "The path to the chromedriver executable must be set by the %s system property;" + " fore more information, see http://code.google.com/p/selenium/wiki/ChromeDriver", CHROME_DRIVER_EXE_PROPERTY); File exe = new File(exePath); checkState(exe.exists(), "The %s system property defined chromedriver executable does not exist: %s", CHROME_DRIVER_EXE_PROPERTY, exe.getAbsolutePath()); checkState(!exe.isDirectory(), "The %s system property defined chromedriver executable is a directory: %s", CHROME_DRIVER_EXE_PROPERTY, exe.getAbsolutePath()); // TODO(jleyba): Check file.canExecute() once we support Java 1.6 //checkState(exe.canExecute(), // "The %s system property defined chromedriver is not executable: %s", // CHROME_DRIVER_EXE_PROPERTY, exe.getAbsolutePath()); return new Builder() .usingChromeDriverExecutable(exe) .usingAnyFreePort() .build(); }
diff --git a/src/org/dita/dost/platform/Integrator.java b/src/org/dita/dost/platform/Integrator.java index 7f10a4cb3..19956b8d0 100644 --- a/src/org/dita/dost/platform/Integrator.java +++ b/src/org/dita/dost/platform/Integrator.java @@ -1,418 +1,421 @@ /* * This file is part of the DITA Open Toolkit project hosted on * Sourceforge.net. See the accompanying license.txt file for * applicable licenses. */ /* * (c) Copyright IBM Corp. 2005, 2006 All Rights Reserved. */ package org.dita.dost.platform; import static org.dita.dost.util.Constants.*; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import org.dita.dost.log.DITAOTJavaLogger; import org.dita.dost.log.DITAOTLogger; import org.dita.dost.log.MessageUtils; import org.dita.dost.util.FileUtils; import org.dita.dost.util.StringUtils; import org.xml.sax.XMLReader; /** * Integrator is the main class to control and excute the integration of the * toolkit and different plug-ins. * * @author Zhang, Yuan Peng */ public final class Integrator { /** Feature name for supported image extensions. */ public static final String FEAT_IMAGE_EXTENSIONS = "dita.image.extensions"; public static final String FEAT_VALUE_SEPARATOR = ","; public static final String PARAM_VALUE_SEPARATOR = ";"; public static final String PARAM_NAME_SEPARATOR = "="; /** Plugin table which contains detected plugins. */ private final Map<String, Features> pluginTable; private final Set<String> templateSet = new HashSet<String>(INT_16); private File ditaDir; private File basedir; /** Plugin configuration file. */ private final Set<File> descSet; private final XMLReader reader; private DITAOTLogger logger; private final Set<String> loadedPlugin; private final Hashtable<String, String> featureTable; private File propertiesFile; private final Set<String> extensionPoints; private Properties properties; /** * Execute point of Integrator. */ public void execute() { if (logger == null) { logger = new DITAOTJavaLogger(); } if (!ditaDir.isAbsolute()) { ditaDir = new File(basedir, ditaDir.getPath()); } // Read the properties file, if it exists. properties = new Properties(); if (propertiesFile != null) { FileInputStream propertiesStream = null; try { propertiesStream = new FileInputStream(propertiesFile); properties.load(propertiesStream); } catch (final Exception e) { logger.logException(e); } finally { if (propertiesStream != null) { try { propertiesStream.close(); } catch (IOException e) { logger.logException(e); } } } } else { // Set reasonable defaults. properties.setProperty("plugindirs", "plugins;demo"); properties.setProperty("plugin.ignores", ""); } // Get the list of plugin directories from the properties. final String[] pluginDirs = properties.getProperty("plugindirs").split(PARAM_VALUE_SEPARATOR); final Set<String> pluginIgnores = new HashSet<String>(); if (properties.getProperty("plugin.ignores") != null) { pluginIgnores.addAll(Arrays.asList(properties.getProperty("plugin.ignores").split(PARAM_VALUE_SEPARATOR))); } for (final String tmpl : properties.getProperty(CONF_TEMPLATES, "").split(PARAM_VALUE_SEPARATOR)) { final String t = tmpl.trim(); if (t.length() != 0) { templateSet.add(t); } } for (final String pluginDir2 : pluginDirs) { - final File pluginDir = new File(ditaDir, pluginDir2); + File pluginDir = new File(pluginDir2); + if (!pluginDir.isAbsolute()) { + pluginDir = new File(ditaDir, pluginDir.getPath()); + } final File[] pluginFiles = pluginDir.listFiles(); for (int i = 0; (pluginFiles != null) && (i < pluginFiles.length); i++) { final File f = pluginFiles[i]; final File descFile = new File(pluginFiles[i], "plugin.xml"); if (pluginFiles[i].isDirectory() && !pluginIgnores.contains(f.getName()) && descFile.exists()) { descSet.add(descFile); } } } parsePlugin(); integrate(); } /** * Generate and process plugin files. */ private void integrate() { // Collect information for each feature id and generate a feature table. final FileGenerator fileGen = new FileGenerator(featureTable, pluginTable); fileGen.setLogger(logger); for (final String currentPlugin : pluginTable.keySet()) { loadPlugin(currentPlugin); } // generate the files from template for (final String template : templateSet) { final File templateFile = new File(ditaDir, template); logger.logDebug("Process template " + templateFile.getPath()); fileGen.generate(templateFile); } // Added on 2010-11-09 for bug 3102827: Allow a way to specify // recognized image extensions -- start // generate configuration properties final Properties configuration = new Properties(); // image extensions final Set<String> imgExts = new HashSet<String>(); for (final String ext : properties.getProperty(CONF_SUPPORTED_IMAGE_EXTENSIONS, "").split(CONF_LIST_SEPARATOR)) { final String e = ext.trim(); if (e.length() != 0) { imgExts.add(e); } } if (featureTable.containsKey(FEAT_IMAGE_EXTENSIONS)) { for (final String ext : featureTable.get(FEAT_IMAGE_EXTENSIONS).split(FEAT_VALUE_SEPARATOR)) { final String e = ext.trim(); if (e.length() != 0) { imgExts.add(e); } } } configuration.put(CONF_SUPPORTED_IMAGE_EXTENSIONS, StringUtils.assembleString(imgExts, CONF_LIST_SEPARATOR)); OutputStream out = null; try { final File outFile = new File(ditaDir, "lib" + File.separator + CONF_PROPERTIES); logger.logDebug("Generate configuration properties " + outFile.getPath()); out = new BufferedOutputStream(new FileOutputStream(outFile)); configuration.store(out, "DITA-OT runtime configuration"); } catch (final Exception e) { logger.logException(e); // throw new // RuntimeException("Failed to write configuration properties: " + // e.getMessage(), e); } finally { if (out != null) { try { out.close(); } catch (final IOException e) { logger.logException(e); } } } } // Added on 2010-11-09 for bug 3102827: Allow a way to specify recognized // image extensions -- end /** * Load the plug-ins and aggregate them by feature and fill into feature * table. * * @param plugin plugin ID * @return {@code true}> if plugin was loaded, otherwise {@code false} */ private boolean loadPlugin(final String plugin) { if (checkPlugin(plugin)) { final Features pluginFeatures = pluginTable.get(plugin); final Set<Map.Entry<String, String>> featureSet = pluginFeatures.getAllFeatures(); for (final Map.Entry<String, String> currentFeature : featureSet) { if (!extensionPoints.contains(currentFeature.getKey())) { logger.logDebug("Plug-in " + plugin + " uses an undefined extension point " + currentFeature.getKey()); } if (featureTable.containsKey(currentFeature.getKey())) { final String value = featureTable.remove(currentFeature.getKey()); featureTable.put(currentFeature.getKey(), new StringBuffer(value).append(FEAT_VALUE_SEPARATOR) .append(currentFeature.getValue()).toString()); } else { featureTable.put(currentFeature.getKey(), currentFeature.getValue()); } } for (final String templateName : pluginFeatures.getAllTemplates()) { templateSet.add(FileUtils.getRelativePathFromMap(getDitaDir() + File.separator + "dummy", pluginFeatures.getLocation() + File.separator + templateName)); } loadedPlugin.add(plugin); return true; } else { return false; } } /** * Check whether the plugin can be loaded. * * @param currentPlugin plugin ID * @return {@code true} if plugin can be loaded, otherwise {@code false} */ private boolean checkPlugin(final String currentPlugin) { final Features pluginFeatures = pluginTable.get(currentPlugin); final Iterator<PluginRequirement> iter = pluginFeatures.getRequireListIter(); // check whether dependcy is satisfied while (iter.hasNext()) { boolean anyPluginFound = false; final PluginRequirement requirement = iter.next(); final Iterator<String> requiredPluginIter = requirement.getPlugins(); while (requiredPluginIter.hasNext()) { // Iterate over all alternatives in plugin requirement. final String requiredPlugin = requiredPluginIter.next(); if (pluginTable.containsKey(requiredPlugin)) { if (!loadedPlugin.contains(requiredPlugin)) { // required plug-in is not loaded loadPlugin(requiredPlugin); } // As soon as any plugin is found, it's OK. anyPluginFound = true; } } if (!anyPluginFound && requirement.getRequired()) { // not contain any plugin required by current plugin final Properties prop = new Properties(); prop.put("%1", requirement.toString()); prop.put("%2", currentPlugin); logger.logWarn(MessageUtils.getMessage("DOTJ020W", prop).toString()); return false; } } return true; } /** * Parse plugin configuration files. */ private void parsePlugin() { if (!descSet.isEmpty()) { for (final File descFile : descSet) { logger.logDebug("Read plugin configuration " + descFile.getPath()); parseDesc(descFile); } } } /** * Parse plugin configuration file * * @param descFile plugin configuration */ private void parseDesc(final File descFile) { try { final DescParser parser = new DescParser(descFile.getParentFile(), ditaDir); reader.setContentHandler(parser); reader.parse(descFile.getAbsolutePath()); final Features f = parser.getFeatures(); extensionPoints.addAll(f.getExtensionPoints().keySet()); pluginTable.put(f.getPluginId(), f); } catch (final Exception e) { logger.logException(e); } } /** * Default Constructor. */ public Integrator() { pluginTable = new HashMap<String, Features>(INT_16); descSet = new HashSet<File>(INT_16); loadedPlugin = new HashSet<String>(INT_16); featureTable = new Hashtable<String, String>(INT_16); extensionPoints = new HashSet<String>(); try { reader = StringUtils.getXMLReader(); } catch (final Exception e) { throw new RuntimeException("Failed to initialize XML parser: " + e.getMessage(), e); } } /** * Return the basedir. * * @return base directory */ public File getBasedir() { return basedir; } /** * Set the basedir. * * @param baseDir base directory */ public void setBasedir(final File baseDir) { this.basedir = baseDir; } /** * Return the ditaDir. * * @return dita directory */ public File getDitaDir() { return ditaDir; } /** * Set the ditaDir. * * @param ditadir dita directory */ public void setDitaDir(final File ditadir) { this.ditaDir = ditadir; } /** * Return the properties file. * * @return properties file */ public File getProperties() { return propertiesFile; } /** * Set the properties file. * * @param propertiesfile properties file */ public void setProperties(final File propertiesfile) { this.propertiesFile = propertiesfile; } /** * Set logger. * * @param logger logger instance */ public void setLogger(final DITAOTLogger logger) { this.logger = logger; } /** * Get all and combine extension values * * @param featureTable plugin features * @param extension extension ID * @return combined extension value, {@code null} if no value available */ static final String getValue(final Map<String, Features> featureTable, final String extension) { final List<String> buf = new ArrayList<String>(); for (final Features f : featureTable.values()) { final String v = f.getFeature(extension); if (v != null) { buf.add(v); } } if (buf.isEmpty()) { return null; } else { return StringUtils.assembleString(buf, ","); } } /** * Command line interface for testing. * * @param args arguments */ public static void main(final String[] args) { final Integrator abc = new Integrator(); final File currentDir = new File("."); abc.setDitaDir(currentDir); abc.setProperties(new File("integrator.properties")); abc.execute(); } }
true
true
public void execute() { if (logger == null) { logger = new DITAOTJavaLogger(); } if (!ditaDir.isAbsolute()) { ditaDir = new File(basedir, ditaDir.getPath()); } // Read the properties file, if it exists. properties = new Properties(); if (propertiesFile != null) { FileInputStream propertiesStream = null; try { propertiesStream = new FileInputStream(propertiesFile); properties.load(propertiesStream); } catch (final Exception e) { logger.logException(e); } finally { if (propertiesStream != null) { try { propertiesStream.close(); } catch (IOException e) { logger.logException(e); } } } } else { // Set reasonable defaults. properties.setProperty("plugindirs", "plugins;demo"); properties.setProperty("plugin.ignores", ""); } // Get the list of plugin directories from the properties. final String[] pluginDirs = properties.getProperty("plugindirs").split(PARAM_VALUE_SEPARATOR); final Set<String> pluginIgnores = new HashSet<String>(); if (properties.getProperty("plugin.ignores") != null) { pluginIgnores.addAll(Arrays.asList(properties.getProperty("plugin.ignores").split(PARAM_VALUE_SEPARATOR))); } for (final String tmpl : properties.getProperty(CONF_TEMPLATES, "").split(PARAM_VALUE_SEPARATOR)) { final String t = tmpl.trim(); if (t.length() != 0) { templateSet.add(t); } } for (final String pluginDir2 : pluginDirs) { final File pluginDir = new File(ditaDir, pluginDir2); final File[] pluginFiles = pluginDir.listFiles(); for (int i = 0; (pluginFiles != null) && (i < pluginFiles.length); i++) { final File f = pluginFiles[i]; final File descFile = new File(pluginFiles[i], "plugin.xml"); if (pluginFiles[i].isDirectory() && !pluginIgnores.contains(f.getName()) && descFile.exists()) { descSet.add(descFile); } } } parsePlugin(); integrate(); }
public void execute() { if (logger == null) { logger = new DITAOTJavaLogger(); } if (!ditaDir.isAbsolute()) { ditaDir = new File(basedir, ditaDir.getPath()); } // Read the properties file, if it exists. properties = new Properties(); if (propertiesFile != null) { FileInputStream propertiesStream = null; try { propertiesStream = new FileInputStream(propertiesFile); properties.load(propertiesStream); } catch (final Exception e) { logger.logException(e); } finally { if (propertiesStream != null) { try { propertiesStream.close(); } catch (IOException e) { logger.logException(e); } } } } else { // Set reasonable defaults. properties.setProperty("plugindirs", "plugins;demo"); properties.setProperty("plugin.ignores", ""); } // Get the list of plugin directories from the properties. final String[] pluginDirs = properties.getProperty("plugindirs").split(PARAM_VALUE_SEPARATOR); final Set<String> pluginIgnores = new HashSet<String>(); if (properties.getProperty("plugin.ignores") != null) { pluginIgnores.addAll(Arrays.asList(properties.getProperty("plugin.ignores").split(PARAM_VALUE_SEPARATOR))); } for (final String tmpl : properties.getProperty(CONF_TEMPLATES, "").split(PARAM_VALUE_SEPARATOR)) { final String t = tmpl.trim(); if (t.length() != 0) { templateSet.add(t); } } for (final String pluginDir2 : pluginDirs) { File pluginDir = new File(pluginDir2); if (!pluginDir.isAbsolute()) { pluginDir = new File(ditaDir, pluginDir.getPath()); } final File[] pluginFiles = pluginDir.listFiles(); for (int i = 0; (pluginFiles != null) && (i < pluginFiles.length); i++) { final File f = pluginFiles[i]; final File descFile = new File(pluginFiles[i], "plugin.xml"); if (pluginFiles[i].isDirectory() && !pluginIgnores.contains(f.getName()) && descFile.exists()) { descSet.add(descFile); } } } parsePlugin(); integrate(); }
diff --git a/opal-reporting/src/main/java/org/obiba/opal/reporting/service/impl/BasicBirtReportServiceImpl.java b/opal-reporting/src/main/java/org/obiba/opal/reporting/service/impl/BasicBirtReportServiceImpl.java index 737f6f2b2..1a1e0f1d0 100644 --- a/opal-reporting/src/main/java/org/obiba/opal/reporting/service/impl/BasicBirtReportServiceImpl.java +++ b/opal-reporting/src/main/java/org/obiba/opal/reporting/service/impl/BasicBirtReportServiceImpl.java @@ -1,134 +1,134 @@ /******************************************************************************* * Copyright 2008(c) The OBiBa Consortium. All rights reserved. * * This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package org.obiba.opal.reporting.service.impl; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Map; import java.util.Map.Entry; import org.obiba.opal.reporting.service.ReportService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * */ // @Component public class BasicBirtReportServiceImpl implements ReportService { private static final Logger log = LoggerFactory.getLogger(BasicBirtReportServiceImpl.class); final static String OPAL_HOME_SYSTEM_PROPERTY_NAME = "OPAL_HOME"; final static String BIRT_HOME_SYSTEM_PROPERTY_NAME = "BIRT_HOME"; private String birtExec; private boolean running = false; @Override public void render(String format, Map<String, String> parameters, String reportDesign, String reportOutput) { Runtime r = Runtime.getRuntime(); try { Process p = r.exec(getBirtCommandLine(format, parameters, reportDesign, reportOutput)); OutputPurger outputErrorPurger = new OutputPurger(p.getErrorStream()); OutputPurger outputPurger = new OutputPurger(p.getInputStream()); outputErrorPurger.start(); outputPurger.start(); // Check for birt failure try { if(p.waitFor() != 0) { - System.err.println("exit value = " + p.exitValue()); + throw new RuntimeException("BIRT executable reported an error. Exit value = " + p.exitValue()); } } catch(InterruptedException e) { - System.err.println(e); + throw new RuntimeException(e); } } catch(IOException e) { - System.err.println(e.getMessage()); + throw new RuntimeException("BIRT could not be executed.", e); } } private String getBirtCommandLine(String format, Map<String, String> parameters, String reportDesign, String reportOutput) { StringBuffer cmd = new StringBuffer(birtExec); if(format != null) { cmd.append(" -f ").append(format); } if(parameters != null && parameters.size() > 0) { cmd.append(" -p"); for(Entry<String, String> entry : parameters.entrySet()) { cmd.append(" ").append(entry.getKey()).append("=").append(entry.getValue()); } } cmd.append(" -o ").append(reportOutput); cmd.append(" ").append(reportDesign); return cmd.toString(); } @Override public boolean isRunning() { return running; } @Override public void start() { birtExec = System.getProperty(BIRT_HOME_SYSTEM_PROPERTY_NAME) + File.separator + "ReportEngine" + File.separator + "genReport"; if(System.getProperty("os.name").contains("Windows")) { birtExec = "cmd.exe /c " + birtExec; birtExec += ".bat"; } else { birtExec += ".sh"; } log.info("birtExec=" + birtExec); running = true; } @Override public void stop() { running = false; } static class OutputPurger extends Thread { InputStream inputStream; OutputPurger(InputStream pInputStream) { inputStream = pInputStream; } public void run() { try { InputStreamReader isReader = new InputStreamReader(inputStream); BufferedReader bufReader = new BufferedReader(isReader); while(true) { String line = bufReader.readLine(); if(line == null) { break; } } } catch(IOException ex) { } } } }
false
true
public void render(String format, Map<String, String> parameters, String reportDesign, String reportOutput) { Runtime r = Runtime.getRuntime(); try { Process p = r.exec(getBirtCommandLine(format, parameters, reportDesign, reportOutput)); OutputPurger outputErrorPurger = new OutputPurger(p.getErrorStream()); OutputPurger outputPurger = new OutputPurger(p.getInputStream()); outputErrorPurger.start(); outputPurger.start(); // Check for birt failure try { if(p.waitFor() != 0) { System.err.println("exit value = " + p.exitValue()); } } catch(InterruptedException e) { System.err.println(e); } } catch(IOException e) { System.err.println(e.getMessage()); } }
public void render(String format, Map<String, String> parameters, String reportDesign, String reportOutput) { Runtime r = Runtime.getRuntime(); try { Process p = r.exec(getBirtCommandLine(format, parameters, reportDesign, reportOutput)); OutputPurger outputErrorPurger = new OutputPurger(p.getErrorStream()); OutputPurger outputPurger = new OutputPurger(p.getInputStream()); outputErrorPurger.start(); outputPurger.start(); // Check for birt failure try { if(p.waitFor() != 0) { throw new RuntimeException("BIRT executable reported an error. Exit value = " + p.exitValue()); } } catch(InterruptedException e) { throw new RuntimeException(e); } } catch(IOException e) { throw new RuntimeException("BIRT could not be executed.", e); } }
diff --git a/src/main/java/se/tla/mavenversionbumper/Main.java b/src/main/java/se/tla/mavenversionbumper/Main.java index 2091f5e..e469805 100644 --- a/src/main/java/se/tla/mavenversionbumper/Main.java +++ b/src/main/java/se/tla/mavenversionbumper/Main.java @@ -1,332 +1,332 @@ /* * Copyright (c) 2012 Jim Svensson <[email protected]> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ package se.tla.mavenversionbumper; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.TreeSet; import joptsimple.OptionException; import joptsimple.OptionParser; import joptsimple.OptionSet; import org.apache.commons.io.FileUtils; import org.apache.commons.io.input.AutoCloseInputStream; import org.jdom.JDOMException; import se.tla.mavenversionbumper.vcs.AbstractVersionControl; import se.tla.mavenversionbumper.vcs.Clearcase; import se.tla.mavenversionbumper.vcs.Git; import se.tla.mavenversionbumper.vcs.NoopVersionControl; import se.tla.mavenversionbumper.vcs.VersionControl; import bsh.EvalError; import bsh.Interpreter; /** * Command line interface for the version bumper. */ public class Main { private static final List<Module> modulesLoadedForUpdate = new LinkedList<Module>(); private static String baseDirName; private static VersionControl versionControl = new NoopVersionControl(); private static final Map<String, Class<? extends VersionControl>> versionControllers; static { versionControllers = new HashMap<String, Class<? extends VersionControl>>(); // Only lower case names. versionControllers.put("git", Git.class); versionControllers.put("clearcase", Clearcase.class); } enum Option { DRYRUN("Dry run. Don't modify anything, only validate configuration.", "d", "dry-run"), REVERT("Revert any uncommited changes.", "r", "revert"), PREPARETEST("Prepare module(s) for a test build.", "p", "prepare-test-build"), WARNOFSNAPSHOTS("Searches for any SNAPSHOT dependencies and warns about them. Works great with --dry-run.", "w", "warn-snapshots"), REVERSEENGINEER("Build a basic scenario file from a set of modules.", "reverse-engineer"), HELP("Show help.", "h", "?", "help"); private final String helpText; private final String[] aliases; Option(String helpText, String... aliases) { this.helpText = helpText; this.aliases = aliases; } public List<String> getAliases() { return Arrays.asList(aliases); } public String getHelpText() { return helpText; } public boolean presentIn(OptionSet o) { return o.has(aliases[0]); } } enum TYPE { NORMAL, DRYRUN, REVERT, PREPARETEST } public static void main(String args[]) { OptionParser parser = new OptionParser() { { acceptsAll(Option.DRYRUN.getAliases(), Option.DRYRUN.getHelpText()); acceptsAll(Option.PREPARETEST.getAliases(), Option.PREPARETEST.getHelpText()); acceptsAll(Option.REVERT.getAliases(), Option.REVERT.getHelpText()); acceptsAll(Option.WARNOFSNAPSHOTS.getAliases(), Option.WARNOFSNAPSHOTS.getHelpText()); acceptsAll(Option.REVERSEENGINEER.getAliases(), Option.REVERSEENGINEER.getHelpText()); acceptsAll(Option.HELP.getAliases(), Option.HELP.getHelpText()); } }; OptionSet options = null; try { options = parser.parse(args); } catch (OptionException e) { System.err.println(e.getMessage()); System.exit(1); } if (Option.HELP.presentIn(options)) { try { parser.printHelpOn(System.out); } catch (IOException e) { System.err.println("Error printing help text: " + e.getMessage()); System.exit(1); } System.exit(0); } if (countTrues(Option.DRYRUN.presentIn(options), Option.PREPARETEST.presentIn(options), Option.REVERT.presentIn(options), Option.REVERSEENGINEER.presentIn(options)) > 1) { System.err.println("Only one of --dry-run/-d, --prepare-test-build/-p, --revert/-r and --reverse-engineer"); System.exit(1); } List<String> arguments = options.nonOptionArguments(); if (arguments.size() < 2 || arguments.size() > 3) { System.err.println("Usage: [-d | --dry-run] [-p | --prepare-test-build] [-r | --revert] [--reverse-engineer] [-w | --warn-snapshot] [-h | --help] <base directory> <scenarioFile> [<VC properties file>]"); System.exit(1); } baseDirName = arguments.get(0); String scenarioFileName = arguments.get(1); Properties versionControlProperties; if (arguments.size() == 3) { try { String versionControlParameter = arguments.get(2); versionControlProperties = new Properties(); versionControlProperties.load(new AutoCloseInputStream(new FileInputStream(versionControlParameter))); String versionControlName = versionControlProperties.getProperty(AbstractVersionControl.VERSIONCONTROL, "").toLowerCase(); Class<? extends VersionControl> versionControlClass = versionControllers.get(versionControlName); if (versionControlClass == null) { System.err.println("No such version control: " + versionControlName); System.exit(1); } versionControl = versionControlClass.getConstructor(Properties.class).newInstance(versionControlProperties); } catch (Exception e) { System.err.println("Error starting up the version control"); e.printStackTrace(); System.exit(1); } } File scenarioFile = new File(scenarioFileName); if (Option.REVERSEENGINEER.presentIn(options)) { if (scenarioFile.exists()) { System.err.println("Scenario file " + scenarioFileName + " mustn't exist in reverse engineering mode."); System.exit(1); } File baseDir = new File(baseDirName); if (!baseDir.isDirectory()) { System.err.println("Base directory " + baseDirName + " isn't a directory."); System.exit(1); } try { List<ReverseEngineeringModule> modules = findModulesForReverseEngineering(baseDir, ""); reverseEngineerModules(modules, scenarioFile); } catch (JDOMException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return; } if (!(scenarioFile.isFile() && scenarioFile.canRead())) { System.err.println("Scenario file " + scenarioFileName + " isn't a readable file."); System.exit(1); } - if (Option.REVERT.presentIn(options) && versionControl == null) { + if (Option.REVERT.presentIn(options) && versionControl instanceof NoopVersionControl) { System.err.println("Version control has to be defined while reverting."); System.exit(1); } TYPE type = TYPE.NORMAL; if (Option.DRYRUN.presentIn(options)) { type = TYPE.DRYRUN; } if (Option.REVERT.presentIn(options)) { type = TYPE.REVERT; } if (Option.PREPARETEST.presentIn(options)) { type = TYPE.PREPARETEST; } try { String scenario = FileUtils.readFileToString(scenarioFile); Interpreter i = new Interpreter(); i.eval("importCommands(\"se.tla.mavenversionbumper.commands\")"); i.eval("import se.tla.mavenversionbumper.Main"); i.eval("import se.tla.mavenversionbumper.Module"); i.eval("import se.tla.mavenversionbumper.ReadonlyModule"); i.eval("baseDir = \"" + baseDirName + "\""); i.eval("load(String moduleName) { return Main.load(moduleName, null, null); }"); i.eval("load(String moduleName, String newVersion) { return Main.load(moduleName, newVersion, null); }"); i.eval("load(String moduleName, String newVersion, String label) { return Main.load(moduleName, newVersion, label); }"); i.eval("loadReadOnly(String groupId, String artifactId, String version) { return new ReadonlyModule(groupId, artifactId, version); }"); i.eval(scenario); if (Option.WARNOFSNAPSHOTS.presentIn(options)) { for (Module module : modulesLoadedForUpdate) { List<String> result = module.findSnapshots(); if (result.size() > 0) { System.out.println("SNAPSHOTS found in module " + module.gav()); for (String s : result) { System.out.println(" " + s); } } } } if (type.equals(TYPE.NORMAL) || type.equals(TYPE.PREPARETEST)) { versionControl.before(modulesLoadedForUpdate); // Save for (Module module : modulesLoadedForUpdate) { module.save(); } } if (type.equals(TYPE.NORMAL)) { versionControl.commit(modulesLoadedForUpdate); versionControl.label(modulesLoadedForUpdate); versionControl.after(modulesLoadedForUpdate); } if (type.equals(TYPE.REVERT)) { versionControl.restore(modulesLoadedForUpdate); } } catch (EvalError e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private static int countTrues(boolean... bs) { int result = 0; for (boolean b : bs) { if (b) { result++; } } return result; } public static List<ReverseEngineeringModule> findModulesForReverseEngineering(File baseDir, String modulePath) throws JDOMException, IOException { List<ReverseEngineeringModule> result = new LinkedList<ReverseEngineeringModule>(); ReverseEngineeringModule m = new ReverseEngineeringModule(baseDir, modulePath); result.add(m); List<String> subModules = m.subModules(); for (String subModule : subModules) { String subModulePath = (modulePath.isEmpty() ? subModule : modulePath + "/" + subModule); result.addAll(findModulesForReverseEngineering(baseDir, subModulePath)); } return result; } public static void reverseEngineerModules(List<ReverseEngineeringModule> modules, File scenarioFile) throws IOException { StringBuilder builder = new StringBuilder(); for (ReverseEngineeringModule module : modules) { module.consider(modules); } for (ReverseEngineeringModule module : new TreeSet<ReverseEngineeringModule>(modules)) { builder.append(module.toString()); } FileUtils.write(scenarioFile, builder.toString(), "ISO-8859-1"); } /** * Create a Module located by this filename that is a directory relative to the baseDir. * * @param moduleDirectoryName Name of base directory for the module. * @param newVersion New version to set directly, of null if no version should be set. * @param label New label to set directly, or null if no labeling should be performed. * @return Newly created Module. * @throws JDOMException If the modules pom.xml couldn't be parsed. * @throws IOException if the modules pom.xml couldn't be read. */ public static Module load(String moduleDirectoryName, String newVersion, String label) throws JDOMException, IOException { Module m = new Module(baseDirName, moduleDirectoryName); if (newVersion != null) { System.out.println("ORG: " + m.gav()); m.version(newVersion); } if (label != null) { m.label(label); } if (newVersion != null) { System.out.println("NEW: " + m.gav() + (label != null ? " (" + label + ")" : "")); } modulesLoadedForUpdate.add(m); return m; } }
true
true
public static void main(String args[]) { OptionParser parser = new OptionParser() { { acceptsAll(Option.DRYRUN.getAliases(), Option.DRYRUN.getHelpText()); acceptsAll(Option.PREPARETEST.getAliases(), Option.PREPARETEST.getHelpText()); acceptsAll(Option.REVERT.getAliases(), Option.REVERT.getHelpText()); acceptsAll(Option.WARNOFSNAPSHOTS.getAliases(), Option.WARNOFSNAPSHOTS.getHelpText()); acceptsAll(Option.REVERSEENGINEER.getAliases(), Option.REVERSEENGINEER.getHelpText()); acceptsAll(Option.HELP.getAliases(), Option.HELP.getHelpText()); } }; OptionSet options = null; try { options = parser.parse(args); } catch (OptionException e) { System.err.println(e.getMessage()); System.exit(1); } if (Option.HELP.presentIn(options)) { try { parser.printHelpOn(System.out); } catch (IOException e) { System.err.println("Error printing help text: " + e.getMessage()); System.exit(1); } System.exit(0); } if (countTrues(Option.DRYRUN.presentIn(options), Option.PREPARETEST.presentIn(options), Option.REVERT.presentIn(options), Option.REVERSEENGINEER.presentIn(options)) > 1) { System.err.println("Only one of --dry-run/-d, --prepare-test-build/-p, --revert/-r and --reverse-engineer"); System.exit(1); } List<String> arguments = options.nonOptionArguments(); if (arguments.size() < 2 || arguments.size() > 3) { System.err.println("Usage: [-d | --dry-run] [-p | --prepare-test-build] [-r | --revert] [--reverse-engineer] [-w | --warn-snapshot] [-h | --help] <base directory> <scenarioFile> [<VC properties file>]"); System.exit(1); } baseDirName = arguments.get(0); String scenarioFileName = arguments.get(1); Properties versionControlProperties; if (arguments.size() == 3) { try { String versionControlParameter = arguments.get(2); versionControlProperties = new Properties(); versionControlProperties.load(new AutoCloseInputStream(new FileInputStream(versionControlParameter))); String versionControlName = versionControlProperties.getProperty(AbstractVersionControl.VERSIONCONTROL, "").toLowerCase(); Class<? extends VersionControl> versionControlClass = versionControllers.get(versionControlName); if (versionControlClass == null) { System.err.println("No such version control: " + versionControlName); System.exit(1); } versionControl = versionControlClass.getConstructor(Properties.class).newInstance(versionControlProperties); } catch (Exception e) { System.err.println("Error starting up the version control"); e.printStackTrace(); System.exit(1); } } File scenarioFile = new File(scenarioFileName); if (Option.REVERSEENGINEER.presentIn(options)) { if (scenarioFile.exists()) { System.err.println("Scenario file " + scenarioFileName + " mustn't exist in reverse engineering mode."); System.exit(1); } File baseDir = new File(baseDirName); if (!baseDir.isDirectory()) { System.err.println("Base directory " + baseDirName + " isn't a directory."); System.exit(1); } try { List<ReverseEngineeringModule> modules = findModulesForReverseEngineering(baseDir, ""); reverseEngineerModules(modules, scenarioFile); } catch (JDOMException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return; } if (!(scenarioFile.isFile() && scenarioFile.canRead())) { System.err.println("Scenario file " + scenarioFileName + " isn't a readable file."); System.exit(1); } if (Option.REVERT.presentIn(options) && versionControl == null) { System.err.println("Version control has to be defined while reverting."); System.exit(1); } TYPE type = TYPE.NORMAL; if (Option.DRYRUN.presentIn(options)) { type = TYPE.DRYRUN; } if (Option.REVERT.presentIn(options)) { type = TYPE.REVERT; } if (Option.PREPARETEST.presentIn(options)) { type = TYPE.PREPARETEST; } try { String scenario = FileUtils.readFileToString(scenarioFile); Interpreter i = new Interpreter(); i.eval("importCommands(\"se.tla.mavenversionbumper.commands\")"); i.eval("import se.tla.mavenversionbumper.Main"); i.eval("import se.tla.mavenversionbumper.Module"); i.eval("import se.tla.mavenversionbumper.ReadonlyModule"); i.eval("baseDir = \"" + baseDirName + "\""); i.eval("load(String moduleName) { return Main.load(moduleName, null, null); }"); i.eval("load(String moduleName, String newVersion) { return Main.load(moduleName, newVersion, null); }"); i.eval("load(String moduleName, String newVersion, String label) { return Main.load(moduleName, newVersion, label); }"); i.eval("loadReadOnly(String groupId, String artifactId, String version) { return new ReadonlyModule(groupId, artifactId, version); }"); i.eval(scenario); if (Option.WARNOFSNAPSHOTS.presentIn(options)) { for (Module module : modulesLoadedForUpdate) { List<String> result = module.findSnapshots(); if (result.size() > 0) { System.out.println("SNAPSHOTS found in module " + module.gav()); for (String s : result) { System.out.println(" " + s); } } } } if (type.equals(TYPE.NORMAL) || type.equals(TYPE.PREPARETEST)) { versionControl.before(modulesLoadedForUpdate); // Save for (Module module : modulesLoadedForUpdate) { module.save(); } } if (type.equals(TYPE.NORMAL)) { versionControl.commit(modulesLoadedForUpdate); versionControl.label(modulesLoadedForUpdate); versionControl.after(modulesLoadedForUpdate); } if (type.equals(TYPE.REVERT)) { versionControl.restore(modulesLoadedForUpdate); } } catch (EvalError e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
public static void main(String args[]) { OptionParser parser = new OptionParser() { { acceptsAll(Option.DRYRUN.getAliases(), Option.DRYRUN.getHelpText()); acceptsAll(Option.PREPARETEST.getAliases(), Option.PREPARETEST.getHelpText()); acceptsAll(Option.REVERT.getAliases(), Option.REVERT.getHelpText()); acceptsAll(Option.WARNOFSNAPSHOTS.getAliases(), Option.WARNOFSNAPSHOTS.getHelpText()); acceptsAll(Option.REVERSEENGINEER.getAliases(), Option.REVERSEENGINEER.getHelpText()); acceptsAll(Option.HELP.getAliases(), Option.HELP.getHelpText()); } }; OptionSet options = null; try { options = parser.parse(args); } catch (OptionException e) { System.err.println(e.getMessage()); System.exit(1); } if (Option.HELP.presentIn(options)) { try { parser.printHelpOn(System.out); } catch (IOException e) { System.err.println("Error printing help text: " + e.getMessage()); System.exit(1); } System.exit(0); } if (countTrues(Option.DRYRUN.presentIn(options), Option.PREPARETEST.presentIn(options), Option.REVERT.presentIn(options), Option.REVERSEENGINEER.presentIn(options)) > 1) { System.err.println("Only one of --dry-run/-d, --prepare-test-build/-p, --revert/-r and --reverse-engineer"); System.exit(1); } List<String> arguments = options.nonOptionArguments(); if (arguments.size() < 2 || arguments.size() > 3) { System.err.println("Usage: [-d | --dry-run] [-p | --prepare-test-build] [-r | --revert] [--reverse-engineer] [-w | --warn-snapshot] [-h | --help] <base directory> <scenarioFile> [<VC properties file>]"); System.exit(1); } baseDirName = arguments.get(0); String scenarioFileName = arguments.get(1); Properties versionControlProperties; if (arguments.size() == 3) { try { String versionControlParameter = arguments.get(2); versionControlProperties = new Properties(); versionControlProperties.load(new AutoCloseInputStream(new FileInputStream(versionControlParameter))); String versionControlName = versionControlProperties.getProperty(AbstractVersionControl.VERSIONCONTROL, "").toLowerCase(); Class<? extends VersionControl> versionControlClass = versionControllers.get(versionControlName); if (versionControlClass == null) { System.err.println("No such version control: " + versionControlName); System.exit(1); } versionControl = versionControlClass.getConstructor(Properties.class).newInstance(versionControlProperties); } catch (Exception e) { System.err.println("Error starting up the version control"); e.printStackTrace(); System.exit(1); } } File scenarioFile = new File(scenarioFileName); if (Option.REVERSEENGINEER.presentIn(options)) { if (scenarioFile.exists()) { System.err.println("Scenario file " + scenarioFileName + " mustn't exist in reverse engineering mode."); System.exit(1); } File baseDir = new File(baseDirName); if (!baseDir.isDirectory()) { System.err.println("Base directory " + baseDirName + " isn't a directory."); System.exit(1); } try { List<ReverseEngineeringModule> modules = findModulesForReverseEngineering(baseDir, ""); reverseEngineerModules(modules, scenarioFile); } catch (JDOMException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return; } if (!(scenarioFile.isFile() && scenarioFile.canRead())) { System.err.println("Scenario file " + scenarioFileName + " isn't a readable file."); System.exit(1); } if (Option.REVERT.presentIn(options) && versionControl instanceof NoopVersionControl) { System.err.println("Version control has to be defined while reverting."); System.exit(1); } TYPE type = TYPE.NORMAL; if (Option.DRYRUN.presentIn(options)) { type = TYPE.DRYRUN; } if (Option.REVERT.presentIn(options)) { type = TYPE.REVERT; } if (Option.PREPARETEST.presentIn(options)) { type = TYPE.PREPARETEST; } try { String scenario = FileUtils.readFileToString(scenarioFile); Interpreter i = new Interpreter(); i.eval("importCommands(\"se.tla.mavenversionbumper.commands\")"); i.eval("import se.tla.mavenversionbumper.Main"); i.eval("import se.tla.mavenversionbumper.Module"); i.eval("import se.tla.mavenversionbumper.ReadonlyModule"); i.eval("baseDir = \"" + baseDirName + "\""); i.eval("load(String moduleName) { return Main.load(moduleName, null, null); }"); i.eval("load(String moduleName, String newVersion) { return Main.load(moduleName, newVersion, null); }"); i.eval("load(String moduleName, String newVersion, String label) { return Main.load(moduleName, newVersion, label); }"); i.eval("loadReadOnly(String groupId, String artifactId, String version) { return new ReadonlyModule(groupId, artifactId, version); }"); i.eval(scenario); if (Option.WARNOFSNAPSHOTS.presentIn(options)) { for (Module module : modulesLoadedForUpdate) { List<String> result = module.findSnapshots(); if (result.size() > 0) { System.out.println("SNAPSHOTS found in module " + module.gav()); for (String s : result) { System.out.println(" " + s); } } } } if (type.equals(TYPE.NORMAL) || type.equals(TYPE.PREPARETEST)) { versionControl.before(modulesLoadedForUpdate); // Save for (Module module : modulesLoadedForUpdate) { module.save(); } } if (type.equals(TYPE.NORMAL)) { versionControl.commit(modulesLoadedForUpdate); versionControl.label(modulesLoadedForUpdate); versionControl.after(modulesLoadedForUpdate); } if (type.equals(TYPE.REVERT)) { versionControl.restore(modulesLoadedForUpdate); } } catch (EvalError e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
diff --git a/src/jvm/clojure/lang/PersistentVector.java b/src/jvm/clojure/lang/PersistentVector.java index b842fc43..460a4069 100644 --- a/src/jvm/clojure/lang/PersistentVector.java +++ b/src/jvm/clojure/lang/PersistentVector.java @@ -1,748 +1,748 @@ /** * Copyright (c) Rich Hickey. All rights reserved. * The use and distribution terms for this software are covered by the * Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) * which can be found in the file epl-v10.html at the root of this distribution. * By using this software in any fashion, you are agreeing to be bound by * the terms of this license. * You must not remove this notice, or any other, from this software. **/ /* rich Jul 5, 2007 */ package clojure.lang; import java.io.Serializable; import java.util.List; import java.util.concurrent.atomic.AtomicReference; public class PersistentVector extends APersistentVector implements IObj, IEditableCollection{ static class Node implements Serializable { transient final AtomicReference<Thread> edit; final Object[] array; Node(AtomicReference<Thread> edit, Object[] array){ this.edit = edit; this.array = array; } Node(AtomicReference<Thread> edit){ this.edit = edit; this.array = new Object[32]; } } final static AtomicReference<Thread> NOEDIT = new AtomicReference<Thread>(null); final static Node EMPTY_NODE = new Node(NOEDIT, new Object[32]); final int cnt; final int shift; final Node root; final Object[] tail; final IPersistentMap _meta; public final static PersistentVector EMPTY = new PersistentVector(0, 5, EMPTY_NODE, new Object[]{}); static public PersistentVector create(ISeq items){ TransientVector ret = EMPTY.asTransient(); for(; items != null; items = items.next()) ret = ret.conj(items.first()); return ret.persistent(); } static public PersistentVector create(List items){ TransientVector ret = EMPTY.asTransient(); for(Object item : items) ret = ret.conj(item); return ret.persistent(); } static public PersistentVector create(Object... items){ TransientVector ret = EMPTY.asTransient(); for(Object item : items) ret = ret.conj(item); return ret.persistent(); } PersistentVector(int cnt, int shift, Node root, Object[] tail){ this._meta = null; this.cnt = cnt; this.shift = shift; this.root = root; this.tail = tail; } PersistentVector(IPersistentMap meta, int cnt, int shift, Node root, Object[] tail){ this._meta = meta; this.cnt = cnt; this.shift = shift; this.root = root; this.tail = tail; } public TransientVector asTransient(){ return new TransientVector(this); } final int tailoff(){ if(cnt < 32) return 0; return ((cnt - 1) >>> 5) << 5; } public Object[] arrayFor(int i){ if(i >= 0 && i < cnt) { if(i >= tailoff()) return tail; Node node = root; for(int level = shift; level > 0; level -= 5) node = (Node) node.array[(i >>> level) & 0x01f]; return node.array; } throw new IndexOutOfBoundsException(); } public Object nth(int i){ Object[] node = arrayFor(i); return node[i & 0x01f]; } public Object nth(int i, Object notFound){ if(i >= 0 && i < cnt) return nth(i); return notFound; } public PersistentVector assocN(int i, Object val){ if(i >= 0 && i < cnt) { if(i >= tailoff()) { Object[] newTail = new Object[tail.length]; System.arraycopy(tail, 0, newTail, 0, tail.length); newTail[i & 0x01f] = val; return new PersistentVector(meta(), cnt, shift, root, newTail); } return new PersistentVector(meta(), cnt, shift, doAssoc(shift, root, i, val), tail); } if(i == cnt) return cons(val); throw new IndexOutOfBoundsException(); } private static Node doAssoc(int level, Node node, int i, Object val){ Node ret = new Node(node.edit,node.array.clone()); if(level == 0) { ret.array[i & 0x01f] = val; } else { int subidx = (i >>> level) & 0x01f; ret.array[subidx] = doAssoc(level - 5, (Node) node.array[subidx], i, val); } return ret; } public int count(){ return cnt; } public PersistentVector withMeta(IPersistentMap meta){ return new PersistentVector(meta, cnt, shift, root, tail); } public IPersistentMap meta(){ return _meta; } public PersistentVector cons(Object val){ int i = cnt; //room in tail? // if(tail.length < 32) if(cnt - tailoff() < 32) { Object[] newTail = new Object[tail.length + 1]; System.arraycopy(tail, 0, newTail, 0, tail.length); newTail[tail.length] = val; return new PersistentVector(meta(), cnt + 1, shift, root, newTail); } //full tail, push into tree Node newroot; Node tailnode = new Node(root.edit,tail); int newshift = shift; //overflow root? if((cnt >>> 5) > (1 << shift)) { newroot = new Node(root.edit); newroot.array[0] = root; newroot.array[1] = newPath(root.edit,shift, tailnode); newshift += 5; } else newroot = pushTail(shift, root, tailnode); return new PersistentVector(meta(), cnt + 1, newshift, newroot, new Object[]{val}); } private Node pushTail(int level, Node parent, Node tailnode){ //if parent is leaf, insert node, // else does it map to an existing child? -> nodeToInsert = pushNode one more level // else alloc new path //return nodeToInsert placed in copy of parent int subidx = ((cnt - 1) >>> level) & 0x01f; Node ret = new Node(parent.edit, parent.array.clone()); Node nodeToInsert; if(level == 5) { nodeToInsert = tailnode; } else { Node child = (Node) parent.array[subidx]; nodeToInsert = (child != null)? pushTail(level-5,child, tailnode) :newPath(root.edit,level-5, tailnode); } ret.array[subidx] = nodeToInsert; return ret; } private static Node newPath(AtomicReference<Thread> edit,int level, Node node){ if(level == 0) return node; Node ret = new Node(edit); ret.array[0] = newPath(edit, level - 5, node); return ret; } public IChunkedSeq chunkedSeq(){ if(count() == 0) return null; return new ChunkedSeq(this,0,0); } public ISeq seq(){ return chunkedSeq(); } static public final class ChunkedSeq extends ASeq implements IChunkedSeq{ public final PersistentVector vec; final Object[] node; final int i; public final int offset; public ChunkedSeq(PersistentVector vec, int i, int offset){ this.vec = vec; this.i = i; this.offset = offset; this.node = vec.arrayFor(i); } ChunkedSeq(IPersistentMap meta, PersistentVector vec, Object[] node, int i, int offset){ super(meta); this.vec = vec; this.node = node; this.i = i; this.offset = offset; } ChunkedSeq(PersistentVector vec, Object[] node, int i, int offset){ this.vec = vec; this.node = node; this.i = i; this.offset = offset; } public IChunk chunkedFirst() throws Exception{ return new ArrayChunk(node, offset); } public ISeq chunkedNext(){ if(i + node.length < vec.cnt) return new ChunkedSeq(vec,i+ node.length,0); return null; } public ISeq chunkedMore(){ ISeq s = chunkedNext(); if(s == null) return PersistentList.EMPTY; return s; } public Obj withMeta(IPersistentMap meta){ if(meta == this._meta) return this; return new ChunkedSeq(meta, vec, node, i, offset); } public Object first(){ return node[offset]; } public ISeq next(){ if(offset + 1 < node.length) return new ChunkedSeq(vec, node, i, offset + 1); return chunkedNext(); } } public IPersistentCollection empty(){ return EMPTY.withMeta(meta()); } //private Node pushTail(int level, Node node, Object[] tailNode, Box expansion){ // Object newchild; // if(level == 0) // { // newchild = tailNode; // } // else // { // newchild = pushTail(level - 5, (Object[]) arr[arr.length - 1], tailNode, expansion); // if(expansion.val == null) // { // Object[] ret = arr.clone(); // ret[arr.length - 1] = newchild; // return ret; // } // else // newchild = expansion.val; // } // //expansion // if(arr.length == 32) // { // expansion.val = new Object[]{newchild}; // return arr; // } // Object[] ret = new Object[arr.length + 1]; // System.arraycopy(arr, 0, ret, 0, arr.length); // ret[arr.length] = newchild; // expansion.val = null; // return ret; //} public PersistentVector pop(){ if(cnt == 0) throw new IllegalStateException("Can't pop empty vector"); if(cnt == 1) return EMPTY.withMeta(meta()); //if(tail.length > 1) if(cnt-tailoff() > 1) { Object[] newTail = new Object[tail.length - 1]; System.arraycopy(tail, 0, newTail, 0, newTail.length); return new PersistentVector(meta(), cnt - 1, shift, root, newTail); } Object[] newtail = arrayFor(cnt - 2); Node newroot = popTail(shift, root); int newshift = shift; if(newroot == null) { newroot = EMPTY_NODE; } if(shift > 5 && newroot.array[1] == null) { newroot = (Node) newroot.array[0]; newshift -= 5; } return new PersistentVector(meta(), cnt - 1, newshift, newroot, newtail); } private Node popTail(int level, Node node){ int subidx = ((cnt-2) >>> level) & 0x01f; if(level > 5) { Node newchild = popTail(level - 5, (Node) node.array[subidx]); if(newchild == null && subidx == 0) return null; else { Node ret = new Node(root.edit, node.array.clone()); ret.array[subidx] = newchild; return ret; } } else if(subidx == 0) return null; else { Node ret = new Node(root.edit, node.array.clone()); ret.array[subidx] = null; return ret; } } static final class TransientVector extends AFn implements ITransientVector, Counted{ int cnt; int shift; Node root; Object[] tail; TransientVector(int cnt, int shift, Node root, Object[] tail){ this.cnt = cnt; this.shift = shift; this.root = root; this.tail = tail; } TransientVector(PersistentVector v){ this(v.cnt, v.shift, editableRoot(v.root), editableTail(v.tail)); } public int count(){ ensureEditable(); return cnt; } Node ensureEditable(Node node){ if(node.edit == root.edit) return node; return new Node(root.edit, node.array.clone()); } void ensureEditable(){ Thread owner = root.edit.get(); if(owner == Thread.currentThread()) return; if(owner != null) throw new IllegalAccessError("Transient used by non-owner thread"); throw new IllegalAccessError("Transient used after persistent! call"); // root = editableRoot(root); // tail = editableTail(tail); } static Node editableRoot(Node node){ return new Node(new AtomicReference<Thread>(Thread.currentThread()), node.array.clone()); } public PersistentVector persistent(){ ensureEditable(); // Thread owner = root.edit.get(); // if(owner != null && owner != Thread.currentThread()) // { // throw new IllegalAccessError("Mutation release by non-owner thread"); // } root.edit.set(null); Object[] trimmedTail = new Object[cnt-tailoff()]; System.arraycopy(tail,0,trimmedTail,0,trimmedTail.length); return new PersistentVector(cnt, shift, root, trimmedTail); } static Object[] editableTail(Object[] tl){ Object[] ret = new Object[32]; System.arraycopy(tl,0,ret,0,tl.length); return ret; } public TransientVector conj(Object val){ ensureEditable(); int i = cnt; //room in tail? if(i - tailoff() < 32) { tail[i & 0x01f] = val; ++cnt; return this; } //full tail, push into tree Node newroot; Node tailnode = new Node(root.edit, tail); tail = new Object[32]; tail[0] = val; int newshift = shift; //overflow root? if((cnt >>> 5) > (1 << shift)) { newroot = new Node(root.edit); newroot.array[0] = root; newroot.array[1] = newPath(root.edit,shift, tailnode); newshift += 5; } else newroot = pushTail(shift, root, tailnode); root = newroot; shift = newshift; ++cnt; return this; } private Node pushTail(int level, Node parent, Node tailnode){ //if parent is leaf, insert node, // else does it map to an existing child? -> nodeToInsert = pushNode one more level // else alloc new path //return nodeToInsert placed in parent parent = ensureEditable(parent); int subidx = ((cnt - 1) >>> level) & 0x01f; Node ret = parent; Node nodeToInsert; if(level == 5) { nodeToInsert = tailnode; } else { Node child = (Node) parent.array[subidx]; nodeToInsert = (child != null) ? pushTail(level - 5, child, tailnode) : newPath(root.edit, level - 5, tailnode); } ret.array[subidx] = nodeToInsert; return ret; } final private int tailoff(){ if(cnt < 32) return 0; return ((cnt-1) >>> 5) << 5; } private Object[] arrayFor(int i){ if(i >= 0 && i < cnt) { if(i >= tailoff()) return tail; Node node = root; for(int level = shift; level > 0; level -= 5) node = (Node) node.array[(i >>> level) & 0x01f]; return node.array; } throw new IndexOutOfBoundsException(); } public Object valAt(Object key){ //note - relies on ensureEditable in 2-arg valAt return valAt(key, null); } public Object valAt(Object key, Object notFound){ ensureEditable(); if(Util.isInteger(key)) { int i = ((Number) key).intValue(); if(i >= 0 && i < cnt) return nth(i); } return notFound; } public Object invoke(Object arg1) throws Exception{ //note - relies on ensureEditable in nth if(Util.isInteger(arg1)) return nth(((Number) arg1).intValue()); throw new IllegalArgumentException("Key must be integer"); } public Object nth(int i){ ensureEditable(); Object[] node = arrayFor(i); return node[i & 0x01f]; } public Object nth(int i, Object notFound){ if(i >= 0 && i < count()) return nth(i); return notFound; } public TransientVector assocN(int i, Object val){ ensureEditable(); if(i >= 0 && i < cnt) { if(i >= tailoff()) { tail[i & 0x01f] = val; return this; } root = doAssoc(shift, root, i, val); return this; } if(i == cnt) return conj(val); throw new IndexOutOfBoundsException(); } public TransientVector assoc(Object key, Object val){ //note - relies on ensureEditable in assocN if(Util.isInteger(key)) { int i = ((Number) key).intValue(); return assocN(i, val); } throw new IllegalArgumentException("Key must be integer"); } private Node doAssoc(int level, Node node, int i, Object val){ node = ensureEditable(node); Node ret = node; if(level == 0) { ret.array[i & 0x01f] = val; } else { int subidx = (i >>> level) & 0x01f; ret.array[subidx] = doAssoc(level - 5, (Node) node.array[subidx], i, val); } return ret; } public TransientVector pop(){ ensureEditable(); if(cnt == 0) throw new IllegalStateException("Can't pop empty vector"); if(cnt == 1) { cnt = 0; return this; } int i = cnt - 1; //pop in tail? if((i & 0x01f) > 0) { --cnt; return this; } Object[] newtail = arrayFor(cnt - 2); Node newroot = popTail(shift, root); int newshift = shift; if(newroot == null) { newroot = new Node(root.edit); } if(shift > 5 && newroot.array[1] == null) { - newroot = (Node) newroot.array[0]; + newroot = ensureEditable((Node) newroot.array[0]); newshift -= 5; } root = newroot; shift = newshift; --cnt; tail = newtail; return this; } private Node popTail(int level, Node node){ node = ensureEditable(node); int subidx = ((cnt - 2) >>> level) & 0x01f; if(level > 5) { Node newchild = popTail(level - 5, (Node) node.array[subidx]); if(newchild == null && subidx == 0) return null; else { Node ret = node; ret.array[subidx] = newchild; return ret; } } else if(subidx == 0) return null; else { Node ret = node; ret.array[subidx] = null; return ret; } } } /* static public void main(String[] args){ if(args.length != 3) { System.err.println("Usage: PersistentVector size writes reads"); return; } int size = Integer.parseInt(args[0]); int writes = Integer.parseInt(args[1]); int reads = Integer.parseInt(args[2]); // Vector v = new Vector(size); ArrayList v = new ArrayList(size); // v.setSize(size); //PersistentArray p = new PersistentArray(size); PersistentVector p = PersistentVector.EMPTY; // MutableVector mp = p.mutable(); for(int i = 0; i < size; i++) { v.add(i); // v.set(i, i); //p = p.set(i, 0); p = p.cons(i); // mp = mp.conj(i); } Random rand; rand = new Random(42); long tv = 0; System.out.println("ArrayList"); long startTime = System.nanoTime(); for(int i = 0; i < writes; i++) { v.set(rand.nextInt(size), i); } for(int i = 0; i < reads; i++) { tv += (Integer) v.get(rand.nextInt(size)); } long estimatedTime = System.nanoTime() - startTime; System.out.println("time: " + estimatedTime / 1000000); System.out.println("PersistentVector"); rand = new Random(42); startTime = System.nanoTime(); long tp = 0; // PersistentVector oldp = p; //Random rand2 = new Random(42); MutableVector mp = p.mutable(); for(int i = 0; i < writes; i++) { // p = p.assocN(rand.nextInt(size), i); mp = mp.assocN(rand.nextInt(size), i); // mp = mp.assoc(rand.nextInt(size), i); //dummy set to force perverse branching //oldp = oldp.assocN(rand2.nextInt(size), i); } for(int i = 0; i < reads; i++) { // tp += (Integer) p.nth(rand.nextInt(size)); tp += (Integer) mp.nth(rand.nextInt(size)); } // p = mp.immutable(); //mp.cons(42); estimatedTime = System.nanoTime() - startTime; System.out.println("time: " + estimatedTime / 1000000); for(int i = 0; i < size / 2; i++) { mp = mp.pop(); // p = p.pop(); v.remove(v.size() - 1); } p = (PersistentVector) mp.immutable(); //mp.pop(); //should fail for(int i = 0; i < size / 2; i++) { tp += (Integer) p.nth(i); tv += (Integer) v.get(i); } System.out.println("Done: " + tv + ", " + tp); } // */ }
true
true
public TransientVector pop(){ ensureEditable(); if(cnt == 0) throw new IllegalStateException("Can't pop empty vector"); if(cnt == 1) { cnt = 0; return this; } int i = cnt - 1; //pop in tail? if((i & 0x01f) > 0) { --cnt; return this; } Object[] newtail = arrayFor(cnt - 2); Node newroot = popTail(shift, root); int newshift = shift; if(newroot == null) { newroot = new Node(root.edit); } if(shift > 5 && newroot.array[1] == null) { newroot = (Node) newroot.array[0]; newshift -= 5; } root = newroot; shift = newshift; --cnt; tail = newtail; return this; }
public TransientVector pop(){ ensureEditable(); if(cnt == 0) throw new IllegalStateException("Can't pop empty vector"); if(cnt == 1) { cnt = 0; return this; } int i = cnt - 1; //pop in tail? if((i & 0x01f) > 0) { --cnt; return this; } Object[] newtail = arrayFor(cnt - 2); Node newroot = popTail(shift, root); int newshift = shift; if(newroot == null) { newroot = new Node(root.edit); } if(shift > 5 && newroot.array[1] == null) { newroot = ensureEditable((Node) newroot.array[0]); newshift -= 5; } root = newroot; shift = newshift; --cnt; tail = newtail; return this; }
diff --git a/src/main/org/jboss/seam/log/LogImpl.java b/src/main/org/jboss/seam/log/LogImpl.java index 0bbb078b..3b7870fd 100644 --- a/src/main/org/jboss/seam/log/LogImpl.java +++ b/src/main/org/jboss/seam/log/LogImpl.java @@ -1,175 +1,175 @@ package org.jboss.seam.log; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import org.jboss.seam.core.Interpolator; /** * Implementation of the Log interface using commons logging. * * @author Gavin King */ class LogImpl implements Log, Externalizable { private static final long serialVersionUID = -1664298172030714342L; private transient LogProvider log; private String category; public LogImpl() {} //for Externalizable LogImpl(String category) { this.category = category; this.log = Logging.getLogProvider(category, true); } public boolean isDebugEnabled() { return log.isDebugEnabled(); } public boolean isErrorEnabled() { return log.isErrorEnabled(); } public boolean isFatalEnabled() { return log.isFatalEnabled(); } public boolean isInfoEnabled() { return log.isInfoEnabled(); } public boolean isTraceEnabled() { return log.isTraceEnabled(); } public boolean isWarnEnabled() { return log.isWarnEnabled(); } public void trace(Object object, Object... params) { if ( isTraceEnabled() ) { log.trace( interpolate(object, params) ); } } public void trace(Object object, Throwable t, Object... params) { if ( isTraceEnabled() ) { log.trace( interpolate(object, params), t ); } } public void debug(Object object, Object... params) { if ( isDebugEnabled() ) { log.debug( interpolate(object, params) ); } } public void debug(Object object, Throwable t, Object... params) { if ( isDebugEnabled() ) { log.debug( interpolate(object, params), t ); } } public void info(Object object, Object... params) { if ( isInfoEnabled() ) { log.info( interpolate(object, params) ); } } public void info(Object object, Throwable t, Object... params) { if ( isInfoEnabled() ) { log.info( interpolate(object, params), t ); } } public void warn(Object object, Object... params) { if ( isWarnEnabled() ) { log.warn( interpolate(object, params) ); } } public void warn(Object object, Throwable t, Object... params) { if ( isWarnEnabled() ) { log.warn( interpolate(object, params), t ); } } public void error(Object object, Object... params) { if ( isErrorEnabled() ) { log.error( interpolate(object, params) ); } } public void error(Object object, Throwable t, Object... params) { if ( isErrorEnabled() ) { log.error( interpolate(object, params), t ); } } public void fatal(Object object, Object... params) { if ( isFatalEnabled() ) { log.fatal( interpolate(object, params) ); } } public void fatal(Object object, Throwable t, Object... params) { if ( isFatalEnabled() ) { log.fatal( interpolate(object, params), t ); } } private Object interpolate(Object object, Object... params) { if (object instanceof String) { try { - return Interpolator.instance().interpolate( (String) object, params ); + object = Interpolator.instance().interpolate( (String) object, params ); } catch (Exception e) { log.error("exception interpolating string: " + object, e); } finally { return object; } } else { return object; } } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { category = (String) in.readObject(); log = Logging.getLogProvider(category, true); } public void writeExternal(ObjectOutput out) throws IOException { out.writeObject(category); } /*void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException { ois.defaultReadObject(); log = LogFactory.getLog(category); }*/ }
true
true
private Object interpolate(Object object, Object... params) { if (object instanceof String) { try { return Interpolator.instance().interpolate( (String) object, params ); } catch (Exception e) { log.error("exception interpolating string: " + object, e); } finally { return object; } } else { return object; } }
private Object interpolate(Object object, Object... params) { if (object instanceof String) { try { object = Interpolator.instance().interpolate( (String) object, params ); } catch (Exception e) { log.error("exception interpolating string: " + object, e); } finally { return object; } } else { return object; } }
diff --git a/src/tng/Main.java b/src/tng/Main.java index 55d7ee5..64208c2 100644 --- a/src/tng/Main.java +++ b/src/tng/Main.java @@ -1,67 +1,67 @@ package tng; import java.io.File; import java.util.List; import models.Method; import models.Pair; import git.GitController; import db.DatabaseConnector; import ast.CallGraphGenerator; import ast.FolderTraversar; public class Main { public static void main(String[] args) { System.out.println("TNG developed by eggnet."); System.out.println(); try { if (args.length < 4 ) { System.out.println("Retry: TNG [dbname] [repository] [branch] [configFile] <commitFile> <port>"); throw new ArrayIndexOutOfBoundsException(); } else { try { // Set up the resources Resources.dbName = args[0]; Resources.repository = args[1]; Resources.branch = args[2]; Resources.configFile = args[3]; setRepositoryName(args[1]); // Set up custom port number - if(args.length == 6) { + if(args.length >= 6) { Resources.dbPort = args[5]; } Resources.dbUrl = Resources.dbUrl + Resources.dbPort + "/"; System.out.println(Resources.dbUrl); DatabaseConnector db = new DatabaseConnector(); db.connect("eggnet"); db.createDatabase(Resources.dbName); NetworkBuilder nb = new NetworkBuilder(db); - if(args.length == 5) + if(args.length >= 5) nb.buildNetworksFromCommitFile(args[4]); else nb.buildAllNetworksNoUpdate(); db.close(); } catch (Exception e) { e.printStackTrace(); } } } catch (ArrayIndexOutOfBoundsException e) { e.printStackTrace(); } } private static void setRepositoryName(String path) { Resources.repositoryName = path.substring(path.lastIndexOf("/")+1); } }
false
true
public static void main(String[] args) { System.out.println("TNG developed by eggnet."); System.out.println(); try { if (args.length < 4 ) { System.out.println("Retry: TNG [dbname] [repository] [branch] [configFile] <commitFile> <port>"); throw new ArrayIndexOutOfBoundsException(); } else { try { // Set up the resources Resources.dbName = args[0]; Resources.repository = args[1]; Resources.branch = args[2]; Resources.configFile = args[3]; setRepositoryName(args[1]); // Set up custom port number if(args.length == 6) { Resources.dbPort = args[5]; } Resources.dbUrl = Resources.dbUrl + Resources.dbPort + "/"; System.out.println(Resources.dbUrl); DatabaseConnector db = new DatabaseConnector(); db.connect("eggnet"); db.createDatabase(Resources.dbName); NetworkBuilder nb = new NetworkBuilder(db); if(args.length == 5) nb.buildNetworksFromCommitFile(args[4]); else nb.buildAllNetworksNoUpdate(); db.close(); } catch (Exception e) { e.printStackTrace(); } } } catch (ArrayIndexOutOfBoundsException e) { e.printStackTrace(); } }
public static void main(String[] args) { System.out.println("TNG developed by eggnet."); System.out.println(); try { if (args.length < 4 ) { System.out.println("Retry: TNG [dbname] [repository] [branch] [configFile] <commitFile> <port>"); throw new ArrayIndexOutOfBoundsException(); } else { try { // Set up the resources Resources.dbName = args[0]; Resources.repository = args[1]; Resources.branch = args[2]; Resources.configFile = args[3]; setRepositoryName(args[1]); // Set up custom port number if(args.length >= 6) { Resources.dbPort = args[5]; } Resources.dbUrl = Resources.dbUrl + Resources.dbPort + "/"; System.out.println(Resources.dbUrl); DatabaseConnector db = new DatabaseConnector(); db.connect("eggnet"); db.createDatabase(Resources.dbName); NetworkBuilder nb = new NetworkBuilder(db); if(args.length >= 5) nb.buildNetworksFromCommitFile(args[4]); else nb.buildAllNetworksNoUpdate(); db.close(); } catch (Exception e) { e.printStackTrace(); } } } catch (ArrayIndexOutOfBoundsException e) { e.printStackTrace(); } }
diff --git a/src/com/android/settings/cyanogenmod/AutoBrightnessCustomizeDialog.java b/src/com/android/settings/cyanogenmod/AutoBrightnessCustomizeDialog.java index 3f93afc..f9b6e19 100644 --- a/src/com/android/settings/cyanogenmod/AutoBrightnessCustomizeDialog.java +++ b/src/com/android/settings/cyanogenmod/AutoBrightnessCustomizeDialog.java @@ -1,565 +1,565 @@ package com.android.settings.cyanogenmod; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.res.Resources; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.Bundle; import android.os.PowerManager; import android.provider.Settings; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.ContextMenu; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.SeekBar; import android.widget.TextView; import java.util.ArrayList; import com.android.settings.R; public class AutoBrightnessCustomizeDialog extends AlertDialog implements DialogInterface.OnClickListener { private static final String TAG = "AutoBrightnessCustomizeDialog"; private TextView mSensorLevel; private TextView mBrightnessLevel; private ListView mConfigList; private SensorManager mSensorManager; private Sensor mLightSensor; private static class SettingRow { int luxFrom; int luxTo; int backlight; public SettingRow(int luxFrom, int luxTo, int backlight) { this.luxFrom = luxFrom; this.luxTo = luxTo; this.backlight = backlight; } }; private SettingRowAdapter mAdapter; private int mMinLevel; private boolean mIsDefault; private SensorEventListener mLightSensorListener = new SensorEventListener() { @Override public void onSensorChanged(SensorEvent event) { final int lux = Math.round(event.values[0]); mSensorLevel.setText(getContext().getString(R.string.light_sensor_current_value, lux)); } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } }; public AutoBrightnessCustomizeDialog(Context context) { super(context); } @Override protected void onCreate(Bundle savedInstanceState) { final Context context = getContext(); View view = getLayoutInflater().inflate(R.layout.dialog_auto_brightness_levels, null); setView(view); setTitle(R.string.auto_brightness_dialog_title); setCancelable(true); setButton(DialogInterface.BUTTON_POSITIVE, context.getString(android.R.string.ok), this); setButton(DialogInterface.BUTTON_NEUTRAL, context.getString(R.string.auto_brightness_reset_button), this); setButton(DialogInterface.BUTTON_NEGATIVE, context.getString(android.R.string.cancel), this); super.onCreate(savedInstanceState); mSensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE); mLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT); PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); mMinLevel = pm.getMinimumAbsoluteScreenBrightness(); mSensorLevel = (TextView) view.findViewById(R.id.light_sensor_value); mBrightnessLevel = (TextView) view.findViewById(R.id.current_brightness); mConfigList = (ListView) view.findViewById(android.R.id.list); mAdapter = new SettingRowAdapter(context, new ArrayList<SettingRow>()); mConfigList.setAdapter(mAdapter); registerForContextMenu(mConfigList); } @Override protected void onStart() { updateSettings(false); super.onStart(); mSensorManager.registerListener(mLightSensorListener, mLightSensor, SensorManager.SENSOR_DELAY_NORMAL); Button neutralButton = getButton(DialogInterface.BUTTON_NEUTRAL); neutralButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showResetConfirmation(); } }); } @Override protected void onStop() { super.onStop(); mSensorManager.unregisterListener(mLightSensorListener, mLightSensor); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo; menu.setHeaderTitle(R.string.auto_brightness_level_options); menu.add(Menu.NONE, Menu.FIRST, 0, R.string.auto_brightness_menu_edit_lux) .setEnabled(!mAdapter.isLastItem(info.position)); menu.add(Menu.NONE, Menu.FIRST + 1, 1, R.string.auto_brightness_menu_split) .setEnabled(mAdapter.canSplitRow(info.position)); menu.add(Menu.NONE, Menu.FIRST + 2, 2, R.string.auto_brightness_menu_remove) .setEnabled(mAdapter.getCount() > 1); } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); int position = info.position; switch (item.getItemId() - Menu.FIRST) { case 0: showLuxSetup(position); return true; case 1: showSplitDialog(position); break; case 2: mAdapter.removeRow(position); return true; } return false; } @Override public void onClick(DialogInterface dialog, int which) { if (which == DialogInterface.BUTTON_POSITIVE) { putSettings(); } else if (which == DialogInterface.BUTTON_NEGATIVE) { cancel(); } } private void updateSettings(boolean forceDefault) { int[] lux = null, values = null; if (!forceDefault) { lux = fetchItems(Settings.System.AUTO_BRIGHTNESS_LUX); values = fetchItems(Settings.System.AUTO_BRIGHTNESS_BACKLIGHT); } if (lux != null && values != null && lux.length != values.length - 1) { Log.e(TAG, "Found invalid backlight settings, ignoring"); values = null; } if (lux == null || values == null) { final Resources res = getContext().getResources(); lux = res.getIntArray(com.android.internal.R.array.config_autoBrightnessLevels); values = res.getIntArray(com.android.internal.R.array.config_autoBrightnessLcdBacklightValues); mIsDefault = true; } else { mIsDefault = false; } mAdapter.initFromSettings(lux, values); } private void showLuxSetup(final int position) { final SettingRow row = mAdapter.getItem(position); final View v = getLayoutInflater().inflate(R.layout.auto_brightness_lux_config, null); final EditText startLux = (EditText) v.findViewById(R.id.start_lux); final EditText endLux = (EditText) v.findViewById(R.id.end_lux); final AlertDialog d = new AlertDialog.Builder(getContext()) .setTitle(R.string.auto_brightness_lux_dialog_title) .setCancelable(true) .setView(v) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface d, int which) { try { int newLux = Integer.valueOf(endLux.getText().toString()); mAdapter.setLuxToForRow(position, newLux); } catch (NumberFormatException e) { //ignored } } }) .setNegativeButton(R.string.cancel, null) .create(); startLux.setText(String.valueOf(row.luxFrom)); endLux.setText(String.valueOf(row.luxTo)); d.show(); } private void showSplitDialog(final int position) { final SettingRow row = mAdapter.getItem(position); final View v = getLayoutInflater().inflate(R.layout.auto_brightness_split_dialog, null); final TextView label = (TextView) v.findViewById(R.id.split_label); final EditText value = (EditText) v.findViewById(R.id.split_position); final AlertDialog d = new AlertDialog.Builder(getContext()) .setTitle(R.string.auto_brightness_lux_dialog_title) .setCancelable(true) .setView(v) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface d, int which) { int splitLux = Integer.valueOf(value.getText().toString()); mAdapter.splitRow(position, splitLux); } }) .setNegativeButton(R.string.cancel, null) .create(); label.setText(getContext().getString(R.string.auto_brightness_split_lux_format, row.luxFrom + 1, row.luxTo - 1)); value.setText(String.valueOf(row.luxFrom + 1)); value.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { boolean ok = false; try { int newLux = Integer.valueOf(s.toString()); ok = newLux > row.luxFrom && newLux < row.luxTo; } catch (NumberFormatException e) { //ignored, ok is false anyway } Button okButton = d.getButton(DialogInterface.BUTTON_POSITIVE); if (okButton != null) { okButton.setEnabled(ok); } } }); d.show(); } private void showResetConfirmation() { final AlertDialog d = new AlertDialog.Builder(getContext()) .setTitle(R.string.auto_brightness_reset_dialog_title) .setCancelable(true) .setMessage(R.string.auto_brightness_reset_confirmation) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface d, int which) { updateSettings(true); } }) .setNegativeButton(R.string.cancel, null) .create(); d.show(); } private void putSettings() { int[] lux = null, values = null; if (!mIsDefault) { lux = mAdapter.getLuxValues(); values = mAdapter.getBacklightValues(); } putItems(Settings.System.AUTO_BRIGHTNESS_LUX, lux); putItems(Settings.System.AUTO_BRIGHTNESS_BACKLIGHT, values); } private int[] fetchItems(String setting) { String value = Settings.System.getString(getContext().getContentResolver(), setting); if (value != null) { String[] values = value.split(","); if (values != null && values.length != 0) { int[] result = new int[values.length]; int i; for (i = 0; i < values.length; i++) { try { result[i] = Integer.valueOf(values[i]); } catch (NumberFormatException e) { break; } } if (i == values.length) { return result; } } } return null; } private void putItems(String setting, int[] values) { String value = null; if (values != null) { final StringBuilder builder = new StringBuilder(); for (int i = 0; i < values.length; i++) { if (i > 0) { builder.append(","); } builder.append(values[i]); } value = builder.toString(); } Settings.System.putString(getContext().getContentResolver(), setting, value); } private class SettingRowAdapter extends ArrayAdapter<SettingRow> { public SettingRowAdapter(Context context, ArrayList<SettingRow> rows) { super(context, 0, rows); setNotifyOnChange(false); } private boolean isLastItem(int position) { return position == getCount() - 1; } public boolean canSplitRow(int position) { if (isLastItem(position)) { return false; } SettingRow row = getItem(position); return row.luxTo > (row.luxFrom + 1); } public void initFromSettings(int[] lux, int[] values) { ArrayList<SettingRow> settings = new ArrayList<SettingRow>(values.length); for (int i = 0; i < lux.length; i++) { settings.add(new SettingRow(i == 0 ? 0 : lux[i - 1], lux[i], values[i])); } settings.add(new SettingRow(lux[lux.length - 1], Integer.MAX_VALUE, values[values.length - 1])); clear(); addAll(settings); notifyDataSetChanged(); } public int[] getLuxValues() { int count = getCount(); int[] lux = new int[count - 1]; for (int i = 0; i < count - 1; i++) { lux[i] = getItem(i).luxTo; } return lux; } public int[] getBacklightValues() { int count = getCount(); int[] values = new int[count]; for (int i = 0; i < count; i++) { values[i] = getItem(i).backlight; } return values; } public void splitRow(int position, int splitLux) { if (!canSplitRow(position)) { return; } ArrayList<SettingRow> rows = new ArrayList<SettingRow>(); for (int i = 0; i <= position; i++) { rows.add(getItem(i)); } SettingRow lastRow = getItem(position); SettingRow nextRow = getItem(position + 1); rows.add(new SettingRow(splitLux, nextRow.luxFrom, lastRow.backlight)); for (int i = position + 1; i < getCount(); i++) { rows.add(getItem(i)); } clear(); addAll(rows); sanitizeValuesAndNotify(); } public void removeRow(int position) { if (getCount() <= 1) { return; } remove(getItem(position)); sanitizeValuesAndNotify(); } public void setLuxToForRow(final int position, int newLuxTo) { final SettingRow row = getItem(position); if (isLastItem(position) || row.luxTo == newLuxTo) { return; } row.luxTo = newLuxTo; sanitizeValuesAndNotify(); } public void sanitizeValuesAndNotify() { final int count = getCount(); getItem(0).luxFrom = 0; for (int i = 1; i < count; i++) { SettingRow lastRow = getItem(i - 1); SettingRow thisRow = getItem(i); thisRow.luxFrom = Math.max(lastRow.luxFrom + 1, thisRow.luxFrom); thisRow.backlight = Math.max(lastRow.backlight, thisRow.backlight); lastRow.luxTo = thisRow.luxFrom; } getItem(count - 1).luxTo = Integer.MAX_VALUE; mIsDefault = false; mAdapter.notifyDataSetChanged(); } private int brightnessToProgress(int brightness) { brightness -= mMinLevel; return brightness * 100; } private float progressToBrightness(int progress) { float brightness = (float) progress / 100F; return brightness + mMinLevel; } @Override public View getView(int position, View convertView, ViewGroup parent) { final Holder holder; if (convertView == null) { convertView = getLayoutInflater().inflate( R.layout.auto_brightness_list_item, parent, false); holder = new Holder(); holder.lux = (TextView) convertView.findViewById(R.id.lux); holder.backlight = (SeekBar) convertView.findViewById(R.id.backlight); holder.percent = (TextView) convertView.findViewById(R.id.backlight_percent); convertView.setTag(holder); holder.backlight.setMax(brightnessToProgress(PowerManager.BRIGHTNESS_ON)); holder.backlight.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { private boolean mIsDragging = false; private void updateBrightness(float brightness) { final Window window = getWindow(); final WindowManager.LayoutParams params = window.getAttributes(); params.screenBrightness = brightness; window.setAttributes(params); } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { int pos = (Integer) seekBar.getTag(); if (fromUser) { int minValue = pos == 0 ? 0 : brightnessToProgress(getItem(pos - 1).backlight); int maxValue = isLastItem(pos) ? seekBar.getMax() : brightnessToProgress(getItem(pos + 1).backlight); if (progress < minValue) { seekBar.setProgress(minValue); - return; + progress = minValue; } else if (progress > maxValue) { seekBar.setProgress(maxValue); - return; + progress = maxValue; } getItem(pos).backlight = Math.round(progressToBrightness(progress)); mIsDefault = false; } if (mIsDragging) { float brightness = progressToBrightness(progress); updateBrightness(brightness / PowerManager.BRIGHTNESS_ON); } holder.updatePercent(); } @Override public void onStartTrackingTouch(SeekBar seekBar) { float brightness = progressToBrightness(seekBar.getProgress()); updateBrightness(brightness / PowerManager.BRIGHTNESS_ON); mIsDragging = true; } @Override public void onStopTrackingTouch(SeekBar seekBar) { updateBrightness(WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE); mIsDragging = false; } }); } else { holder = (Holder) convertView.getTag(); } SettingRow row = (SettingRow) getItem(position); final String to = row.luxTo == Integer.MAX_VALUE ? "\u221e" : String.valueOf(row.luxTo); holder.lux.setText(getContext().getString(R.string.auto_brightness_level_format, String.valueOf(row.luxFrom), to)); holder.backlight.setTag(position); holder.backlight.setProgress(brightnessToProgress(row.backlight)); holder.updatePercent(); return convertView; } private class Holder { TextView lux; SeekBar backlight; TextView percent; public void updatePercent() { int percentValue = Math.round((float) backlight.getProgress() * 100F / backlight.getMax()); percent.setText(getContext().getString( R.string.auto_brightness_brightness_format, percentValue)); } }; }; }
false
true
public View getView(int position, View convertView, ViewGroup parent) { final Holder holder; if (convertView == null) { convertView = getLayoutInflater().inflate( R.layout.auto_brightness_list_item, parent, false); holder = new Holder(); holder.lux = (TextView) convertView.findViewById(R.id.lux); holder.backlight = (SeekBar) convertView.findViewById(R.id.backlight); holder.percent = (TextView) convertView.findViewById(R.id.backlight_percent); convertView.setTag(holder); holder.backlight.setMax(brightnessToProgress(PowerManager.BRIGHTNESS_ON)); holder.backlight.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { private boolean mIsDragging = false; private void updateBrightness(float brightness) { final Window window = getWindow(); final WindowManager.LayoutParams params = window.getAttributes(); params.screenBrightness = brightness; window.setAttributes(params); } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { int pos = (Integer) seekBar.getTag(); if (fromUser) { int minValue = pos == 0 ? 0 : brightnessToProgress(getItem(pos - 1).backlight); int maxValue = isLastItem(pos) ? seekBar.getMax() : brightnessToProgress(getItem(pos + 1).backlight); if (progress < minValue) { seekBar.setProgress(minValue); return; } else if (progress > maxValue) { seekBar.setProgress(maxValue); return; } getItem(pos).backlight = Math.round(progressToBrightness(progress)); mIsDefault = false; } if (mIsDragging) { float brightness = progressToBrightness(progress); updateBrightness(brightness / PowerManager.BRIGHTNESS_ON); } holder.updatePercent(); } @Override public void onStartTrackingTouch(SeekBar seekBar) { float brightness = progressToBrightness(seekBar.getProgress()); updateBrightness(brightness / PowerManager.BRIGHTNESS_ON); mIsDragging = true; } @Override public void onStopTrackingTouch(SeekBar seekBar) { updateBrightness(WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE); mIsDragging = false; } }); } else { holder = (Holder) convertView.getTag(); } SettingRow row = (SettingRow) getItem(position); final String to = row.luxTo == Integer.MAX_VALUE ? "\u221e" : String.valueOf(row.luxTo); holder.lux.setText(getContext().getString(R.string.auto_brightness_level_format, String.valueOf(row.luxFrom), to)); holder.backlight.setTag(position); holder.backlight.setProgress(brightnessToProgress(row.backlight)); holder.updatePercent(); return convertView; }
public View getView(int position, View convertView, ViewGroup parent) { final Holder holder; if (convertView == null) { convertView = getLayoutInflater().inflate( R.layout.auto_brightness_list_item, parent, false); holder = new Holder(); holder.lux = (TextView) convertView.findViewById(R.id.lux); holder.backlight = (SeekBar) convertView.findViewById(R.id.backlight); holder.percent = (TextView) convertView.findViewById(R.id.backlight_percent); convertView.setTag(holder); holder.backlight.setMax(brightnessToProgress(PowerManager.BRIGHTNESS_ON)); holder.backlight.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { private boolean mIsDragging = false; private void updateBrightness(float brightness) { final Window window = getWindow(); final WindowManager.LayoutParams params = window.getAttributes(); params.screenBrightness = brightness; window.setAttributes(params); } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { int pos = (Integer) seekBar.getTag(); if (fromUser) { int minValue = pos == 0 ? 0 : brightnessToProgress(getItem(pos - 1).backlight); int maxValue = isLastItem(pos) ? seekBar.getMax() : brightnessToProgress(getItem(pos + 1).backlight); if (progress < minValue) { seekBar.setProgress(minValue); progress = minValue; } else if (progress > maxValue) { seekBar.setProgress(maxValue); progress = maxValue; } getItem(pos).backlight = Math.round(progressToBrightness(progress)); mIsDefault = false; } if (mIsDragging) { float brightness = progressToBrightness(progress); updateBrightness(brightness / PowerManager.BRIGHTNESS_ON); } holder.updatePercent(); } @Override public void onStartTrackingTouch(SeekBar seekBar) { float brightness = progressToBrightness(seekBar.getProgress()); updateBrightness(brightness / PowerManager.BRIGHTNESS_ON); mIsDragging = true; } @Override public void onStopTrackingTouch(SeekBar seekBar) { updateBrightness(WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE); mIsDragging = false; } }); } else { holder = (Holder) convertView.getTag(); } SettingRow row = (SettingRow) getItem(position); final String to = row.luxTo == Integer.MAX_VALUE ? "\u221e" : String.valueOf(row.luxTo); holder.lux.setText(getContext().getString(R.string.auto_brightness_level_format, String.valueOf(row.luxFrom), to)); holder.backlight.setTag(position); holder.backlight.setProgress(brightnessToProgress(row.backlight)); holder.updatePercent(); return convertView; }
diff --git a/src/net/mcft/copy/betterstorage/BetterStorage.java b/src/net/mcft/copy/betterstorage/BetterStorage.java index e6503b6..f8eab7f 100644 --- a/src/net/mcft/copy/betterstorage/BetterStorage.java +++ b/src/net/mcft/copy/betterstorage/BetterStorage.java @@ -1,183 +1,183 @@ package net.mcft.copy.betterstorage; import java.util.Random; import java.util.logging.Logger; import net.mcft.copy.betterstorage.block.BlockArmorStand; import net.mcft.copy.betterstorage.block.BlockLocker; import net.mcft.copy.betterstorage.block.BlockReinforcedChest; import net.mcft.copy.betterstorage.block.ChestMaterial; import net.mcft.copy.betterstorage.block.crate.BlockCrate; import net.mcft.copy.betterstorage.enchantment.EnchantmentBetterStorage; import net.mcft.copy.betterstorage.item.ItemKey; import net.mcft.copy.betterstorage.item.ItemLock; import net.mcft.copy.betterstorage.item.KeyRecipe; import net.mcft.copy.betterstorage.misc.CreativeTabBetterStorage; import net.mcft.copy.betterstorage.misc.Registry; import net.mcft.copy.betterstorage.misc.handlers.CraftingHandler; import net.mcft.copy.betterstorage.misc.handlers.GuiHandler; import net.minecraft.block.Block; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.ShapedOreRecipe; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod.Init; import cpw.mods.fml.common.Mod.Instance; import cpw.mods.fml.common.Mod.PreInit; import cpw.mods.fml.common.SidedProxy; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.network.NetworkMod; import cpw.mods.fml.common.network.NetworkRegistry; import cpw.mods.fml.common.registry.GameRegistry; import cpw.mods.fml.common.registry.LanguageRegistry; @Mod(modid="BetterStorage", version="@VERSION@", useMetadata=true) @NetworkMod(clientSideRequired=true, serverSideRequired=false) public class BetterStorage { public final static Random random = new Random(); @Instance("BetterStorage") public static BetterStorage instance; @SidedProxy(clientSide="net.mcft.copy.betterstorage.client.ClientProxy", serverSide="net.mcft.copy.betterstorage.CommonProxy") public static CommonProxy proxy; public static Logger log; // Blocks public static BlockCrate crate; public static BlockReinforcedChest reinforcedChest; public static BlockLocker locker; public static BlockArmorStand armorStand; // Items public static ItemKey key; public static ItemLock lock; public static CreativeTabs creativeTab; @PreInit public void preInit(FMLPreInitializationEvent event) { log = event.getModLog(); Config.load(event.getSuggestedConfigurationFile()); Config.save(); } @Init public void load(FMLInitializationEvent event) { creativeTab = new CreativeTabBetterStorage(); initializeItems(); EnchantmentBetterStorage.init(); addRecipes(); addLocalizations(); GameRegistry.registerCraftingHandler(new CraftingHandler()); NetworkRegistry.instance().registerGuiHandler(this, new GuiHandler()); proxy.init(); } private void initializeItems() { crate = new BlockCrate(Config.crateId); reinforcedChest = new BlockReinforcedChest(Config.chestId); locker = new BlockLocker(Config.lockerId); armorStand = new BlockArmorStand(Config.armorStandId); key = new ItemKey(Config.keyId); lock = new ItemLock(Config.lockId); Registry.doYourThing(); } private void addRecipes() { // Crate recipe GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(crate), "o/o", "/ /", "o/o", 'o', "plankWood", '/', Item.stick)); // Reinforced chest recipes for (ChestMaterial material : ChestMaterial.materials) GameRegistry.addRecipe(material.getRecipe(reinforcedChest)); // Locker recipe GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(locker), "ooo", "o |", "ooo", 'o', "plankWood", '|', Block.trapdoor)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(locker), "ooo", "| o", "ooo", 'o', "plankWood", '|', Block.trapdoor)); // Armor stand recipe GameRegistry.addRecipe(new ItemStack(armorStand), " i ", "/i/", " s ", 's', new ItemStack(Block.stoneSingleSlab, 1, 0), 'i', Item.ingotIron, '/', Item.stick); // Key recipe GameRegistry.addRecipe(KeyRecipe.createKeyRecipe( ".o", ".o", " o", 'o', Item.ingotGold, '.', Item.goldNugget)); // Key modify recipe GameRegistry.addRecipe(KeyRecipe.createKeyRecipe( "k", 'k', new ItemStack(key, 1, -1))); // Lock recipe GameRegistry.addRecipe(new ItemStack(lock), " o ", "oko", "oio", 'o', Item.ingotGold, - 'k', new ItemStack(key, 1, -1), + 'k', new ItemStack(key, 1, 32767), 'i', Item.ingotIron); } private void addLocalizations() { LanguageRegistry lang = LanguageRegistry.instance(); lang.addStringLocalization("itemGroup.betterstorage", "BetterStorage"); lang.addStringLocalization("container.crate", "Storage Crate"); lang.addStringLocalization("container.reinforcedChest", "Reinforced Chest"); lang.addStringLocalization("container.reinforcedChestLarge", "Large Reinforced Chest"); lang.addStringLocalization("container.locker", "Locker"); lang.addStringLocalization("container.lockerLarge", "Large Locker"); lang.addStringLocalization("enchantment.key.unlocking", "Unlocking"); lang.addStringLocalization("enchantment.key.lockpicking", "Lockpicking"); lang.addStringLocalization("enchantment.key.morphing", "Morphing"); lang.addStringLocalization("enchantment.lock.persistance", "Persistance"); lang.addStringLocalization("enchantment.lock.security", "Security"); lang.addStringLocalization("enchantment.lock.shock", "Shock"); lang.addStringLocalization("enchantment.lock.trigger", "Trigger"); for (ChestMaterial material : ChestMaterial.materials) lang.addStringLocalization("tile.reinforcedChest." + material.name + ".name", "Reinforced " + material.nameCapitalized + " Chest"); } }
true
true
private void addRecipes() { // Crate recipe GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(crate), "o/o", "/ /", "o/o", 'o', "plankWood", '/', Item.stick)); // Reinforced chest recipes for (ChestMaterial material : ChestMaterial.materials) GameRegistry.addRecipe(material.getRecipe(reinforcedChest)); // Locker recipe GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(locker), "ooo", "o |", "ooo", 'o', "plankWood", '|', Block.trapdoor)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(locker), "ooo", "| o", "ooo", 'o', "plankWood", '|', Block.trapdoor)); // Armor stand recipe GameRegistry.addRecipe(new ItemStack(armorStand), " i ", "/i/", " s ", 's', new ItemStack(Block.stoneSingleSlab, 1, 0), 'i', Item.ingotIron, '/', Item.stick); // Key recipe GameRegistry.addRecipe(KeyRecipe.createKeyRecipe( ".o", ".o", " o", 'o', Item.ingotGold, '.', Item.goldNugget)); // Key modify recipe GameRegistry.addRecipe(KeyRecipe.createKeyRecipe( "k", 'k', new ItemStack(key, 1, -1))); // Lock recipe GameRegistry.addRecipe(new ItemStack(lock), " o ", "oko", "oio", 'o', Item.ingotGold, 'k', new ItemStack(key, 1, -1), 'i', Item.ingotIron); }
private void addRecipes() { // Crate recipe GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(crate), "o/o", "/ /", "o/o", 'o', "plankWood", '/', Item.stick)); // Reinforced chest recipes for (ChestMaterial material : ChestMaterial.materials) GameRegistry.addRecipe(material.getRecipe(reinforcedChest)); // Locker recipe GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(locker), "ooo", "o |", "ooo", 'o', "plankWood", '|', Block.trapdoor)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(locker), "ooo", "| o", "ooo", 'o', "plankWood", '|', Block.trapdoor)); // Armor stand recipe GameRegistry.addRecipe(new ItemStack(armorStand), " i ", "/i/", " s ", 's', new ItemStack(Block.stoneSingleSlab, 1, 0), 'i', Item.ingotIron, '/', Item.stick); // Key recipe GameRegistry.addRecipe(KeyRecipe.createKeyRecipe( ".o", ".o", " o", 'o', Item.ingotGold, '.', Item.goldNugget)); // Key modify recipe GameRegistry.addRecipe(KeyRecipe.createKeyRecipe( "k", 'k', new ItemStack(key, 1, -1))); // Lock recipe GameRegistry.addRecipe(new ItemStack(lock), " o ", "oko", "oio", 'o', Item.ingotGold, 'k', new ItemStack(key, 1, 32767), 'i', Item.ingotIron); }
diff --git a/de.walware.statet.rtm.ggplot.core/src/de/walware/statet/rtm/ggplot/core/GGPlotRCodeGen.java b/de.walware.statet.rtm.ggplot.core/src/de/walware/statet/rtm/ggplot/core/GGPlotRCodeGen.java index f1b435fc..2587fc3d 100644 --- a/de.walware.statet.rtm.ggplot.core/src/de/walware/statet/rtm/ggplot/core/GGPlotRCodeGen.java +++ b/de.walware.statet.rtm.ggplot.core/src/de/walware/statet/rtm/ggplot/core/GGPlotRCodeGen.java @@ -1,382 +1,382 @@ /******************************************************************************* * Copyright (c) 2012-2013 WalWare/StatET-Project (www.walware.de/goto/statet). * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Stephan Wahlbrink - initial API and implementation *******************************************************************************/ package de.walware.statet.rtm.ggplot.core; import java.util.ArrayList; import java.util.List; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EStructuralFeature; import de.walware.ecommons.collections.ConstList; import de.walware.ecommons.collections.IntArrayMap; import de.walware.ecommons.collections.IntMap; import de.walware.statet.rtm.base.core.AbstractRCodeGenerator; import de.walware.statet.rtm.base.util.RExprTypes; import de.walware.statet.rtm.ggplot.FacetLayout; import de.walware.statet.rtm.ggplot.GGPlot; import de.walware.statet.rtm.ggplot.GGPlotPackage; import de.walware.statet.rtm.ggplot.GGPlotPackage.Literals; import de.walware.statet.rtm.ggplot.GeomBarLayer; import de.walware.statet.rtm.ggplot.GeomLineLayer; import de.walware.statet.rtm.ggplot.GeomPointLayer; import de.walware.statet.rtm.ggplot.GridFacetLayout; import de.walware.statet.rtm.ggplot.Layer; import de.walware.statet.rtm.ggplot.PropDataProvider; import de.walware.statet.rtm.ggplot.PropStatProvider; import de.walware.statet.rtm.ggplot.Stat; import de.walware.statet.rtm.ggplot.SummaryStat; import de.walware.statet.rtm.ggplot.TextStyle; import de.walware.statet.rtm.ggplot.WrapFacetLayout; import de.walware.statet.rtm.ggplot.core.GGPlotRCodeGen.E2R.Property; import de.walware.statet.rtm.rtdata.types.RTypedExpr; public class GGPlotRCodeGen extends AbstractRCodeGenerator { /** * Static mapping */ static class E2R { static class Property { private final EStructuralFeature fEFeature; private final String fRArg; private final boolean fAllowMapped; private final boolean fAllowDirect; public Property(final EStructuralFeature eFeature, final String rArg, final boolean allowMapped, final boolean allowDirect) { fEFeature = eFeature; fRArg = rArg; fAllowMapped = allowMapped; fAllowDirect = allowDirect; } public boolean allowMapped() { return fAllowMapped; } public boolean allowDirect() { return fAllowDirect; } public String getRArg() { return fRArg; } public EStructuralFeature getEFeature() { return fEFeature; } } private final EClass fEClass; private final String fRFun; private final List<Property> fProperties; public E2R(final EClass eClass, final String rFun) { fEClass = eClass; fRFun = rFun; final List<Property> list = new ArrayList<Property>(); addProperty(list, Literals.PROP_XVAR_PROVIDER__XVAR, "x"); //$NON-NLS-1$ addProperty(list, Literals.PROP_YVAR_PROVIDER__YVAR, "y"); //$NON-NLS-1$ addProperty(list, Literals.GEOM_TEXT_LAYER__LABEL, "label"); //$NON-NLS-1$ addProperty(list, Literals.GEOM_ABLINE_LAYER__INTERCEPT_VAR, "intercept"); //$NON-NLS-1$ addProperty(list, Literals.GEOM_ABLINE_LAYER__SLOPE_VAR, "slope"); //$NON-NLS-1$ addProperty(list, Literals.PROP_GROUP_VAR_PROVIDER__GROUP_VAR, "group"); //$NON-NLS-1$ addProperty(list, Literals.PROP_SHAPE_PROVIDER__SHAPE, "shape"); //$NON-NLS-1$ addProperty(list, Literals.PROP_LINE_TYPE_PROVIDER__LINE_TYPE, "linetype"); //$NON-NLS-1$ addProperty(list, Literals.TEXT_STYLE__FONT_FAMILY, "family"); //$NON-NLS-1$ addProperty(list, Literals.TEXT_STYLE__FONT_FACE, "face"); //$NON-NLS-1$ addProperty(list, Literals.PROP_SIZE_PROVIDER__SIZE, "size"); //$NON-NLS-1$ addProperty(list, Literals.PROP_COLOR_PROVIDER__COLOR, "colour"); //$NON-NLS-1$ addProperty(list, Literals.PROP_FILL_PROVIDER__FILL, "fill"); //$NON-NLS-1$ addProperty(list, Literals.TEXT_STYLE__HJUST, "hjust"); //$NON-NLS-1$ addProperty(list, Literals.TEXT_STYLE__VJUST, "vjust"); //$NON-NLS-1$ addProperty(list, Literals.TEXT_STYLE__ANGLE, "angle"); //$NON-NLS-1$ fProperties = list; } private void addProperty(final List<Property> list, final EStructuralFeature eFeature, final String rArg) { if (!fEClass.getEAllStructuralFeatures().contains(eFeature)) { return; } final RExprTypes types = GGPlotExprTypesProvider.INSTANCE.getTypes(fEClass, eFeature); final boolean allowMapped = types.contains(RTypedExpr.MAPPED); final boolean allowDirect = types.contains(RTypedExpr.R) || types.contains(RTypedExpr.CHAR); list.add(new Property(eFeature, rArg, allowMapped, allowDirect)); } public EClass getEClass() { return fEClass; } public String getRFun() { return fRFun; } public List<Property> getProperties() { return fProperties; } } private static final IntMap<E2R> E2R_PROPERTIES; static { final List<E2R> list = new ArrayList<GGPlotRCodeGen.E2R>(); list.add(new E2R(Literals.GG_PLOT, "ggplot")); //$NON-NLS-1$ list.add(new E2R(Literals.GEOM_ABLINE_LAYER, "geom_abline")); //$NON-NLS-1$ list.add(new E2R(Literals.GEOM_BAR_LAYER, "geom_bar")); //$NON-NLS-1$ list.add(new E2R(Literals.GEOM_BOXPLOT_LAYER, "geom_boxplot")); //$NON-NLS-1$ list.add(new E2R(Literals.GEOM_HISTOGRAM_LAYER, "geom_histogram")); //$NON-NLS-1$ list.add(new E2R(Literals.GEOM_LINE_LAYER, "geom_line")); //$NON-NLS-1$ list.add(new E2R(Literals.GEOM_POINT_LAYER, "geom_point")); //$NON-NLS-1$ list.add(new E2R(Literals.GEOM_SMOOTH_LAYER, "geom_smooth")); //$NON-NLS-1$ list.add(new E2R(Literals.GEOM_TEXT_LAYER, "geom_text")); //$NON-NLS-1$ list.add(new E2R(Literals.GEOM_TILE_LAYER, "geom_tile")); //$NON-NLS-1$ list.add(new E2R(Literals.GEOM_VIOLIN_LAYER, "geom_violin")); //$NON-NLS-1$ list.add(new E2R(Literals.TEXT_STYLE, "text_theme")); //$NON-NLS-1$ list.add(new E2R(Literals.GRID_FACET_LAYOUT, "facet_grid")); //$NON-NLS-1$ list.add(new E2R(Literals.WRAP_FACET_LAYOUT, "facet_wrap")); //$NON-NLS-1$ E2R_PROPERTIES = new IntArrayMap<GGPlotRCodeGen.E2R>(); for (final E2R e2r : list) { final int id = e2r.getEClass().getClassifierID(); E2R_PROPERTIES.put(id, e2r); } } private static void appendMappedProperties(final FunBuilder fun, final EObject obj, final List<Property> properties) { for (final Property property : properties) { if (property.allowMapped()) { final Object value = obj.eGet(property.getEFeature()); fun.appendExpr(property.getRArg(), (RTypedExpr) value, RTypedExpr.MAPPED); } } } private static final List<String> DIRECT_TYPES = new ConstList<String>(RTypedExpr.R, RTypedExpr.CHAR); private static void appendDirectProperties(final FunBuilder fun, final EObject obj, final List<Property> properties) { for (final Property property : properties) { if (property.allowDirect()) { final Object value = obj.eGet(property.getEFeature()); fun.appendExpr(property.getRArg(), (RTypedExpr) value, DIRECT_TYPES); } } } private final String fPlotVar = "p"; //$NON-NLS-1$ @Override public void generate(final EObject root) { reset(); addRequirePackage("ggplot2"); //$NON-NLS-1$ if (root == null) { return; } if (root.eClass().getClassifierID() != GGPlotPackage.GG_PLOT) { throw new IllegalArgumentException("root: " + root.eClass().getName()); //$NON-NLS-1$ } appendNewLine(); genRCode((GGPlot) root); appendNewLine(); final FunBuilder printFun = appendFun("print"); //$NON-NLS-1$ printFun.append(null, fPlotVar); printFun.close(); appendNewLine(); } public void genRCode(final GGPlot plot) { appendAssign(fPlotVar); { final E2R e2r = E2R_PROPERTIES.get(GGPlotPackage.GG_PLOT); final FunBuilder fun = appendFun(e2r.getRFun()); appendData(fun, plot); appendAes(fun, plot, e2r); fun.close(); appendNewLine(); addFacet(plot.getFacet()); addLab("title", plot.getMainTitle(), null, null); //$NON-NLS-1$ addTheme("plot.title", plot.getMainTitleStyle()); //$NON-NLS-1$ addLab("x", plot.getAxXLabel(), null, null); //$NON-NLS-1$ addTheme("axis.title.x ", plot.getAxXLabelStyle()); //$NON-NLS-1$ addTheme("axis.text.x ", plot.getAxXTextStyle()); //$NON-NLS-1$ addLab("y", plot.getAxYLabel(), null, null); //$NON-NLS-1$ - addTheme("axis.title.x ", plot.getAxYLabelStyle()); //$NON-NLS-1$ + addTheme("axis.title.y ", plot.getAxYLabelStyle()); //$NON-NLS-1$ addTheme("axis.text.y ", plot.getAxYTextStyle()); //$NON-NLS-1$ } final EList<Layer> layers = plot.getLayers(); for (final Layer layer : layers) { appendAssign(fPlotVar); fBuilder.append(fPlotVar); fBuilder.append(" + "); //$NON-NLS-1$ final E2R e2r = E2R_PROPERTIES.get(layer.eClass().getClassifierID()); final FunBuilder fun = appendFun(e2r.getRFun()); appendData(fun, layer); appendAes(fun, layer, e2r); switch (layer.eClass().getClassifierID()) { case GGPlotPackage.GEOM_BAR_LAYER: appendStat(fun, (GeomBarLayer) layer); break; case GGPlotPackage.GEOM_LINE_LAYER: appendStat(fun, (GeomLineLayer) layer); break; case GGPlotPackage.GEOM_POINT_LAYER: appendPosition(fun, (GeomPointLayer) layer); break; } fun.close(); appendNewLine(); } } private void appendData(final FunBuilder fun, final PropDataProvider obj) { if (obj.getData() != null) { String expr = obj.getData().getExpr(); if (obj instanceof GGPlot) { final RTypedExpr dataFilter = ((GGPlot) obj).getDataFilter(); if (dataFilter != null) { expr += dataFilter.getExpr(); } } fun.append("data", expr); //$NON-NLS-1$ } } private void appendAes(final FunBuilder fun, final EObject obj, final E2R e2r) { final List<Property> aesProperties = e2r.getProperties(); final FunBuilder aesFun = fun.appendFun(null, "aes"); //$NON-NLS-1$ appendMappedProperties(aesFun, obj, aesProperties); aesFun.closeOrRemove(); appendDirectProperties(fun, obj, aesProperties); } private void addFacet(final FacetLayout obj) { if (obj == null) { return; } appendAssign(fPlotVar); fBuilder.append(fPlotVar); fBuilder.append(" + "); //$NON-NLS-1$ FunBuilder facetFun; switch (obj.eClass().getClassifierID()) { case GGPlotPackage.GRID_FACET_LAYOUT: { final GridFacetLayout layout = (GridFacetLayout) obj; facetFun = appendFun("facet_grid"); //$NON-NLS-1$ appendExprList(layout.getRowVars(), " + ", "."); //$NON-NLS-1$ //$NON-NLS-2$ fBuilder.append(" ~ "); //$NON-NLS-1$ appendExprList(layout.getColVars(), " + ", "."); //$NON-NLS-1$ //$NON-NLS-2$ break; } case GGPlotPackage.WRAP_FACET_LAYOUT: { final WrapFacetLayout layout = (WrapFacetLayout) obj; facetFun = appendFun("facet_wrap"); //$NON-NLS-1$ fBuilder.append("~ "); //$NON-NLS-1$ appendExprList(layout.getColVars(), " + ", "."); //$NON-NLS-1$ //$NON-NLS-2$ facetFun.appendExpr("ncol", ((WrapFacetLayout) obj).getColNum()); //$NON-NLS-1$ break; } default: throw new UnsupportedOperationException(obj.eClass().getName()); } facetFun.close(); appendNewLine(); } private void appendPosition(final FunBuilder fun, final GeomPointLayer obj) { RTypedExpr xJitter = obj.getPositionXJitter(); RTypedExpr yJitter = obj.getPositionYJitter(); if ((xJitter == null && yJitter == null) ) { return; } if (xJitter == null) { xJitter = R_NUM_ZERO_EXPR; } if (yJitter == null) { yJitter = R_NUM_ZERO_EXPR; } final FunBuilder jitterFun = fun.appendFun("position", "position_jitter"); //$NON-NLS-1$ //$NON-NLS-2$ jitterFun.appendExpr("w", xJitter); //$NON-NLS-1$ jitterFun.appendExpr("h", yJitter); //$NON-NLS-1$ jitterFun.close(); } private void appendStat(final FunBuilder fun, final PropStatProvider obj) { final Stat stat = obj.getStat(); if (stat == null) { return; } switch (stat.eClass().getClassifierID()) { case GGPlotPackage.IDENTITY_STAT: fun.append("stat", "\"identity\""); //$NON-NLS-1$ //$NON-NLS-2$ return; case GGPlotPackage.SUMMARY_STAT: fun.append("stat", "\"summary\""); //$NON-NLS-1$ //$NON-NLS-2$ fun.appendExpr("fun.y", ((SummaryStat) stat).getYFun()); //$NON-NLS-1$ return; } } private void addLab(final String lab, final RTypedExpr text, final String lab2, final RTypedExpr text2) { if (text == null && text2 == null) { return; } appendAssign(fPlotVar); fBuilder.append(fPlotVar); fBuilder.append(" + "); //$NON-NLS-1$ final FunBuilder labsFun = appendFun("labs"); //$NON-NLS-1$ labsFun.appendExpr(lab, text, DIRECT_TYPES); if (lab2 != null) { labsFun.appendExpr(lab2, text2, DIRECT_TYPES); } labsFun.close(); appendNewLine(); } private void addTheme(final String text, final TextStyle obj) { if (obj.getFontFamily() == null && obj.getFontFace() == null && obj.getSize() == null && obj.getColor() == null && obj.getHJust() == null && obj.getVJust() == null && obj.getAngle() == null) { return; } final E2R e2r = E2R_PROPERTIES.get(obj.eClass().getClassifierID()); appendAssign(fPlotVar); fBuilder.append(fPlotVar); fBuilder.append(" + "); //$NON-NLS-1$ final FunBuilder themeFun = appendFun("theme"); //$NON-NLS-1$ final FunBuilder textFun = themeFun.appendFun(text, "element_text"); //$NON-NLS-1$ appendDirectProperties(textFun, obj, e2r.getProperties()); textFun.close(); themeFun.close(); appendNewLine(); } }
true
true
public void genRCode(final GGPlot plot) { appendAssign(fPlotVar); { final E2R e2r = E2R_PROPERTIES.get(GGPlotPackage.GG_PLOT); final FunBuilder fun = appendFun(e2r.getRFun()); appendData(fun, plot); appendAes(fun, plot, e2r); fun.close(); appendNewLine(); addFacet(plot.getFacet()); addLab("title", plot.getMainTitle(), null, null); //$NON-NLS-1$ addTheme("plot.title", plot.getMainTitleStyle()); //$NON-NLS-1$ addLab("x", plot.getAxXLabel(), null, null); //$NON-NLS-1$ addTheme("axis.title.x ", plot.getAxXLabelStyle()); //$NON-NLS-1$ addTheme("axis.text.x ", plot.getAxXTextStyle()); //$NON-NLS-1$ addLab("y", plot.getAxYLabel(), null, null); //$NON-NLS-1$ addTheme("axis.title.x ", plot.getAxYLabelStyle()); //$NON-NLS-1$ addTheme("axis.text.y ", plot.getAxYTextStyle()); //$NON-NLS-1$ } final EList<Layer> layers = plot.getLayers(); for (final Layer layer : layers) { appendAssign(fPlotVar); fBuilder.append(fPlotVar); fBuilder.append(" + "); //$NON-NLS-1$ final E2R e2r = E2R_PROPERTIES.get(layer.eClass().getClassifierID()); final FunBuilder fun = appendFun(e2r.getRFun()); appendData(fun, layer); appendAes(fun, layer, e2r); switch (layer.eClass().getClassifierID()) { case GGPlotPackage.GEOM_BAR_LAYER: appendStat(fun, (GeomBarLayer) layer); break; case GGPlotPackage.GEOM_LINE_LAYER: appendStat(fun, (GeomLineLayer) layer); break; case GGPlotPackage.GEOM_POINT_LAYER: appendPosition(fun, (GeomPointLayer) layer); break; } fun.close(); appendNewLine(); } }
public void genRCode(final GGPlot plot) { appendAssign(fPlotVar); { final E2R e2r = E2R_PROPERTIES.get(GGPlotPackage.GG_PLOT); final FunBuilder fun = appendFun(e2r.getRFun()); appendData(fun, plot); appendAes(fun, plot, e2r); fun.close(); appendNewLine(); addFacet(plot.getFacet()); addLab("title", plot.getMainTitle(), null, null); //$NON-NLS-1$ addTheme("plot.title", plot.getMainTitleStyle()); //$NON-NLS-1$ addLab("x", plot.getAxXLabel(), null, null); //$NON-NLS-1$ addTheme("axis.title.x ", plot.getAxXLabelStyle()); //$NON-NLS-1$ addTheme("axis.text.x ", plot.getAxXTextStyle()); //$NON-NLS-1$ addLab("y", plot.getAxYLabel(), null, null); //$NON-NLS-1$ addTheme("axis.title.y ", plot.getAxYLabelStyle()); //$NON-NLS-1$ addTheme("axis.text.y ", plot.getAxYTextStyle()); //$NON-NLS-1$ } final EList<Layer> layers = plot.getLayers(); for (final Layer layer : layers) { appendAssign(fPlotVar); fBuilder.append(fPlotVar); fBuilder.append(" + "); //$NON-NLS-1$ final E2R e2r = E2R_PROPERTIES.get(layer.eClass().getClassifierID()); final FunBuilder fun = appendFun(e2r.getRFun()); appendData(fun, layer); appendAes(fun, layer, e2r); switch (layer.eClass().getClassifierID()) { case GGPlotPackage.GEOM_BAR_LAYER: appendStat(fun, (GeomBarLayer) layer); break; case GGPlotPackage.GEOM_LINE_LAYER: appendStat(fun, (GeomLineLayer) layer); break; case GGPlotPackage.GEOM_POINT_LAYER: appendPosition(fun, (GeomPointLayer) layer); break; } fun.close(); appendNewLine(); } }
diff --git a/modules/foundation/hud/src/classes/org/jdesktop/wonderland/modules/hud/client/HUDCompassLayoutManager.java b/modules/foundation/hud/src/classes/org/jdesktop/wonderland/modules/hud/client/HUDCompassLayoutManager.java index cdcc6f4c1..5f0feb598 100644 --- a/modules/foundation/hud/src/classes/org/jdesktop/wonderland/modules/hud/client/HUDCompassLayoutManager.java +++ b/modules/foundation/hud/src/classes/org/jdesktop/wonderland/modules/hud/client/HUDCompassLayoutManager.java @@ -1,101 +1,101 @@ /* * Project Wonderland * * Copyright (c) 2004-2009, Sun Microsystems, Inc., All Rights Reserved * * Redistributions in source code form must reproduce the above * copyright and this condition. * * The contents of this file are subject to the GNU General Public * License, Version 2 (the "License"); you may not use this file * except in compliance with the License. A copy of the License is * available at http://www.opensource.org/licenses/gpl-license.php. * * Sun designates this particular file as subject to the "Classpath" * exception as provided by Sun in the License file that accompanied * this code. */ package org.jdesktop.wonderland.modules.hud.client; import com.jme.math.Vector2f; import java.util.logging.Logger; import org.jdesktop.wonderland.client.hud.CompassLayout.Layout; import org.jdesktop.wonderland.client.hud.HUDComponent; /** * A layout manager which lays out HUD components according to compass point * positions. * @author nsimpson */ public class HUDCompassLayoutManager extends HUDAbsoluteLayoutManager { private static final Logger logger = Logger.getLogger(HUDCompassLayoutManager.class.getName()); public HUDCompassLayoutManager(int hudWidth, int hudHeight) { super(hudWidth, hudHeight); } /** * {@inheritDoc} */ @Override public Vector2f getLocation(HUDComponent component) { Vector2f location = new Vector2f(); if (component == null) { return location; } HUDView2D view2d = (HUDView2D) hudViewMap.get(component); if (view2d == null) { return location; } // get HUD component's view width float compWidth = view2d.getDisplayerLocalWidth(); float compHeight = view2d.getDisplayerLocalHeight(); // get the center of the HUD float hudCenterX = hudWidth / 2f; float hudCenterY = hudHeight / 2f; if (component.getPreferredLocation() != Layout.NONE) { switch (component.getPreferredLocation()) { case NORTH: - location.set(hudCenterX, hudHeight - 20 - compHeight); + location.set(hudCenterX, hudHeight - 20 - compHeight / 2f); break; case SOUTH: location.set(hudCenterX, 20); break; case WEST: location.set(20 + compWidth / 2f, hudCenterY - compHeight / 2f); break; case EAST: location.set(hudWidth - 20 - compWidth / 2f, hudCenterY - compHeight / 2f); break; case CENTER: location.set(hudCenterX, hudCenterY); break; case NORTHWEST: location.set(20 + compWidth / 2f, hudHeight - 20 - compHeight / 2f); break; case NORTHEAST: location.set(hudWidth - 20 - compWidth / 2f, hudHeight - 20 - compHeight / 2f); break; case SOUTHWEST: location.set(20 + compWidth / 2f, 20 + compHeight / 2f); break; case SOUTHEAST: location.set(hudWidth - 20 - compWidth / 2, 20 + compHeight / 2f); break; default: logger.warning("unhandled layout type: " + component.getPreferredLocation()); break; } } else { location.set(component.getX() + compWidth / 2f, component.getY() + compHeight / 2f); } return location; } }
true
true
public Vector2f getLocation(HUDComponent component) { Vector2f location = new Vector2f(); if (component == null) { return location; } HUDView2D view2d = (HUDView2D) hudViewMap.get(component); if (view2d == null) { return location; } // get HUD component's view width float compWidth = view2d.getDisplayerLocalWidth(); float compHeight = view2d.getDisplayerLocalHeight(); // get the center of the HUD float hudCenterX = hudWidth / 2f; float hudCenterY = hudHeight / 2f; if (component.getPreferredLocation() != Layout.NONE) { switch (component.getPreferredLocation()) { case NORTH: location.set(hudCenterX, hudHeight - 20 - compHeight); break; case SOUTH: location.set(hudCenterX, 20); break; case WEST: location.set(20 + compWidth / 2f, hudCenterY - compHeight / 2f); break; case EAST: location.set(hudWidth - 20 - compWidth / 2f, hudCenterY - compHeight / 2f); break; case CENTER: location.set(hudCenterX, hudCenterY); break; case NORTHWEST: location.set(20 + compWidth / 2f, hudHeight - 20 - compHeight / 2f); break; case NORTHEAST: location.set(hudWidth - 20 - compWidth / 2f, hudHeight - 20 - compHeight / 2f); break; case SOUTHWEST: location.set(20 + compWidth / 2f, 20 + compHeight / 2f); break; case SOUTHEAST: location.set(hudWidth - 20 - compWidth / 2, 20 + compHeight / 2f); break; default: logger.warning("unhandled layout type: " + component.getPreferredLocation()); break; } } else { location.set(component.getX() + compWidth / 2f, component.getY() + compHeight / 2f); } return location; }
public Vector2f getLocation(HUDComponent component) { Vector2f location = new Vector2f(); if (component == null) { return location; } HUDView2D view2d = (HUDView2D) hudViewMap.get(component); if (view2d == null) { return location; } // get HUD component's view width float compWidth = view2d.getDisplayerLocalWidth(); float compHeight = view2d.getDisplayerLocalHeight(); // get the center of the HUD float hudCenterX = hudWidth / 2f; float hudCenterY = hudHeight / 2f; if (component.getPreferredLocation() != Layout.NONE) { switch (component.getPreferredLocation()) { case NORTH: location.set(hudCenterX, hudHeight - 20 - compHeight / 2f); break; case SOUTH: location.set(hudCenterX, 20); break; case WEST: location.set(20 + compWidth / 2f, hudCenterY - compHeight / 2f); break; case EAST: location.set(hudWidth - 20 - compWidth / 2f, hudCenterY - compHeight / 2f); break; case CENTER: location.set(hudCenterX, hudCenterY); break; case NORTHWEST: location.set(20 + compWidth / 2f, hudHeight - 20 - compHeight / 2f); break; case NORTHEAST: location.set(hudWidth - 20 - compWidth / 2f, hudHeight - 20 - compHeight / 2f); break; case SOUTHWEST: location.set(20 + compWidth / 2f, 20 + compHeight / 2f); break; case SOUTHEAST: location.set(hudWidth - 20 - compWidth / 2, 20 + compHeight / 2f); break; default: logger.warning("unhandled layout type: " + component.getPreferredLocation()); break; } } else { location.set(component.getX() + compWidth / 2f, component.getY() + compHeight / 2f); } return location; }
diff --git a/src/org/sagemath/droid/CellListFragment.java b/src/org/sagemath/droid/CellListFragment.java index 23dd04f..7fa6de9 100644 --- a/src/org/sagemath/droid/CellListFragment.java +++ b/src/org/sagemath/droid/CellListFragment.java @@ -1,66 +1,66 @@ package org.sagemath.droid; import java.util.LinkedList; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.ListFragment; import android.view.View; import android.widget.ListView; public class CellListFragment extends ListFragment { private static final String TAG = "CellListFragment"; protected LinkedList<CellData> cells = new LinkedList<CellData>(); protected CellListAdapter adapter; @Override public void onResume() { super.onResume(); switchToGroup(null); adapter = new CellListAdapter(getActivity(), cells); setListAdapter(adapter); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); adapter = new CellListAdapter(getActivity(), cells); setListAdapter(adapter); } public void switchToGroup(String group) { CellCollection cellCollection = CellCollection.getInstance(); cells.clear(); if (group == null) { LinkedList<CellData> data = cellCollection.getCurrentGroup(); if (data != null) cells.addAll(data); else return; } else cells.addAll(cellCollection.getGroup(group)); if (cells.size()>0) cellCollection.setCurrentCell(cells.getFirst()); else - getActivity().onBackPressed(); + getActivity().getSupportFragmentManager().popBackStack(); if (adapter != null) adapter.notifyDataSetChanged(); } @Override public void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); CellData cell = cells.get(position); CellCollection.getInstance().setCurrentCell(cell); Intent i = new Intent(getActivity().getApplicationContext(), SageActivity.class); startActivity(i); } }
true
true
public void switchToGroup(String group) { CellCollection cellCollection = CellCollection.getInstance(); cells.clear(); if (group == null) { LinkedList<CellData> data = cellCollection.getCurrentGroup(); if (data != null) cells.addAll(data); else return; } else cells.addAll(cellCollection.getGroup(group)); if (cells.size()>0) cellCollection.setCurrentCell(cells.getFirst()); else getActivity().onBackPressed(); if (adapter != null) adapter.notifyDataSetChanged(); }
public void switchToGroup(String group) { CellCollection cellCollection = CellCollection.getInstance(); cells.clear(); if (group == null) { LinkedList<CellData> data = cellCollection.getCurrentGroup(); if (data != null) cells.addAll(data); else return; } else cells.addAll(cellCollection.getGroup(group)); if (cells.size()>0) cellCollection.setCurrentCell(cells.getFirst()); else getActivity().getSupportFragmentManager().popBackStack(); if (adapter != null) adapter.notifyDataSetChanged(); }
diff --git a/src/main/java/de/cismet/cids/custom/objecteditors/wunda_blau/Sb_stadtbildserieEditor.java b/src/main/java/de/cismet/cids/custom/objecteditors/wunda_blau/Sb_stadtbildserieEditor.java index 1de6f470..ff59499e 100644 --- a/src/main/java/de/cismet/cids/custom/objecteditors/wunda_blau/Sb_stadtbildserieEditor.java +++ b/src/main/java/de/cismet/cids/custom/objecteditors/wunda_blau/Sb_stadtbildserieEditor.java @@ -1,2035 +1,2033 @@ /*************************************************** * * cismet GmbH, Saarbruecken, Germany * * ... and it just works. * ****************************************************/ package de.cismet.cids.custom.objecteditors.wunda_blau; import Sirius.server.middleware.types.AbstractAttributeRepresentationFormater; import com.vividsolutions.jts.geom.Geometry; import edu.umd.cs.piccolo.event.PBasicInputEventHandler; import edu.umd.cs.piccolo.event.PInputEvent; import org.jdesktop.beansbinding.Converter; import org.jdesktop.swingx.JXErrorPane; import org.jdesktop.swingx.error.ErrorInfo; import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.Color; import java.awt.Cursor; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.IOException; import java.io.InputStream; import java.lang.ref.SoftReference; import java.net.URL; import java.sql.Timestamp; import java.util.Arrays; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutionException; import java.util.logging.Level; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JComponent; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.SwingWorker; import javax.swing.Timer; import de.cismet.cids.client.tools.DevelopmentTools; import de.cismet.cids.custom.objectrenderer.utils.AbstractJasperReportPrint; import de.cismet.cids.custom.objectrenderer.utils.ObjectRendererUtils; import de.cismet.cids.custom.objectrenderer.wunda_blau.StadtbildJasperReportPrint; import de.cismet.cids.custom.utils.TifferDownload; import de.cismet.cids.custom.utils.alkis.AlkisConstants; import de.cismet.cids.dynamics.CidsBean; import de.cismet.cids.editors.DefaultBindableJCheckBox; import de.cismet.cids.editors.DefaultCustomObjectEditor; import de.cismet.cids.editors.FastBindableReferenceCombo; import de.cismet.cids.tools.metaobjectrenderer.CidsBeanRenderer; import de.cismet.cismap.commons.CrsTransformer; import de.cismet.cismap.commons.XBoundingBox; import de.cismet.cismap.commons.features.DefaultStyledFeature; import de.cismet.cismap.commons.features.StyledFeature; import de.cismet.cismap.commons.gui.MappingComponent; import de.cismet.cismap.commons.gui.layerwidget.ActiveLayerModel; import de.cismet.cismap.commons.raster.wms.simple.SimpleWMS; import de.cismet.cismap.commons.raster.wms.simple.SimpleWmsGetMapUrl; import de.cismet.security.WebAccessManager; import de.cismet.tools.gui.RoundedPanel; import de.cismet.tools.gui.StaticSwingTools; import de.cismet.tools.gui.TitleComponentProvider; import de.cismet.tools.gui.downloadmanager.DownloadManager; import de.cismet.tools.gui.downloadmanager.DownloadManagerDialog; import static de.cismet.cids.custom.objecteditors.wunda_blau.MauerEditor.adjustScale; /** * DOCUMENT ME! * * @author Gilles Baatz * @version $Revision$, $Date$ */ public class Sb_stadtbildserieEditor extends JPanel implements CidsBeanRenderer, TitleComponentProvider { //~ Static fields/initializers --------------------------------------------- public static final String REPORT_FILE = "/de/cismet/cids/custom/wunda_blau/res/StadtbildA4H.jasper"; private static final ImageIcon FOLDER_ICON = new ImageIcon(MauerEditor.class.getResource( "/de/cismet/cids/custom/objecteditors/wunda_blau/inode-directory.png")); private static final ImageIcon ERROR_ICON = new ImageIcon(MauerEditor.class.getResource( "/de/cismet/cids/custom/objecteditors/wunda_blau/file-broken.png")); private static final int CACHE_SIZE = 20; private static final Map<String, SoftReference<BufferedImage>> IMAGE_CACHE = new LinkedHashMap<String, SoftReference<BufferedImage>>(CACHE_SIZE) { @Override protected boolean removeEldestEntry(final Map.Entry<String, SoftReference<BufferedImage>> eldest) { return size() >= CACHE_SIZE; } }; private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(Sb_stadtbildserieEditor.class); //~ Instance fields -------------------------------------------------------- private CidsBean cidsBean; private String title; private final Converter<Timestamp, Date> timeStampConverter = new Converter<Timestamp, Date>() { @Override public Date convertForward(final Timestamp value) { try { if (value != null) { return new java.util.Date(value.getTime()); } else { return null; } } catch (Exception ex) { LOG.fatal(ex); return new java.util.Date(System.currentTimeMillis()); } } @Override public Timestamp convertReverse(final Date value) { try { if (value != null) { return new Timestamp(value.getTime()); } else { return null; } } catch (Exception ex) { LOG.fatal(ex); return new Timestamp(System.currentTimeMillis()); } } }; private final PropertyChangeListener listRepaintListener = new PropertyChangeListener() { @Override public void propertyChange(final PropertyChangeEvent evt) { lstBildnummern.repaint(); } }; private final AbstractAttributeRepresentationFormater strasseFormater = new AbstractAttributeRepresentationFormater() { @Override public final String getRepresentation() { return String.valueOf(getAttribute("name")); } }; private CidsBean fotoCidsBean; private BufferedImage image; private boolean resizeListenerEnabled; private final Timer timer; private Sb_stadtbildserieEditor.ImageResizeWorker currentResizeWorker; private MappingComponent map; // Variables declaration - do not modify//GEN-BEGIN:variables private de.cismet.cids.editors.FastBindableReferenceCombo bcbStrasse; private javax.swing.JButton btnAddImageNumber; private javax.swing.JButton btnAddSuchwort; private javax.swing.JButton btnCombineGeometries; private javax.swing.JButton btnDownloadHighResImage; private javax.swing.JButton btnNextImg; private javax.swing.JButton btnPrevImg; private javax.swing.JButton btnRemoveImageNumber; private javax.swing.JButton btnRemoveSuchwort; private javax.swing.JCheckBox chbPruefen; private de.cismet.cids.editors.DefaultBindableReferenceCombo dbcAuftraggeber; private de.cismet.cids.editors.DefaultBindableReferenceCombo dbcFilmart; private de.cismet.cids.editors.DefaultBindableReferenceCombo dbcFotograf; private de.cismet.cids.editors.DefaultBindableReferenceCombo dbcOrt; private de.cismet.cids.editors.DefaultBindableJTextField defaultBindableJTextField1; private de.cismet.cids.editors.DefaultBindableReferenceCombo defaultBindableReferenceCombo2; private de.cismet.cids.editors.DefaultBindableReferenceCombo defaultBindableReferenceCombo3; private de.cismet.cismap.cids.geometryeditor.DefaultCismapGeometryComboBoxEditor defaultCismapGeometryComboBoxEditor1; private javax.swing.Box.Filler filler1; private javax.swing.Box.Filler filler2; private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JScrollPane jScrollPane4; private javax.swing.JScrollPane jScrollPane5; private javax.swing.JTextArea jTextArea1; private javax.swing.JTextArea jTextArea2; private org.jdesktop.swingx.JXDatePicker jXDatePicker1; private org.jdesktop.swingx.JXBusyLabel lblBusy; private javax.swing.JLabel lblDescAufnahmedatum; private javax.swing.JLabel lblDescAuftraggeber; private javax.swing.JLabel lblDescBildnummer; private javax.swing.JLabel lblDescBildtyp; private javax.swing.JLabel lblDescFilmart; private javax.swing.JLabel lblDescFotograf; private javax.swing.JLabel lblDescGeometrie; private javax.swing.JLabel lblDescInfo; private javax.swing.JLabel lblDescLagerort; private javax.swing.JLabel lblDescOrt; private javax.swing.JLabel lblDescStrasse; private javax.swing.JLabel lblDescSuchworte; private javax.swing.JLabel lblGeomAus; private javax.swing.JLabel lblPicture; private javax.swing.JLabel lblPrint; private javax.swing.JLabel lblTitle; private javax.swing.JLabel lblVorschau; private javax.swing.JList lstBildnummern; private javax.swing.JList lstSuchworte; private javax.swing.JPanel panContent; private javax.swing.JPanel panDetails; private javax.swing.JPanel panDetails1; private javax.swing.JPanel panDetails3; private javax.swing.JPanel panDetails4; private javax.swing.JPanel panPrintButton; private javax.swing.JPanel panTitle; private javax.swing.JPanel panTitleString; private javax.swing.JPanel pnlCtrlBtn; private javax.swing.JPanel pnlCtrlButtons; private javax.swing.JPanel pnlCtrlButtons1; private javax.swing.JPanel pnlFoto; private javax.swing.JPanel pnlMap; private de.cismet.tools.gui.RoundedPanel pnlVorschau; private de.cismet.tools.gui.RoundedPanel roundedPanel1; private de.cismet.tools.gui.RoundedPanel roundedPanel2; private de.cismet.tools.gui.RoundedPanel roundedPanel3; private de.cismet.tools.gui.RoundedPanel roundedPanel4; private de.cismet.tools.gui.RoundedPanel roundedPanel6; private de.cismet.tools.gui.RoundedPanel roundedPanel7; private de.cismet.tools.gui.SemiRoundedPanel semiRoundedPanel1; private de.cismet.tools.gui.SemiRoundedPanel semiRoundedPanel2; private de.cismet.tools.gui.SemiRoundedPanel semiRoundedPanel3; private de.cismet.tools.gui.SemiRoundedPanel semiRoundedPanel4; private de.cismet.tools.gui.SemiRoundedPanel semiRoundedPanel5; private de.cismet.tools.gui.SemiRoundedPanel semiRoundedPanel7; private de.cismet.tools.gui.SemiRoundedPanel semiRoundedPanel8; private de.cismet.cids.custom.objectrenderer.converter.SQLDateToStringConverter sqlDateToStringConverter; private de.cismet.cids.editors.converters.SqlDateToUtilDateConverter sqlDateToUtilDateConverter; private javax.swing.JToggleButton tbtnIsPreviewImage; private org.jdesktop.beansbinding.BindingGroup bindingGroup; // End of variables declaration//GEN-END:variables //~ Constructors ----------------------------------------------------------- /** * Creates new form Arc_stadtbildRenderer. */ public Sb_stadtbildserieEditor() { initComponents(); jScrollPane5.getViewport().setOpaque(false); title = ""; ObjectRendererUtils.decorateComponentWithMouseOverCursorChange( lblPrint, Cursor.HAND_CURSOR, Cursor.DEFAULT_CURSOR); map = new MappingComponent(); pnlMap.setLayout(new BorderLayout()); pnlMap.add(map, BorderLayout.CENTER); timer = new Timer(300, new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { if (resizeListenerEnabled) { if (currentResizeWorker != null) { currentResizeWorker.cancel(true); } currentResizeWorker = new Sb_stadtbildserieEditor.ImageResizeWorker(); currentResizeWorker.execute(); } } }); timer.setRepeats(false); } //~ Methods ---------------------------------------------------------------- /** * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The * content of this method is always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; bindingGroup = new org.jdesktop.beansbinding.BindingGroup(); sqlDateToUtilDateConverter = new de.cismet.cids.editors.converters.SqlDateToUtilDateConverter(); sqlDateToStringConverter = new de.cismet.cids.custom.objectrenderer.converter.SQLDateToStringConverter(); panTitle = new javax.swing.JPanel(); panTitleString = new javax.swing.JPanel(); lblTitle = new javax.swing.JLabel(); panPrintButton = new javax.swing.JPanel(); lblPrint = new javax.swing.JLabel(); roundedPanel1 = new de.cismet.tools.gui.RoundedPanel(); semiRoundedPanel1 = new de.cismet.tools.gui.SemiRoundedPanel(); jScrollPane5 = new javax.swing.JScrollPane(); jPanel3 = new javax.swing.JPanel(); jPanel1 = new javax.swing.JPanel(); roundedPanel2 = new de.cismet.tools.gui.RoundedPanel(); semiRoundedPanel3 = new de.cismet.tools.gui.SemiRoundedPanel(); jLabel1 = new javax.swing.JLabel(); panContent = new RoundedPanel(); pnlCtrlButtons1 = new javax.swing.JPanel(); btnAddSuchwort = new javax.swing.JButton(); btnRemoveSuchwort = new javax.swing.JButton(); pnlCtrlButtons = new javax.swing.JPanel(); btnAddImageNumber = new javax.swing.JButton(); btnRemoveImageNumber = new javax.swing.JButton(); lblDescBildnummer = new javax.swing.JLabel(); lblDescLagerort = new javax.swing.JLabel(); lblDescAufnahmedatum = new javax.swing.JLabel(); lblDescInfo = new javax.swing.JLabel(); lblDescBildtyp = new javax.swing.JLabel(); lblDescSuchworte = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); lstBildnummern = new javax.swing.JList(); jScrollPane2 = new javax.swing.JScrollPane(); lstSuchworte = new javax.swing.JList(); defaultBindableReferenceCombo2 = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); defaultBindableReferenceCombo3 = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); jScrollPane3 = new javax.swing.JScrollPane(); jTextArea1 = new javax.swing.JTextArea(); jXDatePicker1 = new org.jdesktop.swingx.JXDatePicker(); roundedPanel3 = new de.cismet.tools.gui.RoundedPanel(); semiRoundedPanel4 = new de.cismet.tools.gui.SemiRoundedPanel(); jLabel2 = new javax.swing.JLabel(); panDetails = new RoundedPanel(); lblDescFilmart = new javax.swing.JLabel(); lblDescFotograf = new javax.swing.JLabel(); lblDescAuftraggeber = new javax.swing.JLabel(); dbcAuftraggeber = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); dbcFotograf = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); dbcFilmart = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); roundedPanel4 = new de.cismet.tools.gui.RoundedPanel(); semiRoundedPanel5 = new de.cismet.tools.gui.SemiRoundedPanel(); jLabel3 = new javax.swing.JLabel(); panDetails1 = new RoundedPanel(); lblDescGeometrie = new javax.swing.JLabel(); lblDescOrt = new javax.swing.JLabel(); lblDescStrasse = new javax.swing.JLabel(); dbcOrt = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); jLabel7 = new javax.swing.JLabel(); defaultBindableJTextField1 = new de.cismet.cids.editors.DefaultBindableJTextField(); lblGeomAus = new javax.swing.JLabel(); btnCombineGeometries = new javax.swing.JButton(); defaultCismapGeometryComboBoxEditor1 = new de.cismet.cismap.cids.geometryeditor.DefaultCismapGeometryComboBoxEditor(); bcbStrasse = new FastBindableReferenceCombo( "select s.strassenschluessel,s.name from strasse s", strasseFormater, new String[] { "NAME" }); jPanel2 = new javax.swing.JPanel(); pnlVorschau = new de.cismet.tools.gui.RoundedPanel(); semiRoundedPanel2 = new de.cismet.tools.gui.SemiRoundedPanel(); lblVorschau = new javax.swing.JLabel(); pnlFoto = new javax.swing.JPanel(); lblBusy = new org.jdesktop.swingx.JXBusyLabel(new Dimension(75, 75)); jPanel4 = new javax.swing.JPanel(); lblPicture = new javax.swing.JLabel(); pnlCtrlBtn = new javax.swing.JPanel(); btnDownloadHighResImage = new javax.swing.JButton(); btnPrevImg = new javax.swing.JButton(); btnNextImg = new javax.swing.JButton(); filler1 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0), new java.awt.Dimension(32767, 0)); filler2 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0), new java.awt.Dimension(32767, 0)); tbtnIsPreviewImage = new javax.swing.JToggleButton(); roundedPanel7 = new de.cismet.tools.gui.RoundedPanel(); semiRoundedPanel8 = new de.cismet.tools.gui.SemiRoundedPanel(); jLabel6 = new javax.swing.JLabel(); panDetails4 = new RoundedPanel(); pnlMap = new javax.swing.JPanel(); roundedPanel6 = new de.cismet.tools.gui.RoundedPanel(); semiRoundedPanel7 = new de.cismet.tools.gui.SemiRoundedPanel(); jLabel5 = new javax.swing.JLabel(); panDetails3 = new RoundedPanel(); chbPruefen = new DefaultBindableJCheckBox(); jScrollPane4 = new javax.swing.JScrollPane(); jTextArea2 = new javax.swing.JTextArea(); jButton1 = new javax.swing.JButton(); panTitle.setOpaque(false); panTitle.setLayout(new java.awt.BorderLayout()); panTitleString.setOpaque(false); panTitleString.setLayout(new java.awt.GridBagLayout()); lblTitle.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N lblTitle.setForeground(new java.awt.Color(255, 255, 255)); lblTitle.setText("TITLE"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); panTitleString.add(lblTitle, gridBagConstraints); panTitle.add(panTitleString, java.awt.BorderLayout.CENTER); panPrintButton.setOpaque(false); panPrintButton.setLayout(new java.awt.GridBagLayout()); lblPrint.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/icons/printer.png"))); // NOI18N lblPrint.addMouseListener(new java.awt.event.MouseAdapter() { @Override public void mouseClicked(final java.awt.event.MouseEvent evt) { lblPrintMouseClicked(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); panPrintButton.add(lblPrint, gridBagConstraints); panTitle.add(panPrintButton, java.awt.BorderLayout.EAST); roundedPanel1.add(semiRoundedPanel1, java.awt.BorderLayout.CENTER); setOpaque(false); setLayout(new java.awt.GridBagLayout()); jScrollPane5.setBorder(null); jScrollPane5.setOpaque(false); jPanel3.setOpaque(false); jPanel3.setLayout(new java.awt.GridBagLayout()); jPanel1.setOpaque(false); jPanel1.setLayout(new java.awt.GridBagLayout()); roundedPanel2.setLayout(new java.awt.GridBagLayout()); semiRoundedPanel3.setBackground(new java.awt.Color(51, 51, 51)); semiRoundedPanel3.setLayout(new java.awt.FlowLayout()); jLabel1.setForeground(new java.awt.Color(255, 255, 255)); jLabel1.setText("Allgemeine Informationen"); semiRoundedPanel3.add(jLabel1); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.ipadx = 1; roundedPanel2.add(semiRoundedPanel3, gridBagConstraints); panContent.setOpaque(false); panContent.setLayout(new java.awt.GridBagLayout()); pnlCtrlButtons1.setOpaque(false); pnlCtrlButtons1.setLayout(new java.awt.GridBagLayout()); btnAddSuchwort.setIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit_add_mini.png"))); // NOI18N btnAddSuchwort.setText(org.openide.util.NbBundle.getMessage( Sb_stadtbildserieEditor.class, "MauerEditor.btnAddImg.text")); // NOI18N btnAddSuchwort.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { btnAddSuchwortActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlCtrlButtons1.add(btnAddSuchwort, gridBagConstraints); btnRemoveSuchwort.setIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit_remove_mini.png"))); // NOI18N btnRemoveSuchwort.setText(org.openide.util.NbBundle.getMessage( Sb_stadtbildserieEditor.class, "MauerEditor.btnRemoveImg.text")); // NOI18N btnRemoveSuchwort.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { btnRemoveSuchwortActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridy = 1; pnlCtrlButtons1.add(btnRemoveSuchwort, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; panContent.add(pnlCtrlButtons1, gridBagConstraints); pnlCtrlButtons.setOpaque(false); pnlCtrlButtons.setLayout(new java.awt.GridBagLayout()); btnAddImageNumber.setIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit_add_mini.png"))); // NOI18N btnAddImageNumber.setText(org.openide.util.NbBundle.getMessage( Sb_stadtbildserieEditor.class, "MauerEditor.btnAddImg.text")); // NOI18N btnAddImageNumber.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { btnAddImageNumberActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlCtrlButtons.add(btnAddImageNumber, gridBagConstraints); btnRemoveImageNumber.setIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit_remove_mini.png"))); // NOI18N btnRemoveImageNumber.setText(org.openide.util.NbBundle.getMessage( Sb_stadtbildserieEditor.class, "MauerEditor.btnRemoveImg.text")); // NOI18N btnRemoveImageNumber.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { btnRemoveImageNumberActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridy = 1; pnlCtrlButtons.add(btnRemoveImageNumber, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; panContent.add(pnlCtrlButtons, gridBagConstraints); lblDescBildnummer.setText("Bildnummer"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panContent.add(lblDescBildnummer, gridBagConstraints); lblDescLagerort.setText("Lagerort"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 6; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panContent.add(lblDescLagerort, gridBagConstraints); lblDescAufnahmedatum.setText("Aufnahmedatum"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panContent.add(lblDescAufnahmedatum, gridBagConstraints); lblDescInfo.setText("Kommentar"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 7; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panContent.add(lblDescInfo, gridBagConstraints); lblDescBildtyp.setText("Bildtyp"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panContent.add(lblDescBildtyp, gridBagConstraints); lblDescSuchworte.setText("Suchworte"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panContent.add(lblDescSuchworte, gridBagConstraints); lstBildnummern.setModel(new javax.swing.AbstractListModel() { String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" }; @Override public int getSize() { return strings.length; } @Override public Object getElementAt(final int i) { return strings[i]; } }); lstBildnummern.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); org.jdesktop.beansbinding.ELProperty eLProperty = org.jdesktop.beansbinding.ELProperty.create( "${cidsBean.stadtbilder_arr}"); org.jdesktop.swingbinding.JListBinding jListBinding = org.jdesktop.swingbinding.SwingBindings .createJListBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, eLProperty, lstBildnummern); bindingGroup.addBinding(jListBinding); lstBildnummern.addListSelectionListener(new javax.swing.event.ListSelectionListener() { @Override public void valueChanged(final javax.swing.event.ListSelectionEvent evt) { lstBildnummernValueChanged(evt); } }); jScrollPane1.setViewportView(lstBildnummern); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panContent.add(jScrollPane1, gridBagConstraints); lstSuchworte.setModel(new javax.swing.AbstractListModel() { String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" }; @Override public int getSize() { return strings.length; } @Override public Object getElementAt(final int i) { return strings[i]; } }); eLProperty = org.jdesktop.beansbinding.ELProperty.create("${cidsBean.suchwort_arr}"); jListBinding = org.jdesktop.swingbinding.SwingBindings.createJListBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, eLProperty, lstSuchworte); bindingGroup.addBinding(jListBinding); jScrollPane2.setViewportView(lstSuchworte); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panContent.add(jScrollPane2, gridBagConstraints); org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.bildtyp}"), defaultBindableReferenceCombo2, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 5; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panContent.add(defaultBindableReferenceCombo2, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.lager}"), defaultBindableReferenceCombo3, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 6; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panContent.add(defaultBindableReferenceCombo3, gridBagConstraints); jTextArea1.setColumns(20); jTextArea1.setRows(5); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.kommentar}"), jTextArea1, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jScrollPane3.setViewportView(jTextArea1); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 7; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panContent.add(jScrollPane3, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.aufnahmedatum}"), jXDatePicker1, org.jdesktop.beansbinding.BeanProperty.create("date")); binding.setConverter(timeStampConverter); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panContent.add(jXDatePicker1, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; roundedPanel2.add(panContent, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel1.add(roundedPanel2, gridBagConstraints); roundedPanel3.setLayout(new java.awt.GridBagLayout()); semiRoundedPanel4.setBackground(new java.awt.Color(51, 51, 51)); semiRoundedPanel4.setLayout(new java.awt.FlowLayout()); jLabel2.setForeground(new java.awt.Color(255, 255, 255)); jLabel2.setText("Metainformationen"); semiRoundedPanel4.add(jLabel2); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.ipadx = 1; roundedPanel3.add(semiRoundedPanel4, gridBagConstraints); panDetails.setOpaque(false); panDetails.setLayout(new java.awt.GridBagLayout()); lblDescFilmart.setText("Filmart"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails.add(lblDescFilmart, gridBagConstraints); lblDescFotograf.setText("Fotograf"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails.add(lblDescFotograf, gridBagConstraints); lblDescAuftraggeber.setText("Auftraggeber"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails.add(lblDescAuftraggeber, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.auftraggeber}"), dbcAuftraggeber, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails.add(dbcAuftraggeber, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.fotograf}"), dbcFotograf, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails.add(dbcFotograf, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.filmart}"), dbcFilmart, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails.add(dbcFilmart, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; roundedPanel3.add(panDetails, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel1.add(roundedPanel3, gridBagConstraints); roundedPanel4.setLayout(new java.awt.GridBagLayout()); semiRoundedPanel5.setBackground(new java.awt.Color(51, 51, 51)); semiRoundedPanel5.setLayout(new java.awt.FlowLayout()); jLabel3.setForeground(new java.awt.Color(255, 255, 255)); jLabel3.setText("Ortbezogene Informationen"); semiRoundedPanel5.add(jLabel3); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.ipadx = 1; roundedPanel4.add(semiRoundedPanel5, gridBagConstraints); panDetails1.setOpaque(false); panDetails1.setLayout(new java.awt.GridBagLayout()); lblDescGeometrie.setText("Geometrie"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails1.add(lblDescGeometrie, gridBagConstraints); lblDescOrt.setText("Ort"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails1.add(lblDescOrt, gridBagConstraints); lblDescStrasse.setText("Straße"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails1.add(lblDescStrasse, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.ort}"), dbcOrt, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails1.add(dbcOrt, gridBagConstraints); jLabel7.setText("Hs.-Nr."); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails1.add(jLabel7, gridBagConstraints); defaultBindableJTextField1.setPreferredSize(new java.awt.Dimension(50, 19)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.hausnummer}"), defaultBindableJTextField1, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails1.add(defaultBindableJTextField1, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.geom_aus}"), lblGeomAus, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 2; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails1.add(lblGeomAus, gridBagConstraints); btnCombineGeometries.setIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/wizard.png"))); // NOI18N btnCombineGeometries.setText(org.openide.util.NbBundle.getMessage( Sb_stadtbildserieEditor.class, "VermessungRissEditor.btnCombineGeometries.text")); // NOI18N btnCombineGeometries.setToolTipText(org.openide.util.NbBundle.getMessage( Sb_stadtbildserieEditor.class, "VermessungRissEditor.btnCombineGeometries.toolTipText")); // NOI18N btnCombineGeometries.setEnabled(false); btnCombineGeometries.setFocusPainted(false); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails1.add(btnCombineGeometries, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.geom}"), defaultCismapGeometryComboBoxEditor1, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails1.add(defaultCismapGeometryComboBoxEditor1, gridBagConstraints); ((FastBindableReferenceCombo)bcbStrasse).setSorted(true); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.strasse}"), bcbStrasse, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails1.add(bcbStrasse, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; roundedPanel4.add(panDetails1, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel1.add(roundedPanel4, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridheight = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 3.0; jPanel3.add(jPanel1, gridBagConstraints); jPanel2.setOpaque(false); jPanel2.setLayout(new java.awt.GridBagLayout()); pnlVorschau.setPreferredSize(new java.awt.Dimension(140, 300)); pnlVorschau.setLayout(new java.awt.GridBagLayout()); semiRoundedPanel2.setBackground(new java.awt.Color(51, 51, 51)); semiRoundedPanel2.setLayout(new java.awt.FlowLayout()); lblVorschau.setForeground(new java.awt.Color(255, 255, 255)); lblVorschau.setText(org.openide.util.NbBundle.getMessage( Sb_stadtbildserieEditor.class, "MauerEditor.lblVorschau.text")); // NOI18N semiRoundedPanel2.add(lblVorschau); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; pnlVorschau.add(semiRoundedPanel2, gridBagConstraints); pnlFoto.setOpaque(false); pnlFoto.setLayout(new java.awt.CardLayout()); lblBusy.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); lblBusy.setMaximumSize(new java.awt.Dimension(140, 40)); lblBusy.setMinimumSize(new java.awt.Dimension(140, 60)); lblBusy.setPreferredSize(new java.awt.Dimension(140, 60)); pnlFoto.add(lblBusy, "busy"); jPanel4.setOpaque(false); jPanel4.setLayout(new java.awt.GridBagLayout()); lblPicture.setText(org.openide.util.NbBundle.getMessage( Sb_stadtbildserieEditor.class, "MauerEditor.lblPicture.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; jPanel4.add(lblPicture, gridBagConstraints); pnlFoto.add(jPanel4, "image"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; pnlVorschau.add(pnlFoto, gridBagConstraints); pnlCtrlBtn.setOpaque(false); pnlCtrlBtn.setPreferredSize(new java.awt.Dimension(100, 50)); pnlCtrlBtn.setLayout(new java.awt.GridBagLayout()); btnDownloadHighResImage.setIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/tools/gui/downloadmanager/res/download.png"))); // NOI18N btnDownloadHighResImage.setText(org.openide.util.NbBundle.getMessage( Sb_stadtbildserieEditor.class, "MauerEditor.btnPrevImg.text")); // NOI18N btnDownloadHighResImage.setBorder(null); btnDownloadHighResImage.setBorderPainted(false); btnDownloadHighResImage.setContentAreaFilled(false); btnDownloadHighResImage.setFocusPainted(false); btnDownloadHighResImage.setMaximumSize(new java.awt.Dimension(30, 30)); btnDownloadHighResImage.setMinimumSize(new java.awt.Dimension(30, 30)); btnDownloadHighResImage.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { btnDownloadHighResImageActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 0); pnlCtrlBtn.add(btnDownloadHighResImage, gridBagConstraints); btnPrevImg.setIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/arrow-left.png"))); // NOI18N btnPrevImg.setText(org.openide.util.NbBundle.getMessage( Sb_stadtbildserieEditor.class, "MauerEditor.btnPrevImg.text")); // NOI18N btnPrevImg.setBorder(null); btnPrevImg.setBorderPainted(false); btnPrevImg.setContentAreaFilled(false); btnPrevImg.setFocusPainted(false); btnPrevImg.setMaximumSize(new java.awt.Dimension(30, 30)); btnPrevImg.setMinimumSize(new java.awt.Dimension(30, 30)); btnPrevImg.setPreferredSize(new java.awt.Dimension(30, 30)); btnPrevImg.setPressedIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/arrow-left-pressed.png"))); // NOI18N btnPrevImg.setRolloverIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/arrow-left-selected.png"))); // NOI18N btnPrevImg.setSelectedIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/arrow-left-selected.png"))); // NOI18N btnPrevImg.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { btnPrevImgActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 10); pnlCtrlBtn.add(btnPrevImg, gridBagConstraints); btnNextImg.setIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/arrow-right.png"))); // NOI18N btnNextImg.setText(org.openide.util.NbBundle.getMessage( Sb_stadtbildserieEditor.class, "MauerEditor.btnNextImg.text")); // NOI18N btnNextImg.setBorder(null); btnNextImg.setBorderPainted(false); btnNextImg.setContentAreaFilled(false); btnNextImg.setFocusPainted(false); btnNextImg.setMaximumSize(new java.awt.Dimension(30, 30)); btnNextImg.setMinimumSize(new java.awt.Dimension(30, 30)); btnNextImg.setPreferredSize(new java.awt.Dimension(30, 30)); btnNextImg.setPressedIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/arrow-right-pressed.png"))); // NOI18N btnNextImg.setRolloverIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/arrow-right-selected.png"))); // NOI18N btnNextImg.setSelectedIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/arrow-right-selected.png"))); // NOI18N btnNextImg.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { btnNextImgActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 0); pnlCtrlBtn.add(btnNextImg, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; pnlCtrlBtn.add(filler1, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 4; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; pnlCtrlBtn.add(filler2, gridBagConstraints); tbtnIsPreviewImage.setIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/tick_32.png"))); // NOI18N tbtnIsPreviewImage.setSelected(true); tbtnIsPreviewImage.setBorderPainted(false); - tbtnIsPreviewImage.setDisabledIcon(new javax.swing.ImageIcon( - getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/tick.png"))); // NOI18N tbtnIsPreviewImage.setMaximumSize(new java.awt.Dimension(30, 30)); tbtnIsPreviewImage.setMinimumSize(new java.awt.Dimension(30, 30)); tbtnIsPreviewImage.setPreferredSize(new java.awt.Dimension(32, 32)); tbtnIsPreviewImage.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { tbtnIsPreviewImageActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); pnlCtrlBtn.add(tbtnIsPreviewImage, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; pnlVorschau.add(pnlCtrlBtn, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel2.add(pnlVorschau, gridBagConstraints); roundedPanel7.setLayout(new java.awt.GridBagLayout()); semiRoundedPanel8.setBackground(new java.awt.Color(51, 51, 51)); semiRoundedPanel8.setLayout(new java.awt.FlowLayout()); jLabel6.setForeground(new java.awt.Color(255, 255, 255)); jLabel6.setText("Karte"); semiRoundedPanel8.add(jLabel6); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.ipadx = 1; roundedPanel7.add(semiRoundedPanel8, gridBagConstraints); panDetails4.setOpaque(false); panDetails4.setLayout(new java.awt.GridBagLayout()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails4.add(pnlMap, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; roundedPanel7.add(panDetails4, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel2.add(roundedPanel7, gridBagConstraints); roundedPanel6.setLayout(new java.awt.GridBagLayout()); semiRoundedPanel7.setBackground(new java.awt.Color(51, 51, 51)); semiRoundedPanel7.setLayout(new java.awt.FlowLayout()); jLabel5.setForeground(new java.awt.Color(255, 255, 255)); jLabel5.setText("Prüfhinweis"); semiRoundedPanel7.add(jLabel5); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.ipadx = 1; roundedPanel6.add(semiRoundedPanel7, gridBagConstraints); panDetails3.setOpaque(false); panDetails3.setLayout(new java.awt.GridBagLayout()); chbPruefen.setText("Prüfen"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.pruefen}"), chbPruefen, org.jdesktop.beansbinding.BeanProperty.create("selected")); binding.setConverter(((DefaultBindableJCheckBox)chbPruefen).getConverter()); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails3.add(chbPruefen, gridBagConstraints); jTextArea2.setColumns(20); jTextArea2.setRows(5); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.pruefhinweis_von}"), jTextArea2, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jScrollPane4.setViewportView(jTextArea2); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails3.add(jScrollPane4, gridBagConstraints); jButton1.setText("Prüfhinweis speichern"); jButton1.setEnabled(false); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails3.add(jButton1, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; roundedPanel6.add(panDetails3, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel2.add(roundedPanel6, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.gridheight = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 3.0; jPanel3.add(jPanel2, gridBagConstraints); jScrollPane5.setViewportView(jPanel3); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; add(jScrollPane5, gridBagConstraints); bindingGroup.bind(); } // </editor-fold>//GEN-END:initComponents /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void lblPrintMouseClicked(final java.awt.event.MouseEvent evt) { //GEN-FIRST:event_lblPrintMouseClicked if ((evt != null) && !evt.isPopupTrigger()) { final CidsBean bean = cidsBean; if (bean != null) { final AbstractJasperReportPrint jp = new StadtbildJasperReportPrint(REPORT_FILE, bean); jp.print(); } } } //GEN-LAST:event_lblPrintMouseClicked /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void btnPrevImgActionPerformed(final java.awt.event.ActionEvent evt) { //GEN-FIRST:event_btnPrevImgActionPerformed lstBildnummern.setSelectedIndex(lstBildnummern.getSelectedIndex() - 1); } //GEN-LAST:event_btnPrevImgActionPerformed /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void btnNextImgActionPerformed(final java.awt.event.ActionEvent evt) { //GEN-FIRST:event_btnNextImgActionPerformed lstBildnummern.setSelectedIndex(lstBildnummern.getSelectedIndex() + 1); } //GEN-LAST:event_btnNextImgActionPerformed /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void btnDownloadHighResImageActionPerformed(final java.awt.event.ActionEvent evt) { //GEN-FIRST:event_btnDownloadHighResImageActionPerformed if (DownloadManagerDialog.showAskingForUserTitle( this)) { final String jobname = DownloadManagerDialog.getJobname(); final String imageNumber = (String)((CidsBean)lstBildnummern.getSelectedValue()).getProperty("bildnummer"); DownloadManager.instance() .add( new TifferDownload( jobname, "Stadtbild " + imageNumber, "stadtbild_" + imageNumber, lstBildnummern.getSelectedValue().toString(), "1")); } } //GEN-LAST:event_btnDownloadHighResImageActionPerformed /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void lstBildnummernValueChanged(final javax.swing.event.ListSelectionEvent evt) { //GEN-FIRST:event_lstBildnummernValueChanged if (!evt.getValueIsAdjusting()) { if (!lstBildnummern.isSelectionEmpty()) { final String imageNumber = lstBildnummern.getSelectedValue().toString(); new CheckAccessibilityOfHighResImage(imageNumber).execute(); loadFoto(); final boolean isPreviewImage = cidsBean.getProperty("vorschaubild") .equals(lstBildnummern.getSelectedValue()); tbtnIsPreviewImage.setSelected(isPreviewImage); tbtnIsPreviewImage.setEnabled(!isPreviewImage); lstBildnummern.ensureIndexIsVisible(lstBildnummern.getSelectedIndex()); } else { tbtnIsPreviewImage.setSelected(false); tbtnIsPreviewImage.setEnabled(false); } } } //GEN-LAST:event_lstBildnummernValueChanged /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void tbtnIsPreviewImageActionPerformed(final java.awt.event.ActionEvent evt) { //GEN-FIRST:event_tbtnIsPreviewImageActionPerformed if (tbtnIsPreviewImage.isSelected()) { try { cidsBean.setProperty("vorschaubild", lstBildnummern.getSelectedValue()); } catch (Exception e) { LOG.error("Error while setting the preview image of the CidsBean", e); } } } //GEN-LAST:event_tbtnIsPreviewImageActionPerformed /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void btnAddImageNumberActionPerformed(final java.awt.event.ActionEvent evt) { //GEN-FIRST:event_btnAddImageNumberActionPerformed } //GEN-LAST:event_btnAddImageNumberActionPerformed /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void btnRemoveImageNumberActionPerformed(final java.awt.event.ActionEvent evt) { //GEN-FIRST:event_btnRemoveImageNumberActionPerformed final Object selection = lstBildnummern.getSelectedValue(); if ((selection != null) && (selection instanceof CidsBean)) { final CidsBean cidesBeanToRemove = (CidsBean)selection; final int answer = JOptionPane.showConfirmDialog( StaticSwingTools.getParentFrame(this), "Soll die Bildnummer wirklich entfernt werden?", "Bildernummern entfernen", JOptionPane.YES_NO_OPTION); if (answer == JOptionPane.YES_OPTION) { final int modelSize = lstBildnummern.getModel().getSize(); if (modelSize >= 2) { final int oldIndex = lstBildnummern.getSelectedIndex(); // select the second or second last element as new selected element final int newIndex = (oldIndex == 0) ? 1 : (oldIndex - 1); lstBildnummern.setSelectedIndex(newIndex); } else { image = null; lblPicture.setIcon(FOLDER_ICON); } try { final List<CidsBean> fotos = cidsBean.getBeanCollectionProperty("stadtbilder_arr"); if (fotos != null) { fotos.remove(cidesBeanToRemove); } IMAGE_CACHE.remove(cidesBeanToRemove.toString()); } catch (Exception e) { LOG.error(e, e); final ErrorInfo ei = new ErrorInfo( "Fehler", "Beim Entfernen der Bildernummern ist ein Fehler aufgetreten", null, null, e, Level.SEVERE, null); JXErrorPane.showDialog(StaticSwingTools.getParentFrame(this), ei); } } } } //GEN-LAST:event_btnRemoveImageNumberActionPerformed /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void btnAddSuchwortActionPerformed(final java.awt.event.ActionEvent evt) { //GEN-FIRST:event_btnAddSuchwortActionPerformed // TODO add your handling code here: } //GEN-LAST:event_btnAddSuchwortActionPerformed /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void btnRemoveSuchwortActionPerformed(final java.awt.event.ActionEvent evt) { //GEN-FIRST:event_btnRemoveSuchwortActionPerformed final Object[] selection = lstSuchworte.getSelectedValues(); if ((selection != null) && (selection.length > 0)) { final int answer = JOptionPane.showConfirmDialog( StaticSwingTools.getParentFrame(this), "Sollen die Suchwörter wirklich entfernt werden?", "Suchwörter entfernen", JOptionPane.YES_NO_OPTION); if (answer == JOptionPane.YES_OPTION) { try { final List<Object> removeList = Arrays.asList(selection); final List<CidsBean> suchwoerter = cidsBean.getBeanCollectionProperty("suchwort_arr"); if (suchwoerter != null) { suchwoerter.removeAll(removeList); } } catch (Exception e) { LOG.error(e, e); final ErrorInfo ei = new ErrorInfo( "Fehler", "Beim Entfernen der Suchwörter ist ein Fehler aufgetreten", null, null, e, Level.SEVERE, null); JXErrorPane.showDialog(StaticSwingTools.getParentFrame(this), ei); } } } } //GEN-LAST:event_btnRemoveSuchwortActionPerformed /** * DOCUMENT ME! * * @return DOCUMENT ME! */ @Override public CidsBean getCidsBean() { return cidsBean; } /** * DOCUMENT ME! * * @param cidsBean DOCUMENT ME! */ @Override public void setCidsBean(final CidsBean cidsBean) { bindingGroup.unbind(); if (cidsBean != null) { DefaultCustomObjectEditor.setMetaClassInformationToMetaClassStoreComponentsInBindingGroup( bindingGroup, cidsBean); this.cidsBean = cidsBean; bindingGroup.bind(); lstBildnummern.setSelectedValue(cidsBean.getProperty("vorschaubild"), true); initMap(); final String obj = String.valueOf(cidsBean.getProperty("bildnummer")); // lblPicture.setPictureURL(StaticProperties.ARCHIVAR_URL_PREFIX + obj + StaticProperties.ARCHIVAR_URL_SUFFIX); } } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ @Override public String getTitle() { return title; } /** * DOCUMENT ME! * * @param title DOCUMENT ME! */ @Override public void setTitle(final String title) { this.title = "Stadtbild " + title; lblTitle.setText(this.title); } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ @Override public JComponent getTitleComponent() { return panTitle; } /** * DOCUMENT ME! */ @Override public void dispose() { bindingGroup.unbind(); } /** * DOCUMENT ME! */ private void loadFoto() { final Object stadtbild = lstBildnummern.getSelectedValue(); if (fotoCidsBean != null) { fotoCidsBean.removePropertyChangeListener(listRepaintListener); } if (stadtbild instanceof CidsBean) { fotoCidsBean = (CidsBean)stadtbild; fotoCidsBean.addPropertyChangeListener(listRepaintListener); final String bildnummer = (String)fotoCidsBean.getProperty("bildnummer"); boolean cacheHit = false; if (bildnummer != null) { final SoftReference<BufferedImage> cachedImageRef = IMAGE_CACHE.get(bildnummer); if (cachedImageRef != null) { final BufferedImage cachedImage = cachedImageRef.get(); if (cachedImage != null) { showWait(true); cacheHit = true; image = cachedImage; resizeListenerEnabled = true; timer.restart(); } } if (!cacheHit) { new Sb_stadtbildserieEditor.LoadSelectedImageWorker(bildnummer).execute(); } } } else { image = null; lblPicture.setIcon(FOLDER_ICON); } } /** * DOCUMENT ME! */ public void defineButtonStatus() { final int selectedIdx = lstBildnummern.getSelectedIndex(); btnPrevImg.setEnabled(selectedIdx > 0); btnNextImg.setEnabled((selectedIdx < (lstBildnummern.getModel().getSize() - 1)) && (selectedIdx > -1)); } /** * DOCUMENT ME! * * @param wait DOCUMENT ME! */ private void showWait(final boolean wait) { if (wait) { if (!lblBusy.isBusy()) { ((CardLayout)pnlFoto.getLayout()).show(pnlFoto, "busy"); // lblPicture.setIcon(null); lblBusy.setBusy(true); btnPrevImg.setEnabled(false); btnNextImg.setEnabled(false); } } else { ((CardLayout)pnlFoto.getLayout()).show(pnlFoto, "image"); lblBusy.setBusy(false); defineButtonStatus(); } } /** * DOCUMENT ME! * * @param tooltip DOCUMENT ME! */ private void indicateError(final String tooltip) { lblPicture.setIcon(ERROR_ICON); lblPicture.setText("Fehler beim Übertragen des Bildes!"); lblPicture.setToolTipText(tooltip); } /** * DOCUMENT ME! * * @param args DOCUMENT ME! * * @throws Exception DOCUMENT ME! */ public static void main(final String[] args) throws Exception { DevelopmentTools.createEditorInFrameFromRMIConnectionOnLocalhost( "WUNDA_BLAU", "Administratoren", "admin", "kif", "sb_stadtbildserie", 161078, // id 161078 high res, id 18 = interval 1280, 1024); } /** * DOCUMENT ME! */ private void initMap() { if (cidsBean != null) { final Object geoObj = cidsBean.getProperty("geom"); if (geoObj instanceof Geometry) { final Geometry pureGeom = CrsTransformer.transformToGivenCrs((Geometry)geoObj, AlkisConstants.COMMONS.SRS_SERVICE); if (LOG.isDebugEnabled()) { LOG.debug("ALKISConstatns.Commons.GeoBUffer: " + AlkisConstants.COMMONS.GEO_BUFFER); } final XBoundingBox box = new XBoundingBox(pureGeom.getEnvelope().buffer( AlkisConstants.COMMONS.GEO_BUFFER)); final double diagonalLength = Math.sqrt((box.getWidth() * box.getWidth()) + (box.getHeight() * box.getHeight())); if (LOG.isDebugEnabled()) { LOG.debug("Buffer for map: " + diagonalLength); } final XBoundingBox bufferedBox = new XBoundingBox(box.getGeometry().buffer(diagonalLength)); final Runnable mapRunnable = new Runnable() { @Override public void run() { final ActiveLayerModel mappingModel = new ActiveLayerModel(); mappingModel.setSrs(AlkisConstants.COMMONS.SRS_SERVICE); mappingModel.addHome(new XBoundingBox( bufferedBox.getX1(), bufferedBox.getY1(), bufferedBox.getX2(), bufferedBox.getY2(), AlkisConstants.COMMONS.SRS_SERVICE, true)); final SimpleWMS swms = new SimpleWMS(new SimpleWmsGetMapUrl( AlkisConstants.COMMONS.MAP_CALL_STRING)); swms.setName("Mauer"); final StyledFeature dsf = new DefaultStyledFeature(); dsf.setGeometry(pureGeom); dsf.setFillingPaint(new Color(1, 0, 0, 0.5f)); dsf.setLineWidth(3); dsf.setLinePaint(new Color(1, 0, 0, 1f)); // add the raster layer to the model mappingModel.addLayer(swms); // set the model map.setMappingModel(mappingModel); // initial positioning of the map final int duration = map.getAnimationDuration(); map.setAnimationDuration(0); map.gotoInitialBoundingBox(); // interaction mode map.setInteractionMode(MappingComponent.ZOOM); // finally when all configurations are done ... map.unlock(); map.addCustomInputListener("MUTE", new PBasicInputEventHandler() { @Override public void mouseClicked(final PInputEvent evt) { if (evt.getClickCount() > 1) { final CidsBean bean = cidsBean; ObjectRendererUtils.switchToCismapMap(); ObjectRendererUtils.addBeanGeomAsFeatureToCismapMap(bean, false); } } }); map.setInteractionMode("MUTE"); map.getFeatureCollection().addFeature(dsf); map.setAnimationDuration(duration); } }; if (EventQueue.isDispatchThread()) { mapRunnable.run(); } else { EventQueue.invokeLater(mapRunnable); } } } } //~ Inner Classes ---------------------------------------------------------- /** * DOCUMENT ME! * * @version $Revision$, $Date$ */ final class ImageResizeWorker extends SwingWorker<ImageIcon, Void> { //~ Constructors ------------------------------------------------------- /** * Creates a new ImageResizeWorker object. */ public ImageResizeWorker() { if (image != null) { lblPicture.setText("Wird neu skaliert..."); } } //~ Methods ------------------------------------------------------------ @Override protected ImageIcon doInBackground() throws Exception { if (image != null) { final ImageIcon result = new ImageIcon(adjustScale(image, pnlFoto, 20, 20)); return result; } else { return null; } } @Override protected void done() { if (!isCancelled()) { try { resizeListenerEnabled = false; final ImageIcon result = get(); lblPicture.setIcon(result); lblPicture.setText(""); lblPicture.setToolTipText(null); } catch (InterruptedException ex) { LOG.warn(ex, ex); } catch (ExecutionException ex) { LOG.error(ex, ex); lblPicture.setText("Fehler beim Skalieren!"); } finally { showWait(false); if (currentResizeWorker == this) { currentResizeWorker = null; } resizeListenerEnabled = true; } } } } /** * DOCUMENT ME! * * @version $Revision$, $Date$ */ final class LoadSelectedImageWorker extends SwingWorker<BufferedImage, Void> { //~ Instance fields ---------------------------------------------------- private final String bildnummer; //~ Constructors ------------------------------------------------------- /** * Creates a new LoadSelectedImageWorker object. * * @param toLoad DOCUMENT ME! */ public LoadSelectedImageWorker(final String toLoad) { this.bildnummer = toLoad; lblPicture.setText(""); lblPicture.setToolTipText(null); showWait(true); } //~ Methods ------------------------------------------------------------ @Override protected BufferedImage doInBackground() throws Exception { if ((bildnummer != null) && (bildnummer.length() > 0)) { return downloadImageFromUrl(bildnummer); } return null; } /** * DOCUMENT ME! * * @param bildnummer DOCUMENT ME! * * @return DOCUMENT ME! */ private BufferedImage downloadImageFromUrl(final String bildnummer) { final URL urlLowResImage = TifferDownload.getURLOfLowResPicture(bildnummer); if (urlLowResImage != null) { InputStream is = null; try { is = WebAccessManager.getInstance().doRequest(urlLowResImage); final BufferedImage img = ImageIO.read(is); return img; } catch (Exception ex) { LOG.warn("Image could not be loaded.", ex); } finally { if (is != null) { try { is.close(); } catch (IOException ex) { LOG.warn("Error during closing InputStream.", ex); } } } } return null; } @Override protected void done() { try { image = get(); if (image != null) { IMAGE_CACHE.put(bildnummer, new SoftReference<BufferedImage>(image)); resizeListenerEnabled = true; timer.restart(); } else { indicateError("Bild konnte nicht geladen werden."); } } catch (InterruptedException ex) { image = null; LOG.warn(ex, ex); } catch (ExecutionException ex) { image = null; LOG.error(ex, ex); indicateError(ex.getMessage()); } finally { if (image == null) { showWait(false); } } } } /** * DOCUMENT ME! * * @version $Revision$, $Date$ */ final class CheckAccessibilityOfHighResImage extends SwingWorker<Boolean, Void> { //~ Instance fields ---------------------------------------------------- private final String imageNumber; //~ Constructors ------------------------------------------------------- /** * Creates a new CheckAccessibilityOfHighResImage object. * * @param imageNumber DOCUMENT ME! */ public CheckAccessibilityOfHighResImage(final String imageNumber) { this.imageNumber = imageNumber; btnDownloadHighResImage.setEnabled(false); } //~ Methods ------------------------------------------------------------ @Override protected Boolean doInBackground() throws Exception { return TifferDownload.getFormatOfHighResPicture(imageNumber) != null; } @Override protected void done() { try { final boolean accessible = get(); btnDownloadHighResImage.setEnabled(accessible); } catch (InterruptedException ex) { LOG.warn(ex, ex); } catch (ExecutionException ex) { LOG.warn(ex, ex); } } } }
true
true
private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; bindingGroup = new org.jdesktop.beansbinding.BindingGroup(); sqlDateToUtilDateConverter = new de.cismet.cids.editors.converters.SqlDateToUtilDateConverter(); sqlDateToStringConverter = new de.cismet.cids.custom.objectrenderer.converter.SQLDateToStringConverter(); panTitle = new javax.swing.JPanel(); panTitleString = new javax.swing.JPanel(); lblTitle = new javax.swing.JLabel(); panPrintButton = new javax.swing.JPanel(); lblPrint = new javax.swing.JLabel(); roundedPanel1 = new de.cismet.tools.gui.RoundedPanel(); semiRoundedPanel1 = new de.cismet.tools.gui.SemiRoundedPanel(); jScrollPane5 = new javax.swing.JScrollPane(); jPanel3 = new javax.swing.JPanel(); jPanel1 = new javax.swing.JPanel(); roundedPanel2 = new de.cismet.tools.gui.RoundedPanel(); semiRoundedPanel3 = new de.cismet.tools.gui.SemiRoundedPanel(); jLabel1 = new javax.swing.JLabel(); panContent = new RoundedPanel(); pnlCtrlButtons1 = new javax.swing.JPanel(); btnAddSuchwort = new javax.swing.JButton(); btnRemoveSuchwort = new javax.swing.JButton(); pnlCtrlButtons = new javax.swing.JPanel(); btnAddImageNumber = new javax.swing.JButton(); btnRemoveImageNumber = new javax.swing.JButton(); lblDescBildnummer = new javax.swing.JLabel(); lblDescLagerort = new javax.swing.JLabel(); lblDescAufnahmedatum = new javax.swing.JLabel(); lblDescInfo = new javax.swing.JLabel(); lblDescBildtyp = new javax.swing.JLabel(); lblDescSuchworte = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); lstBildnummern = new javax.swing.JList(); jScrollPane2 = new javax.swing.JScrollPane(); lstSuchworte = new javax.swing.JList(); defaultBindableReferenceCombo2 = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); defaultBindableReferenceCombo3 = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); jScrollPane3 = new javax.swing.JScrollPane(); jTextArea1 = new javax.swing.JTextArea(); jXDatePicker1 = new org.jdesktop.swingx.JXDatePicker(); roundedPanel3 = new de.cismet.tools.gui.RoundedPanel(); semiRoundedPanel4 = new de.cismet.tools.gui.SemiRoundedPanel(); jLabel2 = new javax.swing.JLabel(); panDetails = new RoundedPanel(); lblDescFilmart = new javax.swing.JLabel(); lblDescFotograf = new javax.swing.JLabel(); lblDescAuftraggeber = new javax.swing.JLabel(); dbcAuftraggeber = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); dbcFotograf = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); dbcFilmart = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); roundedPanel4 = new de.cismet.tools.gui.RoundedPanel(); semiRoundedPanel5 = new de.cismet.tools.gui.SemiRoundedPanel(); jLabel3 = new javax.swing.JLabel(); panDetails1 = new RoundedPanel(); lblDescGeometrie = new javax.swing.JLabel(); lblDescOrt = new javax.swing.JLabel(); lblDescStrasse = new javax.swing.JLabel(); dbcOrt = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); jLabel7 = new javax.swing.JLabel(); defaultBindableJTextField1 = new de.cismet.cids.editors.DefaultBindableJTextField(); lblGeomAus = new javax.swing.JLabel(); btnCombineGeometries = new javax.swing.JButton(); defaultCismapGeometryComboBoxEditor1 = new de.cismet.cismap.cids.geometryeditor.DefaultCismapGeometryComboBoxEditor(); bcbStrasse = new FastBindableReferenceCombo( "select s.strassenschluessel,s.name from strasse s", strasseFormater, new String[] { "NAME" }); jPanel2 = new javax.swing.JPanel(); pnlVorschau = new de.cismet.tools.gui.RoundedPanel(); semiRoundedPanel2 = new de.cismet.tools.gui.SemiRoundedPanel(); lblVorschau = new javax.swing.JLabel(); pnlFoto = new javax.swing.JPanel(); lblBusy = new org.jdesktop.swingx.JXBusyLabel(new Dimension(75, 75)); jPanel4 = new javax.swing.JPanel(); lblPicture = new javax.swing.JLabel(); pnlCtrlBtn = new javax.swing.JPanel(); btnDownloadHighResImage = new javax.swing.JButton(); btnPrevImg = new javax.swing.JButton(); btnNextImg = new javax.swing.JButton(); filler1 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0), new java.awt.Dimension(32767, 0)); filler2 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0), new java.awt.Dimension(32767, 0)); tbtnIsPreviewImage = new javax.swing.JToggleButton(); roundedPanel7 = new de.cismet.tools.gui.RoundedPanel(); semiRoundedPanel8 = new de.cismet.tools.gui.SemiRoundedPanel(); jLabel6 = new javax.swing.JLabel(); panDetails4 = new RoundedPanel(); pnlMap = new javax.swing.JPanel(); roundedPanel6 = new de.cismet.tools.gui.RoundedPanel(); semiRoundedPanel7 = new de.cismet.tools.gui.SemiRoundedPanel(); jLabel5 = new javax.swing.JLabel(); panDetails3 = new RoundedPanel(); chbPruefen = new DefaultBindableJCheckBox(); jScrollPane4 = new javax.swing.JScrollPane(); jTextArea2 = new javax.swing.JTextArea(); jButton1 = new javax.swing.JButton(); panTitle.setOpaque(false); panTitle.setLayout(new java.awt.BorderLayout()); panTitleString.setOpaque(false); panTitleString.setLayout(new java.awt.GridBagLayout()); lblTitle.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N lblTitle.setForeground(new java.awt.Color(255, 255, 255)); lblTitle.setText("TITLE"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); panTitleString.add(lblTitle, gridBagConstraints); panTitle.add(panTitleString, java.awt.BorderLayout.CENTER); panPrintButton.setOpaque(false); panPrintButton.setLayout(new java.awt.GridBagLayout()); lblPrint.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/icons/printer.png"))); // NOI18N lblPrint.addMouseListener(new java.awt.event.MouseAdapter() { @Override public void mouseClicked(final java.awt.event.MouseEvent evt) { lblPrintMouseClicked(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); panPrintButton.add(lblPrint, gridBagConstraints); panTitle.add(panPrintButton, java.awt.BorderLayout.EAST); roundedPanel1.add(semiRoundedPanel1, java.awt.BorderLayout.CENTER); setOpaque(false); setLayout(new java.awt.GridBagLayout()); jScrollPane5.setBorder(null); jScrollPane5.setOpaque(false); jPanel3.setOpaque(false); jPanel3.setLayout(new java.awt.GridBagLayout()); jPanel1.setOpaque(false); jPanel1.setLayout(new java.awt.GridBagLayout()); roundedPanel2.setLayout(new java.awt.GridBagLayout()); semiRoundedPanel3.setBackground(new java.awt.Color(51, 51, 51)); semiRoundedPanel3.setLayout(new java.awt.FlowLayout()); jLabel1.setForeground(new java.awt.Color(255, 255, 255)); jLabel1.setText("Allgemeine Informationen"); semiRoundedPanel3.add(jLabel1); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.ipadx = 1; roundedPanel2.add(semiRoundedPanel3, gridBagConstraints); panContent.setOpaque(false); panContent.setLayout(new java.awt.GridBagLayout()); pnlCtrlButtons1.setOpaque(false); pnlCtrlButtons1.setLayout(new java.awt.GridBagLayout()); btnAddSuchwort.setIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit_add_mini.png"))); // NOI18N btnAddSuchwort.setText(org.openide.util.NbBundle.getMessage( Sb_stadtbildserieEditor.class, "MauerEditor.btnAddImg.text")); // NOI18N btnAddSuchwort.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { btnAddSuchwortActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlCtrlButtons1.add(btnAddSuchwort, gridBagConstraints); btnRemoveSuchwort.setIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit_remove_mini.png"))); // NOI18N btnRemoveSuchwort.setText(org.openide.util.NbBundle.getMessage( Sb_stadtbildserieEditor.class, "MauerEditor.btnRemoveImg.text")); // NOI18N btnRemoveSuchwort.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { btnRemoveSuchwortActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridy = 1; pnlCtrlButtons1.add(btnRemoveSuchwort, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; panContent.add(pnlCtrlButtons1, gridBagConstraints); pnlCtrlButtons.setOpaque(false); pnlCtrlButtons.setLayout(new java.awt.GridBagLayout()); btnAddImageNumber.setIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit_add_mini.png"))); // NOI18N btnAddImageNumber.setText(org.openide.util.NbBundle.getMessage( Sb_stadtbildserieEditor.class, "MauerEditor.btnAddImg.text")); // NOI18N btnAddImageNumber.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { btnAddImageNumberActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlCtrlButtons.add(btnAddImageNumber, gridBagConstraints); btnRemoveImageNumber.setIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit_remove_mini.png"))); // NOI18N btnRemoveImageNumber.setText(org.openide.util.NbBundle.getMessage( Sb_stadtbildserieEditor.class, "MauerEditor.btnRemoveImg.text")); // NOI18N btnRemoveImageNumber.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { btnRemoveImageNumberActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridy = 1; pnlCtrlButtons.add(btnRemoveImageNumber, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; panContent.add(pnlCtrlButtons, gridBagConstraints); lblDescBildnummer.setText("Bildnummer"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panContent.add(lblDescBildnummer, gridBagConstraints); lblDescLagerort.setText("Lagerort"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 6; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panContent.add(lblDescLagerort, gridBagConstraints); lblDescAufnahmedatum.setText("Aufnahmedatum"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panContent.add(lblDescAufnahmedatum, gridBagConstraints); lblDescInfo.setText("Kommentar"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 7; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panContent.add(lblDescInfo, gridBagConstraints); lblDescBildtyp.setText("Bildtyp"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panContent.add(lblDescBildtyp, gridBagConstraints); lblDescSuchworte.setText("Suchworte"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panContent.add(lblDescSuchworte, gridBagConstraints); lstBildnummern.setModel(new javax.swing.AbstractListModel() { String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" }; @Override public int getSize() { return strings.length; } @Override public Object getElementAt(final int i) { return strings[i]; } }); lstBildnummern.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); org.jdesktop.beansbinding.ELProperty eLProperty = org.jdesktop.beansbinding.ELProperty.create( "${cidsBean.stadtbilder_arr}"); org.jdesktop.swingbinding.JListBinding jListBinding = org.jdesktop.swingbinding.SwingBindings .createJListBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, eLProperty, lstBildnummern); bindingGroup.addBinding(jListBinding); lstBildnummern.addListSelectionListener(new javax.swing.event.ListSelectionListener() { @Override public void valueChanged(final javax.swing.event.ListSelectionEvent evt) { lstBildnummernValueChanged(evt); } }); jScrollPane1.setViewportView(lstBildnummern); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panContent.add(jScrollPane1, gridBagConstraints); lstSuchworte.setModel(new javax.swing.AbstractListModel() { String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" }; @Override public int getSize() { return strings.length; } @Override public Object getElementAt(final int i) { return strings[i]; } }); eLProperty = org.jdesktop.beansbinding.ELProperty.create("${cidsBean.suchwort_arr}"); jListBinding = org.jdesktop.swingbinding.SwingBindings.createJListBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, eLProperty, lstSuchworte); bindingGroup.addBinding(jListBinding); jScrollPane2.setViewportView(lstSuchworte); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panContent.add(jScrollPane2, gridBagConstraints); org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.bildtyp}"), defaultBindableReferenceCombo2, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 5; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panContent.add(defaultBindableReferenceCombo2, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.lager}"), defaultBindableReferenceCombo3, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 6; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panContent.add(defaultBindableReferenceCombo3, gridBagConstraints); jTextArea1.setColumns(20); jTextArea1.setRows(5); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.kommentar}"), jTextArea1, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jScrollPane3.setViewportView(jTextArea1); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 7; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panContent.add(jScrollPane3, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.aufnahmedatum}"), jXDatePicker1, org.jdesktop.beansbinding.BeanProperty.create("date")); binding.setConverter(timeStampConverter); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panContent.add(jXDatePicker1, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; roundedPanel2.add(panContent, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel1.add(roundedPanel2, gridBagConstraints); roundedPanel3.setLayout(new java.awt.GridBagLayout()); semiRoundedPanel4.setBackground(new java.awt.Color(51, 51, 51)); semiRoundedPanel4.setLayout(new java.awt.FlowLayout()); jLabel2.setForeground(new java.awt.Color(255, 255, 255)); jLabel2.setText("Metainformationen"); semiRoundedPanel4.add(jLabel2); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.ipadx = 1; roundedPanel3.add(semiRoundedPanel4, gridBagConstraints); panDetails.setOpaque(false); panDetails.setLayout(new java.awt.GridBagLayout()); lblDescFilmart.setText("Filmart"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails.add(lblDescFilmart, gridBagConstraints); lblDescFotograf.setText("Fotograf"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails.add(lblDescFotograf, gridBagConstraints); lblDescAuftraggeber.setText("Auftraggeber"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails.add(lblDescAuftraggeber, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.auftraggeber}"), dbcAuftraggeber, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails.add(dbcAuftraggeber, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.fotograf}"), dbcFotograf, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails.add(dbcFotograf, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.filmart}"), dbcFilmart, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails.add(dbcFilmart, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; roundedPanel3.add(panDetails, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel1.add(roundedPanel3, gridBagConstraints); roundedPanel4.setLayout(new java.awt.GridBagLayout()); semiRoundedPanel5.setBackground(new java.awt.Color(51, 51, 51)); semiRoundedPanel5.setLayout(new java.awt.FlowLayout()); jLabel3.setForeground(new java.awt.Color(255, 255, 255)); jLabel3.setText("Ortbezogene Informationen"); semiRoundedPanel5.add(jLabel3); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.ipadx = 1; roundedPanel4.add(semiRoundedPanel5, gridBagConstraints); panDetails1.setOpaque(false); panDetails1.setLayout(new java.awt.GridBagLayout()); lblDescGeometrie.setText("Geometrie"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails1.add(lblDescGeometrie, gridBagConstraints); lblDescOrt.setText("Ort"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails1.add(lblDescOrt, gridBagConstraints); lblDescStrasse.setText("Straße"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails1.add(lblDescStrasse, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.ort}"), dbcOrt, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails1.add(dbcOrt, gridBagConstraints); jLabel7.setText("Hs.-Nr."); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails1.add(jLabel7, gridBagConstraints); defaultBindableJTextField1.setPreferredSize(new java.awt.Dimension(50, 19)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.hausnummer}"), defaultBindableJTextField1, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails1.add(defaultBindableJTextField1, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.geom_aus}"), lblGeomAus, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 2; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails1.add(lblGeomAus, gridBagConstraints); btnCombineGeometries.setIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/wizard.png"))); // NOI18N btnCombineGeometries.setText(org.openide.util.NbBundle.getMessage( Sb_stadtbildserieEditor.class, "VermessungRissEditor.btnCombineGeometries.text")); // NOI18N btnCombineGeometries.setToolTipText(org.openide.util.NbBundle.getMessage( Sb_stadtbildserieEditor.class, "VermessungRissEditor.btnCombineGeometries.toolTipText")); // NOI18N btnCombineGeometries.setEnabled(false); btnCombineGeometries.setFocusPainted(false); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails1.add(btnCombineGeometries, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.geom}"), defaultCismapGeometryComboBoxEditor1, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails1.add(defaultCismapGeometryComboBoxEditor1, gridBagConstraints); ((FastBindableReferenceCombo)bcbStrasse).setSorted(true); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.strasse}"), bcbStrasse, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails1.add(bcbStrasse, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; roundedPanel4.add(panDetails1, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel1.add(roundedPanel4, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridheight = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 3.0; jPanel3.add(jPanel1, gridBagConstraints); jPanel2.setOpaque(false); jPanel2.setLayout(new java.awt.GridBagLayout()); pnlVorschau.setPreferredSize(new java.awt.Dimension(140, 300)); pnlVorschau.setLayout(new java.awt.GridBagLayout()); semiRoundedPanel2.setBackground(new java.awt.Color(51, 51, 51)); semiRoundedPanel2.setLayout(new java.awt.FlowLayout()); lblVorschau.setForeground(new java.awt.Color(255, 255, 255)); lblVorschau.setText(org.openide.util.NbBundle.getMessage( Sb_stadtbildserieEditor.class, "MauerEditor.lblVorschau.text")); // NOI18N semiRoundedPanel2.add(lblVorschau); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; pnlVorschau.add(semiRoundedPanel2, gridBagConstraints); pnlFoto.setOpaque(false); pnlFoto.setLayout(new java.awt.CardLayout()); lblBusy.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); lblBusy.setMaximumSize(new java.awt.Dimension(140, 40)); lblBusy.setMinimumSize(new java.awt.Dimension(140, 60)); lblBusy.setPreferredSize(new java.awt.Dimension(140, 60)); pnlFoto.add(lblBusy, "busy"); jPanel4.setOpaque(false); jPanel4.setLayout(new java.awt.GridBagLayout()); lblPicture.setText(org.openide.util.NbBundle.getMessage( Sb_stadtbildserieEditor.class, "MauerEditor.lblPicture.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; jPanel4.add(lblPicture, gridBagConstraints); pnlFoto.add(jPanel4, "image"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; pnlVorschau.add(pnlFoto, gridBagConstraints); pnlCtrlBtn.setOpaque(false); pnlCtrlBtn.setPreferredSize(new java.awt.Dimension(100, 50)); pnlCtrlBtn.setLayout(new java.awt.GridBagLayout()); btnDownloadHighResImage.setIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/tools/gui/downloadmanager/res/download.png"))); // NOI18N btnDownloadHighResImage.setText(org.openide.util.NbBundle.getMessage( Sb_stadtbildserieEditor.class, "MauerEditor.btnPrevImg.text")); // NOI18N btnDownloadHighResImage.setBorder(null); btnDownloadHighResImage.setBorderPainted(false); btnDownloadHighResImage.setContentAreaFilled(false); btnDownloadHighResImage.setFocusPainted(false); btnDownloadHighResImage.setMaximumSize(new java.awt.Dimension(30, 30)); btnDownloadHighResImage.setMinimumSize(new java.awt.Dimension(30, 30)); btnDownloadHighResImage.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { btnDownloadHighResImageActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 0); pnlCtrlBtn.add(btnDownloadHighResImage, gridBagConstraints); btnPrevImg.setIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/arrow-left.png"))); // NOI18N btnPrevImg.setText(org.openide.util.NbBundle.getMessage( Sb_stadtbildserieEditor.class, "MauerEditor.btnPrevImg.text")); // NOI18N btnPrevImg.setBorder(null); btnPrevImg.setBorderPainted(false); btnPrevImg.setContentAreaFilled(false); btnPrevImg.setFocusPainted(false); btnPrevImg.setMaximumSize(new java.awt.Dimension(30, 30)); btnPrevImg.setMinimumSize(new java.awt.Dimension(30, 30)); btnPrevImg.setPreferredSize(new java.awt.Dimension(30, 30)); btnPrevImg.setPressedIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/arrow-left-pressed.png"))); // NOI18N btnPrevImg.setRolloverIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/arrow-left-selected.png"))); // NOI18N btnPrevImg.setSelectedIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/arrow-left-selected.png"))); // NOI18N btnPrevImg.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { btnPrevImgActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 10); pnlCtrlBtn.add(btnPrevImg, gridBagConstraints); btnNextImg.setIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/arrow-right.png"))); // NOI18N btnNextImg.setText(org.openide.util.NbBundle.getMessage( Sb_stadtbildserieEditor.class, "MauerEditor.btnNextImg.text")); // NOI18N btnNextImg.setBorder(null); btnNextImg.setBorderPainted(false); btnNextImg.setContentAreaFilled(false); btnNextImg.setFocusPainted(false); btnNextImg.setMaximumSize(new java.awt.Dimension(30, 30)); btnNextImg.setMinimumSize(new java.awt.Dimension(30, 30)); btnNextImg.setPreferredSize(new java.awt.Dimension(30, 30)); btnNextImg.setPressedIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/arrow-right-pressed.png"))); // NOI18N btnNextImg.setRolloverIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/arrow-right-selected.png"))); // NOI18N btnNextImg.setSelectedIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/arrow-right-selected.png"))); // NOI18N btnNextImg.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { btnNextImgActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 0); pnlCtrlBtn.add(btnNextImg, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; pnlCtrlBtn.add(filler1, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 4; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; pnlCtrlBtn.add(filler2, gridBagConstraints); tbtnIsPreviewImage.setIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/tick_32.png"))); // NOI18N tbtnIsPreviewImage.setSelected(true); tbtnIsPreviewImage.setBorderPainted(false); tbtnIsPreviewImage.setDisabledIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/tick.png"))); // NOI18N tbtnIsPreviewImage.setMaximumSize(new java.awt.Dimension(30, 30)); tbtnIsPreviewImage.setMinimumSize(new java.awt.Dimension(30, 30)); tbtnIsPreviewImage.setPreferredSize(new java.awt.Dimension(32, 32)); tbtnIsPreviewImage.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { tbtnIsPreviewImageActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); pnlCtrlBtn.add(tbtnIsPreviewImage, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; pnlVorschau.add(pnlCtrlBtn, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel2.add(pnlVorschau, gridBagConstraints); roundedPanel7.setLayout(new java.awt.GridBagLayout()); semiRoundedPanel8.setBackground(new java.awt.Color(51, 51, 51)); semiRoundedPanel8.setLayout(new java.awt.FlowLayout()); jLabel6.setForeground(new java.awt.Color(255, 255, 255)); jLabel6.setText("Karte"); semiRoundedPanel8.add(jLabel6); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.ipadx = 1; roundedPanel7.add(semiRoundedPanel8, gridBagConstraints); panDetails4.setOpaque(false); panDetails4.setLayout(new java.awt.GridBagLayout()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails4.add(pnlMap, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; roundedPanel7.add(panDetails4, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel2.add(roundedPanel7, gridBagConstraints); roundedPanel6.setLayout(new java.awt.GridBagLayout()); semiRoundedPanel7.setBackground(new java.awt.Color(51, 51, 51)); semiRoundedPanel7.setLayout(new java.awt.FlowLayout()); jLabel5.setForeground(new java.awt.Color(255, 255, 255)); jLabel5.setText("Prüfhinweis"); semiRoundedPanel7.add(jLabel5); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.ipadx = 1; roundedPanel6.add(semiRoundedPanel7, gridBagConstraints); panDetails3.setOpaque(false); panDetails3.setLayout(new java.awt.GridBagLayout()); chbPruefen.setText("Prüfen"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.pruefen}"), chbPruefen, org.jdesktop.beansbinding.BeanProperty.create("selected")); binding.setConverter(((DefaultBindableJCheckBox)chbPruefen).getConverter()); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails3.add(chbPruefen, gridBagConstraints); jTextArea2.setColumns(20); jTextArea2.setRows(5); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.pruefhinweis_von}"), jTextArea2, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jScrollPane4.setViewportView(jTextArea2); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails3.add(jScrollPane4, gridBagConstraints); jButton1.setText("Prüfhinweis speichern"); jButton1.setEnabled(false); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails3.add(jButton1, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; roundedPanel6.add(panDetails3, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel2.add(roundedPanel6, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.gridheight = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 3.0; jPanel3.add(jPanel2, gridBagConstraints); jScrollPane5.setViewportView(jPanel3); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; add(jScrollPane5, gridBagConstraints); bindingGroup.bind(); } // </editor-fold>//GEN-END:initComponents
private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; bindingGroup = new org.jdesktop.beansbinding.BindingGroup(); sqlDateToUtilDateConverter = new de.cismet.cids.editors.converters.SqlDateToUtilDateConverter(); sqlDateToStringConverter = new de.cismet.cids.custom.objectrenderer.converter.SQLDateToStringConverter(); panTitle = new javax.swing.JPanel(); panTitleString = new javax.swing.JPanel(); lblTitle = new javax.swing.JLabel(); panPrintButton = new javax.swing.JPanel(); lblPrint = new javax.swing.JLabel(); roundedPanel1 = new de.cismet.tools.gui.RoundedPanel(); semiRoundedPanel1 = new de.cismet.tools.gui.SemiRoundedPanel(); jScrollPane5 = new javax.swing.JScrollPane(); jPanel3 = new javax.swing.JPanel(); jPanel1 = new javax.swing.JPanel(); roundedPanel2 = new de.cismet.tools.gui.RoundedPanel(); semiRoundedPanel3 = new de.cismet.tools.gui.SemiRoundedPanel(); jLabel1 = new javax.swing.JLabel(); panContent = new RoundedPanel(); pnlCtrlButtons1 = new javax.swing.JPanel(); btnAddSuchwort = new javax.swing.JButton(); btnRemoveSuchwort = new javax.swing.JButton(); pnlCtrlButtons = new javax.swing.JPanel(); btnAddImageNumber = new javax.swing.JButton(); btnRemoveImageNumber = new javax.swing.JButton(); lblDescBildnummer = new javax.swing.JLabel(); lblDescLagerort = new javax.swing.JLabel(); lblDescAufnahmedatum = new javax.swing.JLabel(); lblDescInfo = new javax.swing.JLabel(); lblDescBildtyp = new javax.swing.JLabel(); lblDescSuchworte = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); lstBildnummern = new javax.swing.JList(); jScrollPane2 = new javax.swing.JScrollPane(); lstSuchworte = new javax.swing.JList(); defaultBindableReferenceCombo2 = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); defaultBindableReferenceCombo3 = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); jScrollPane3 = new javax.swing.JScrollPane(); jTextArea1 = new javax.swing.JTextArea(); jXDatePicker1 = new org.jdesktop.swingx.JXDatePicker(); roundedPanel3 = new de.cismet.tools.gui.RoundedPanel(); semiRoundedPanel4 = new de.cismet.tools.gui.SemiRoundedPanel(); jLabel2 = new javax.swing.JLabel(); panDetails = new RoundedPanel(); lblDescFilmart = new javax.swing.JLabel(); lblDescFotograf = new javax.swing.JLabel(); lblDescAuftraggeber = new javax.swing.JLabel(); dbcAuftraggeber = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); dbcFotograf = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); dbcFilmart = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); roundedPanel4 = new de.cismet.tools.gui.RoundedPanel(); semiRoundedPanel5 = new de.cismet.tools.gui.SemiRoundedPanel(); jLabel3 = new javax.swing.JLabel(); panDetails1 = new RoundedPanel(); lblDescGeometrie = new javax.swing.JLabel(); lblDescOrt = new javax.swing.JLabel(); lblDescStrasse = new javax.swing.JLabel(); dbcOrt = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); jLabel7 = new javax.swing.JLabel(); defaultBindableJTextField1 = new de.cismet.cids.editors.DefaultBindableJTextField(); lblGeomAus = new javax.swing.JLabel(); btnCombineGeometries = new javax.swing.JButton(); defaultCismapGeometryComboBoxEditor1 = new de.cismet.cismap.cids.geometryeditor.DefaultCismapGeometryComboBoxEditor(); bcbStrasse = new FastBindableReferenceCombo( "select s.strassenschluessel,s.name from strasse s", strasseFormater, new String[] { "NAME" }); jPanel2 = new javax.swing.JPanel(); pnlVorschau = new de.cismet.tools.gui.RoundedPanel(); semiRoundedPanel2 = new de.cismet.tools.gui.SemiRoundedPanel(); lblVorschau = new javax.swing.JLabel(); pnlFoto = new javax.swing.JPanel(); lblBusy = new org.jdesktop.swingx.JXBusyLabel(new Dimension(75, 75)); jPanel4 = new javax.swing.JPanel(); lblPicture = new javax.swing.JLabel(); pnlCtrlBtn = new javax.swing.JPanel(); btnDownloadHighResImage = new javax.swing.JButton(); btnPrevImg = new javax.swing.JButton(); btnNextImg = new javax.swing.JButton(); filler1 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0), new java.awt.Dimension(32767, 0)); filler2 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0), new java.awt.Dimension(32767, 0)); tbtnIsPreviewImage = new javax.swing.JToggleButton(); roundedPanel7 = new de.cismet.tools.gui.RoundedPanel(); semiRoundedPanel8 = new de.cismet.tools.gui.SemiRoundedPanel(); jLabel6 = new javax.swing.JLabel(); panDetails4 = new RoundedPanel(); pnlMap = new javax.swing.JPanel(); roundedPanel6 = new de.cismet.tools.gui.RoundedPanel(); semiRoundedPanel7 = new de.cismet.tools.gui.SemiRoundedPanel(); jLabel5 = new javax.swing.JLabel(); panDetails3 = new RoundedPanel(); chbPruefen = new DefaultBindableJCheckBox(); jScrollPane4 = new javax.swing.JScrollPane(); jTextArea2 = new javax.swing.JTextArea(); jButton1 = new javax.swing.JButton(); panTitle.setOpaque(false); panTitle.setLayout(new java.awt.BorderLayout()); panTitleString.setOpaque(false); panTitleString.setLayout(new java.awt.GridBagLayout()); lblTitle.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N lblTitle.setForeground(new java.awt.Color(255, 255, 255)); lblTitle.setText("TITLE"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); panTitleString.add(lblTitle, gridBagConstraints); panTitle.add(panTitleString, java.awt.BorderLayout.CENTER); panPrintButton.setOpaque(false); panPrintButton.setLayout(new java.awt.GridBagLayout()); lblPrint.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/icons/printer.png"))); // NOI18N lblPrint.addMouseListener(new java.awt.event.MouseAdapter() { @Override public void mouseClicked(final java.awt.event.MouseEvent evt) { lblPrintMouseClicked(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); panPrintButton.add(lblPrint, gridBagConstraints); panTitle.add(panPrintButton, java.awt.BorderLayout.EAST); roundedPanel1.add(semiRoundedPanel1, java.awt.BorderLayout.CENTER); setOpaque(false); setLayout(new java.awt.GridBagLayout()); jScrollPane5.setBorder(null); jScrollPane5.setOpaque(false); jPanel3.setOpaque(false); jPanel3.setLayout(new java.awt.GridBagLayout()); jPanel1.setOpaque(false); jPanel1.setLayout(new java.awt.GridBagLayout()); roundedPanel2.setLayout(new java.awt.GridBagLayout()); semiRoundedPanel3.setBackground(new java.awt.Color(51, 51, 51)); semiRoundedPanel3.setLayout(new java.awt.FlowLayout()); jLabel1.setForeground(new java.awt.Color(255, 255, 255)); jLabel1.setText("Allgemeine Informationen"); semiRoundedPanel3.add(jLabel1); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.ipadx = 1; roundedPanel2.add(semiRoundedPanel3, gridBagConstraints); panContent.setOpaque(false); panContent.setLayout(new java.awt.GridBagLayout()); pnlCtrlButtons1.setOpaque(false); pnlCtrlButtons1.setLayout(new java.awt.GridBagLayout()); btnAddSuchwort.setIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit_add_mini.png"))); // NOI18N btnAddSuchwort.setText(org.openide.util.NbBundle.getMessage( Sb_stadtbildserieEditor.class, "MauerEditor.btnAddImg.text")); // NOI18N btnAddSuchwort.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { btnAddSuchwortActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlCtrlButtons1.add(btnAddSuchwort, gridBagConstraints); btnRemoveSuchwort.setIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit_remove_mini.png"))); // NOI18N btnRemoveSuchwort.setText(org.openide.util.NbBundle.getMessage( Sb_stadtbildserieEditor.class, "MauerEditor.btnRemoveImg.text")); // NOI18N btnRemoveSuchwort.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { btnRemoveSuchwortActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridy = 1; pnlCtrlButtons1.add(btnRemoveSuchwort, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; panContent.add(pnlCtrlButtons1, gridBagConstraints); pnlCtrlButtons.setOpaque(false); pnlCtrlButtons.setLayout(new java.awt.GridBagLayout()); btnAddImageNumber.setIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit_add_mini.png"))); // NOI18N btnAddImageNumber.setText(org.openide.util.NbBundle.getMessage( Sb_stadtbildserieEditor.class, "MauerEditor.btnAddImg.text")); // NOI18N btnAddImageNumber.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { btnAddImageNumberActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlCtrlButtons.add(btnAddImageNumber, gridBagConstraints); btnRemoveImageNumber.setIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit_remove_mini.png"))); // NOI18N btnRemoveImageNumber.setText(org.openide.util.NbBundle.getMessage( Sb_stadtbildserieEditor.class, "MauerEditor.btnRemoveImg.text")); // NOI18N btnRemoveImageNumber.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { btnRemoveImageNumberActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridy = 1; pnlCtrlButtons.add(btnRemoveImageNumber, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; panContent.add(pnlCtrlButtons, gridBagConstraints); lblDescBildnummer.setText("Bildnummer"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panContent.add(lblDescBildnummer, gridBagConstraints); lblDescLagerort.setText("Lagerort"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 6; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panContent.add(lblDescLagerort, gridBagConstraints); lblDescAufnahmedatum.setText("Aufnahmedatum"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panContent.add(lblDescAufnahmedatum, gridBagConstraints); lblDescInfo.setText("Kommentar"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 7; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panContent.add(lblDescInfo, gridBagConstraints); lblDescBildtyp.setText("Bildtyp"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panContent.add(lblDescBildtyp, gridBagConstraints); lblDescSuchworte.setText("Suchworte"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panContent.add(lblDescSuchworte, gridBagConstraints); lstBildnummern.setModel(new javax.swing.AbstractListModel() { String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" }; @Override public int getSize() { return strings.length; } @Override public Object getElementAt(final int i) { return strings[i]; } }); lstBildnummern.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); org.jdesktop.beansbinding.ELProperty eLProperty = org.jdesktop.beansbinding.ELProperty.create( "${cidsBean.stadtbilder_arr}"); org.jdesktop.swingbinding.JListBinding jListBinding = org.jdesktop.swingbinding.SwingBindings .createJListBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, eLProperty, lstBildnummern); bindingGroup.addBinding(jListBinding); lstBildnummern.addListSelectionListener(new javax.swing.event.ListSelectionListener() { @Override public void valueChanged(final javax.swing.event.ListSelectionEvent evt) { lstBildnummernValueChanged(evt); } }); jScrollPane1.setViewportView(lstBildnummern); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panContent.add(jScrollPane1, gridBagConstraints); lstSuchworte.setModel(new javax.swing.AbstractListModel() { String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" }; @Override public int getSize() { return strings.length; } @Override public Object getElementAt(final int i) { return strings[i]; } }); eLProperty = org.jdesktop.beansbinding.ELProperty.create("${cidsBean.suchwort_arr}"); jListBinding = org.jdesktop.swingbinding.SwingBindings.createJListBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, eLProperty, lstSuchworte); bindingGroup.addBinding(jListBinding); jScrollPane2.setViewportView(lstSuchworte); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panContent.add(jScrollPane2, gridBagConstraints); org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.bildtyp}"), defaultBindableReferenceCombo2, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 5; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panContent.add(defaultBindableReferenceCombo2, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.lager}"), defaultBindableReferenceCombo3, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 6; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panContent.add(defaultBindableReferenceCombo3, gridBagConstraints); jTextArea1.setColumns(20); jTextArea1.setRows(5); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.kommentar}"), jTextArea1, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jScrollPane3.setViewportView(jTextArea1); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 7; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panContent.add(jScrollPane3, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.aufnahmedatum}"), jXDatePicker1, org.jdesktop.beansbinding.BeanProperty.create("date")); binding.setConverter(timeStampConverter); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panContent.add(jXDatePicker1, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; roundedPanel2.add(panContent, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel1.add(roundedPanel2, gridBagConstraints); roundedPanel3.setLayout(new java.awt.GridBagLayout()); semiRoundedPanel4.setBackground(new java.awt.Color(51, 51, 51)); semiRoundedPanel4.setLayout(new java.awt.FlowLayout()); jLabel2.setForeground(new java.awt.Color(255, 255, 255)); jLabel2.setText("Metainformationen"); semiRoundedPanel4.add(jLabel2); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.ipadx = 1; roundedPanel3.add(semiRoundedPanel4, gridBagConstraints); panDetails.setOpaque(false); panDetails.setLayout(new java.awt.GridBagLayout()); lblDescFilmart.setText("Filmart"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails.add(lblDescFilmart, gridBagConstraints); lblDescFotograf.setText("Fotograf"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails.add(lblDescFotograf, gridBagConstraints); lblDescAuftraggeber.setText("Auftraggeber"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails.add(lblDescAuftraggeber, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.auftraggeber}"), dbcAuftraggeber, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails.add(dbcAuftraggeber, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.fotograf}"), dbcFotograf, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails.add(dbcFotograf, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.filmart}"), dbcFilmart, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails.add(dbcFilmart, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; roundedPanel3.add(panDetails, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel1.add(roundedPanel3, gridBagConstraints); roundedPanel4.setLayout(new java.awt.GridBagLayout()); semiRoundedPanel5.setBackground(new java.awt.Color(51, 51, 51)); semiRoundedPanel5.setLayout(new java.awt.FlowLayout()); jLabel3.setForeground(new java.awt.Color(255, 255, 255)); jLabel3.setText("Ortbezogene Informationen"); semiRoundedPanel5.add(jLabel3); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.ipadx = 1; roundedPanel4.add(semiRoundedPanel5, gridBagConstraints); panDetails1.setOpaque(false); panDetails1.setLayout(new java.awt.GridBagLayout()); lblDescGeometrie.setText("Geometrie"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails1.add(lblDescGeometrie, gridBagConstraints); lblDescOrt.setText("Ort"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails1.add(lblDescOrt, gridBagConstraints); lblDescStrasse.setText("Straße"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails1.add(lblDescStrasse, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.ort}"), dbcOrt, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails1.add(dbcOrt, gridBagConstraints); jLabel7.setText("Hs.-Nr."); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails1.add(jLabel7, gridBagConstraints); defaultBindableJTextField1.setPreferredSize(new java.awt.Dimension(50, 19)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.hausnummer}"), defaultBindableJTextField1, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails1.add(defaultBindableJTextField1, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.geom_aus}"), lblGeomAus, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 2; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails1.add(lblGeomAus, gridBagConstraints); btnCombineGeometries.setIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/wizard.png"))); // NOI18N btnCombineGeometries.setText(org.openide.util.NbBundle.getMessage( Sb_stadtbildserieEditor.class, "VermessungRissEditor.btnCombineGeometries.text")); // NOI18N btnCombineGeometries.setToolTipText(org.openide.util.NbBundle.getMessage( Sb_stadtbildserieEditor.class, "VermessungRissEditor.btnCombineGeometries.toolTipText")); // NOI18N btnCombineGeometries.setEnabled(false); btnCombineGeometries.setFocusPainted(false); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails1.add(btnCombineGeometries, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.geom}"), defaultCismapGeometryComboBoxEditor1, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails1.add(defaultCismapGeometryComboBoxEditor1, gridBagConstraints); ((FastBindableReferenceCombo)bcbStrasse).setSorted(true); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.strasse}"), bcbStrasse, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails1.add(bcbStrasse, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; roundedPanel4.add(panDetails1, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel1.add(roundedPanel4, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridheight = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 3.0; jPanel3.add(jPanel1, gridBagConstraints); jPanel2.setOpaque(false); jPanel2.setLayout(new java.awt.GridBagLayout()); pnlVorschau.setPreferredSize(new java.awt.Dimension(140, 300)); pnlVorschau.setLayout(new java.awt.GridBagLayout()); semiRoundedPanel2.setBackground(new java.awt.Color(51, 51, 51)); semiRoundedPanel2.setLayout(new java.awt.FlowLayout()); lblVorschau.setForeground(new java.awt.Color(255, 255, 255)); lblVorschau.setText(org.openide.util.NbBundle.getMessage( Sb_stadtbildserieEditor.class, "MauerEditor.lblVorschau.text")); // NOI18N semiRoundedPanel2.add(lblVorschau); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; pnlVorschau.add(semiRoundedPanel2, gridBagConstraints); pnlFoto.setOpaque(false); pnlFoto.setLayout(new java.awt.CardLayout()); lblBusy.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); lblBusy.setMaximumSize(new java.awt.Dimension(140, 40)); lblBusy.setMinimumSize(new java.awt.Dimension(140, 60)); lblBusy.setPreferredSize(new java.awt.Dimension(140, 60)); pnlFoto.add(lblBusy, "busy"); jPanel4.setOpaque(false); jPanel4.setLayout(new java.awt.GridBagLayout()); lblPicture.setText(org.openide.util.NbBundle.getMessage( Sb_stadtbildserieEditor.class, "MauerEditor.lblPicture.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; jPanel4.add(lblPicture, gridBagConstraints); pnlFoto.add(jPanel4, "image"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; pnlVorschau.add(pnlFoto, gridBagConstraints); pnlCtrlBtn.setOpaque(false); pnlCtrlBtn.setPreferredSize(new java.awt.Dimension(100, 50)); pnlCtrlBtn.setLayout(new java.awt.GridBagLayout()); btnDownloadHighResImage.setIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/tools/gui/downloadmanager/res/download.png"))); // NOI18N btnDownloadHighResImage.setText(org.openide.util.NbBundle.getMessage( Sb_stadtbildserieEditor.class, "MauerEditor.btnPrevImg.text")); // NOI18N btnDownloadHighResImage.setBorder(null); btnDownloadHighResImage.setBorderPainted(false); btnDownloadHighResImage.setContentAreaFilled(false); btnDownloadHighResImage.setFocusPainted(false); btnDownloadHighResImage.setMaximumSize(new java.awt.Dimension(30, 30)); btnDownloadHighResImage.setMinimumSize(new java.awt.Dimension(30, 30)); btnDownloadHighResImage.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { btnDownloadHighResImageActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 0); pnlCtrlBtn.add(btnDownloadHighResImage, gridBagConstraints); btnPrevImg.setIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/arrow-left.png"))); // NOI18N btnPrevImg.setText(org.openide.util.NbBundle.getMessage( Sb_stadtbildserieEditor.class, "MauerEditor.btnPrevImg.text")); // NOI18N btnPrevImg.setBorder(null); btnPrevImg.setBorderPainted(false); btnPrevImg.setContentAreaFilled(false); btnPrevImg.setFocusPainted(false); btnPrevImg.setMaximumSize(new java.awt.Dimension(30, 30)); btnPrevImg.setMinimumSize(new java.awt.Dimension(30, 30)); btnPrevImg.setPreferredSize(new java.awt.Dimension(30, 30)); btnPrevImg.setPressedIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/arrow-left-pressed.png"))); // NOI18N btnPrevImg.setRolloverIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/arrow-left-selected.png"))); // NOI18N btnPrevImg.setSelectedIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/arrow-left-selected.png"))); // NOI18N btnPrevImg.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { btnPrevImgActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 10); pnlCtrlBtn.add(btnPrevImg, gridBagConstraints); btnNextImg.setIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/arrow-right.png"))); // NOI18N btnNextImg.setText(org.openide.util.NbBundle.getMessage( Sb_stadtbildserieEditor.class, "MauerEditor.btnNextImg.text")); // NOI18N btnNextImg.setBorder(null); btnNextImg.setBorderPainted(false); btnNextImg.setContentAreaFilled(false); btnNextImg.setFocusPainted(false); btnNextImg.setMaximumSize(new java.awt.Dimension(30, 30)); btnNextImg.setMinimumSize(new java.awt.Dimension(30, 30)); btnNextImg.setPreferredSize(new java.awt.Dimension(30, 30)); btnNextImg.setPressedIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/arrow-right-pressed.png"))); // NOI18N btnNextImg.setRolloverIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/arrow-right-selected.png"))); // NOI18N btnNextImg.setSelectedIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/arrow-right-selected.png"))); // NOI18N btnNextImg.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { btnNextImgActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 0); pnlCtrlBtn.add(btnNextImg, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; pnlCtrlBtn.add(filler1, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 4; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; pnlCtrlBtn.add(filler2, gridBagConstraints); tbtnIsPreviewImage.setIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/tick_32.png"))); // NOI18N tbtnIsPreviewImage.setSelected(true); tbtnIsPreviewImage.setBorderPainted(false); tbtnIsPreviewImage.setMaximumSize(new java.awt.Dimension(30, 30)); tbtnIsPreviewImage.setMinimumSize(new java.awt.Dimension(30, 30)); tbtnIsPreviewImage.setPreferredSize(new java.awt.Dimension(32, 32)); tbtnIsPreviewImage.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { tbtnIsPreviewImageActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); pnlCtrlBtn.add(tbtnIsPreviewImage, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; pnlVorschau.add(pnlCtrlBtn, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel2.add(pnlVorschau, gridBagConstraints); roundedPanel7.setLayout(new java.awt.GridBagLayout()); semiRoundedPanel8.setBackground(new java.awt.Color(51, 51, 51)); semiRoundedPanel8.setLayout(new java.awt.FlowLayout()); jLabel6.setForeground(new java.awt.Color(255, 255, 255)); jLabel6.setText("Karte"); semiRoundedPanel8.add(jLabel6); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.ipadx = 1; roundedPanel7.add(semiRoundedPanel8, gridBagConstraints); panDetails4.setOpaque(false); panDetails4.setLayout(new java.awt.GridBagLayout()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails4.add(pnlMap, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; roundedPanel7.add(panDetails4, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel2.add(roundedPanel7, gridBagConstraints); roundedPanel6.setLayout(new java.awt.GridBagLayout()); semiRoundedPanel7.setBackground(new java.awt.Color(51, 51, 51)); semiRoundedPanel7.setLayout(new java.awt.FlowLayout()); jLabel5.setForeground(new java.awt.Color(255, 255, 255)); jLabel5.setText("Prüfhinweis"); semiRoundedPanel7.add(jLabel5); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.ipadx = 1; roundedPanel6.add(semiRoundedPanel7, gridBagConstraints); panDetails3.setOpaque(false); panDetails3.setLayout(new java.awt.GridBagLayout()); chbPruefen.setText("Prüfen"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.pruefen}"), chbPruefen, org.jdesktop.beansbinding.BeanProperty.create("selected")); binding.setConverter(((DefaultBindableJCheckBox)chbPruefen).getConverter()); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails3.add(chbPruefen, gridBagConstraints); jTextArea2.setColumns(20); jTextArea2.setRows(5); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.pruefhinweis_von}"), jTextArea2, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jScrollPane4.setViewportView(jTextArea2); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails3.add(jScrollPane4, gridBagConstraints); jButton1.setText("Prüfhinweis speichern"); jButton1.setEnabled(false); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); panDetails3.add(jButton1, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; roundedPanel6.add(panDetails3, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel2.add(roundedPanel6, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.gridheight = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 3.0; jPanel3.add(jPanel2, gridBagConstraints); jScrollPane5.setViewportView(jPanel3); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; add(jScrollPane5, gridBagConstraints); bindingGroup.bind(); } // </editor-fold>//GEN-END:initComponents
diff --git a/src/com/slidellrobotics/reboundrumble/Main.java b/src/com/slidellrobotics/reboundrumble/Main.java index 16d39b7..de6c5e0 100644 --- a/src/com/slidellrobotics/reboundrumble/Main.java +++ b/src/com/slidellrobotics/reboundrumble/Main.java @@ -1,76 +1,76 @@ /*----------------------------------------------------------------------------*/ /* Copyright (c) FIRST 2008. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ package com.slidellrobotics.reboundrumble; import edu.wpi.first.wpilibj.IterativeRobot; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.command.Scheduler; import com.slidellrobotics.reboundrumble.commands.CommandBase; import edu.wpi.first.wpilibj.image.CriteriaCollection; import edu.wpi.first.wpilibj.image.NIVision.MeasurementType; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the IterativeRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class Main extends IterativeRobot { CriteriaCollection cc; Command autonomousCommand; /** * This function is run when the robot is first started up and should be * used for any initialization code. */ public void robotInit() { // instantiate the command used for the autonomous period //autonomousCommand = new ExampleCommand(); // Initialize all subsystems CommandBase.init(); SmartDashboard.putData(Scheduler.getInstance()); cc = new CriteriaCollection(); //Sets the - cc.addCriteria(MeasurementType.IMAQ_MT_BOUNDING_RECT_WIDTH, //criteria - 20, 500, false); //for height + cc.addCriteria(MeasurementType.IMAQ_MT_BOUNDING_RECT_HEIGHT, //criteria + 20, 400, false); //for height cc.addCriteria(MeasurementType.IMAQ_MT_BOUNDING_RECT_WIDTH, //and width - 30, 400, false); //thresholds. + 30, 500, false); //thresholds. } public void autonomousInit() { // schedule the autonomous command (example) autonomousCommand.start(); } /** * This function is called periodically during autonomous */ public void autonomousPeriodic() { Scheduler.getInstance().run(); } public void teleopInit() { // This makes sure that the autonomous stops running when // teleop starts running. If you want the autonomous to // continue until interrupted by another command, remove // this line or comment it out. //autonomousCommand.cancel(); } /** * This function is called periodically during operator control */ public void teleopPeriodic() { Scheduler.getInstance().run(); } }
false
true
public void robotInit() { // instantiate the command used for the autonomous period //autonomousCommand = new ExampleCommand(); // Initialize all subsystems CommandBase.init(); SmartDashboard.putData(Scheduler.getInstance()); cc = new CriteriaCollection(); //Sets the cc.addCriteria(MeasurementType.IMAQ_MT_BOUNDING_RECT_WIDTH, //criteria 20, 500, false); //for height cc.addCriteria(MeasurementType.IMAQ_MT_BOUNDING_RECT_WIDTH, //and width 30, 400, false); //thresholds. }
public void robotInit() { // instantiate the command used for the autonomous period //autonomousCommand = new ExampleCommand(); // Initialize all subsystems CommandBase.init(); SmartDashboard.putData(Scheduler.getInstance()); cc = new CriteriaCollection(); //Sets the cc.addCriteria(MeasurementType.IMAQ_MT_BOUNDING_RECT_HEIGHT, //criteria 20, 400, false); //for height cc.addCriteria(MeasurementType.IMAQ_MT_BOUNDING_RECT_WIDTH, //and width 30, 500, false); //thresholds. }
diff --git a/gr.sch.ira.minoas/src/gr/sch/ira/minoas/seam/components/management/EmployeeLeavesManagement.java b/gr.sch.ira.minoas/src/gr/sch/ira/minoas/seam/components/management/EmployeeLeavesManagement.java index eaacac99..fc529e0c 100644 --- a/gr.sch.ira.minoas/src/gr/sch/ira/minoas/seam/components/management/EmployeeLeavesManagement.java +++ b/gr.sch.ira.minoas/src/gr/sch/ira/minoas/seam/components/management/EmployeeLeavesManagement.java @@ -1,1254 +1,1259 @@ package gr.sch.ira.minoas.seam.components.management; import gr.sch.ira.minoas.core.CoreUtils; import gr.sch.ira.minoas.model.employee.Employee; import gr.sch.ira.minoas.model.employement.EmployeeLeave; import gr.sch.ira.minoas.model.employement.EmployeeLeaveType; import gr.sch.ira.minoas.model.employement.Employment; import gr.sch.ira.minoas.model.employement.EmploymentType; import gr.sch.ira.minoas.model.printout.PrintoutRecipients; import gr.sch.ira.minoas.model.printout.PrintoutSignatures; import gr.sch.ira.minoas.model.security.Principal; import gr.sch.ira.minoas.seam.components.BaseDatabaseAwareSeamComponent; import gr.sch.ira.minoas.seam.components.home.EmployeeHome; import gr.sch.ira.minoas.seam.components.home.EmployeeLeaveHome; import gr.sch.ira.minoas.seam.components.managers.MedicalEmployeeLeavesOfCurrentYear; import gr.sch.ira.minoas.seam.components.managers.MedicalEmployeeLeavesOfPrevious5Years; import gr.sch.ira.minoas.seam.components.managers.RegularEmployeeLeavesOfCurrentYear; import gr.sch.ira.minoas.seam.components.managers.RegularEmployeeLeavesOfPreviousYear; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.faces.model.SelectItem; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import net.sf.jasperreports.engine.JRDataSource; import net.sf.jasperreports.engine.JRExporterParameter; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.JasperPrint; import net.sf.jasperreports.engine.JasperRunManager; import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource; import net.sf.jasperreports.engine.export.oasis.JROdtExporter; import org.apache.commons.lang.time.DateUtils; import org.jboss.seam.ScopeType; import org.jboss.seam.annotations.In; import org.jboss.seam.annotations.Name; import org.jboss.seam.annotations.Out; import org.jboss.seam.annotations.RaiseEvent; import org.jboss.seam.annotations.Scope; import org.jboss.seam.annotations.Transactional; import org.jboss.seam.international.StatusMessage.Severity; @Name(value = "employeeLeavesManagement") @Scope(ScopeType.PAGE) public class EmployeeLeavesManagement extends BaseDatabaseAwareSeamComponent { public class PrintingHelper { private String fieldText1; private String fieldText2; private String fieldText3; private String fieldText4; private String fieldText5; private String fieldText6; private String fieldText7; private String fieldText8; private String fieldText9; private Date fieldDate1; private Date fieldDate2; private Date fieldDate3; private Date fieldDate4; private Date fieldDate5; private Date fieldDate6; private Date fieldDate7; private Date fieldDate8; private Date fieldDate9; /** * @return the fieldText1 */ public String getFieldText1() { return fieldText1; } /** * @param fieldText1 the fieldText1 to set */ public void setFieldText1(String fieldText1) { this.fieldText1 = fieldText1; } /** * @return the fieldText2 */ public String getFieldText2() { return fieldText2; } /** * @param fieldText2 the fieldText2 to set */ public void setFieldText2(String fieldText2) { this.fieldText2 = fieldText2; } /** * @return the fieldText3 */ public String getFieldText3() { return fieldText3; } /** * @param fieldText3 the fieldText3 to set */ public void setFieldText3(String fieldText3) { this.fieldText3 = fieldText3; } /** * @return the fieldText4 */ public String getFieldText4() { return fieldText4; } /** * @param fieldText4 the fieldText4 to set */ public void setFieldText4(String fieldText4) { this.fieldText4 = fieldText4; } /** * @return the fieldText5 */ public String getFieldText5() { return fieldText5; } /** * @param fieldText5 the fieldText5 to set */ public void setFieldText5(String fieldText5) { this.fieldText5 = fieldText5; } /** * @return the fieldText6 */ public String getFieldText6() { return fieldText6; } /** * @param fieldText6 the fieldText6 to set */ public void setFieldText6(String fieldText6) { this.fieldText6 = fieldText6; } /** * @return the fieldText7 */ public String getFieldText7() { return fieldText7; } /** * @param fieldText7 the fieldText7 to set */ public void setFieldText7(String fieldText7) { this.fieldText7 = fieldText7; } /** * @return the fieldText8 */ public String getFieldText8() { return fieldText8; } /** * @param fieldText8 the fieldText8 to set */ public void setFieldText8(String fieldText8) { this.fieldText8 = fieldText8; } /** * @return the fieldText9 */ public String getFieldText9() { return fieldText9; } /** * @param fieldText9 the fieldText9 to set */ public void setFieldText9(String fieldText9) { this.fieldText9 = fieldText9; } /** * @return the fieldDate1 */ public Date getFieldDate1() { return fieldDate1; } /** * @param fieldDate1 the fieldDate1 to set */ public void setFieldDate1(Date fieldDate1) { this.fieldDate1 = fieldDate1; } /** * @return the fieldDate2 */ public Date getFieldDate2() { return fieldDate2; } /** * @param fieldDate2 the fieldDate2 to set */ public void setFieldDate2(Date fieldDate2) { this.fieldDate2 = fieldDate2; } /** * @return the fieldDate3 */ public Date getFieldDate3() { return fieldDate3; } /** * @param fieldDate3 the fieldDate3 to set */ public void setFieldDate3(Date fieldDate3) { this.fieldDate3 = fieldDate3; } /** * @return the fieldDate4 */ public Date getFieldDate4() { return fieldDate4; } /** * @param fieldDate4 the fieldDate4 to set */ public void setFieldDate4(Date fieldDate4) { this.fieldDate4 = fieldDate4; } /** * @return the fieldDate5 */ public Date getFieldDate5() { return fieldDate5; } /** * @param fieldDate5 the fieldDate5 to set */ public void setFieldDate5(Date fieldDate5) { this.fieldDate5 = fieldDate5; } /** * @return the fieldDate6 */ public Date getFieldDate6() { return fieldDate6; } /** * @param fieldDate6 the fieldDate6 to set */ public void setFieldDate6(Date fieldDate6) { this.fieldDate6 = fieldDate6; } /** * @return the fieldDate7 */ public Date getFieldDate7() { return fieldDate7; } /** * @param fieldDate7 the fieldDate7 to set */ public void setFieldDate7(Date fieldDate7) { this.fieldDate7 = fieldDate7; } /** * @return the fieldDate8 */ public Date getFieldDate8() { return fieldDate8; } /** * @param fieldDate8 the fieldDate8 to set */ public void setFieldDate8(Date fieldDate8) { this.fieldDate8 = fieldDate8; } /** * @return the fieldDate9 */ public Date getFieldDate9() { return fieldDate9; } /** * @param fieldDate9 the fieldDate9 to set */ public void setFieldDate9(Date fieldDate9) { this.fieldDate9 = fieldDate9; } } /** * Comment for <code>serialVersionUID</code> */ private static final long serialVersionUID = 1L; @In(required = true) private EmployeeHome employeeHome; private List<PrintoutRecipients> leavePrintounRecipientList = new ArrayList<PrintoutRecipients>(); private List<PrintoutRecipients> leavePrintounRecipientListSource = new ArrayList<PrintoutRecipients>(); private PrintoutSignatures leavePrintoutSignature; private Collection<PrintoutSignatures> leavePrintoutSignatureSource = new ArrayList<PrintoutSignatures>(); private Date leavePrintoutDate; private Date leavePrintoutRequestDate; private String leavePrintoutReferenceNumber; private PrintingHelper printHelper = new PrintingHelper(); private Integer leaveDurarionInDaysHelper = 0; private Integer leaveDurationInDaysWithoutWeekends = 0; /** * It is the date used for various leave count computation. It is used by {@link RegularEmployeeLeavesOfCurrentYear}, * {@link RegularEmployeeLeavesOfPreviousYear}, {@link MedicalEmployeeLeavesOfCurrentYear} and {@link MedicalEmployeeLeavesOfPrevious5Years} */ @Out(value="leaveComputationReferenceDay", scope=ScopeType.PAGE, required=true) private Date leaveComputationReferenceDay = new Date(); @SuppressWarnings("unchecked") @Transactional public Collection<EmployeeLeaveType> suggestLeaveTypesBasedOnSelectedEmployee(Object search_pattern) { System.err.println(getEmployeeHome().getInstance().getType()); return getEntityManager() .createQuery( "SELECT s FROM EmployeeLeaveType s WHERE (LOWER(s.description) LIKE LOWER(:search_pattern) OR (s.legacyCode LIKE :search_pattern2)) AND s.suitableForEmployeeType=:employeeType ORDER BY s.legacyCode") .setParameter("search_pattern", CoreUtils.getSearchPattern(String.valueOf(search_pattern))) .setParameter("search_pattern2", CoreUtils.getSearchPattern(String.valueOf(search_pattern))) .setParameter("employeeType", employeeHome.getInstance().getType()).getResultList(); } /** * @return the employeeHome */ public EmployeeHome getEmployeeHome() { return employeeHome; } /** * @param employeeHome the employeeHome to set */ public void setEmployeeHome(EmployeeHome employeeHome) { this.employeeHome = employeeHome; } // @Transactional // public String createNewLeave() { // if(!leaveHome.isManaged()) { // info("trying to create new leave #0", leaveHome.getInstance()); // if(validateLeave(leaveHome.getInstance(), true)) { // leaveHome.persist(); // constructLeaveHistory(); // findEmployeeActiveLeave(); // facesMessages.add(Severity.INFO, "Η εισαγωγή νέας άδειας έγινε"); // return ACTION_OUTCOME_SUCCESS; // } else { // facesMessages.add(Severity.WARN, "Η εισαγωγή νέας άδειας δεν ήταν εφικτή."); // return ACTION_OUTCOME_FAILURE; // } // } else { // facesMessages.add(Severity.ERROR, "Employee's #0 leave #1 is managed.", employeeHome.getInstance(), leaveHome.getInstance()); // return ACTION_OUTCOME_FAILURE; // } // // } // // @Transactional // public String deleteLeave() { // if(leaveHome.isManaged()) { // Leave leave = leaveHome.getInstance(); // leave.setActive(Boolean.FALSE); // leave.setDeleted(Boolean.TRUE); // leave.setDeletedOn(new Date()); // leave.setDeletedBy(getPrincipal()); // leaveHome.update(); // constructLeaveHistory(); // findEmployeeActiveLeave(); // return ACTION_OUTCOME_SUCCESS; // } else { // facesMessages.add(Severity.ERROR, "Employee's #0 leave #1 is not managed.", employeeHome.getInstance(), leaveHome.getInstance()); // return ACTION_OUTCOME_FAILURE; // } // } // // /* this method is called when the user clicks the "add new leave" */ // public void prepeareNewLeave() { // leaveHome.clearInstance(); // Leave leave = leaveHome.getInstance(); // leave.setEstablished(new Date()); // leave.setDueTo(null); // leave.setEmployee(employeeHome.getInstance()); // leave.setLeaveType(LeaveType.MEDICAL_LABOUR_LEAVE); // } // public String modifyInactiveLeave() { // if(leaveHome != null && leaveHome.isManaged()) { // info("trying to modify inactive leave #0", leaveHome); // /* check if the leave dates leads us to activate the leave. */ // boolean leaveShouldBeActivated = leaveShouldBeActivated(leaveHome.getInstance(), new Date()); // // if(leaveShouldBeActivated) { // facesMessages.add(Severity.ERROR, "Οι ημ/νιες έναρξης και λήξης της άδειας, έτσι όπως τις τροποποιήσατε, είναι μή αποδεκτές γιατί καθιστούν την άδεια ενεργή."); // return ACTION_OUTCOME_FAILURE; // } else { // info("employee's #0 leave #1 has been updated!", leaveHome.getInstance().getEmployee(), leaveHome.getInstance()); // leaveHome.update(); // return ACTION_OUTCOME_SUCCESS; // } // } else { // facesMessages.add(Severity.ERROR, "leave home #0 is not managed, thus #1 leave can't be modified.", leaveHome, leaveHome.getInstance()); // return ACTION_OUTCOME_FAILURE; // } // } // /** // * Checks if a leave should be set active in regards to the reference date. // * @param leave // * @param referenceDate // * @return // */ // protected boolean leaveShouldBeActivated(Leave leave, Date referenceDate) { // Date established = DateUtils.truncate(leave.getEstablished(), Calendar.DAY_OF_MONTH); // Date dueTo = DateUtils.truncate(leave.getDueTo(), Calendar.DAY_OF_MONTH); // Date today = DateUtils.truncate(referenceDate, Calendar.DAY_OF_MONTH); // if((established.before(today) || established.equals(today)) && (dueTo.after(today) || dueTo.equals(today))) { // return true; // } else return false; // } /** * TODO: We need to re-fresh the method * @param leave * @param addMessages * @return */ // protected boolean validateLeave(Leave leave, boolean addMessages) { // Date established = DateUtils.truncate(leave.getEstablished(), Calendar.DAY_OF_MONTH); // Date dueTo = DateUtils.truncate(leave.getDueTo(), Calendar.DAY_OF_MONTH); // /* check if the dates are correct */ // if (established.after(dueTo)) { // // if (addMessages) // facesMessages // .add(Severity.ERROR, // "H ημ/νία έναρξης είναι μεταγενέστερη της ημ/νιας λήξης της άδειας. Μάλλον πρέπει να κάνεις ενα διάλειμα."); // return false; // } // // Collection<Leave> current_leaves = getCoreSearching().getEmployeeLeaves(employeeHome.getInstance()); // for (Leave current_leave : current_leaves) { // if (current_leave.getId().equals(leave.getId())) // continue; // Date current_established = DateUtils.truncate(current_leave.getEstablished(), Calendar.DAY_OF_MONTH); // Date current_dueTo = DateUtils.truncate(current_leave.getDueTo(), Calendar.DAY_OF_MONTH); // if (DateUtils.isSameDay(established, current_established) || DateUtils.isSameDay(dueTo, current_dueTo)) { // if (addMessages) // facesMessages.add(Severity.ERROR, // "Υπάρχει ήδη άδεια με τις ημερομηνίες που εισάγατε. Μήπως να πιείτε κανα καφεδάκι ;"); // return false; // } // // if (DateUtils.isSameDay(established, current_dueTo)) { // // if (addMessages) // facesMessages // .add(Severity.ERROR, // "Η ημ/νία έναρξης της άδειας πρέπει να είναι μεταγενέστερη της ημ/νιας λήξης της προηγούμενης άδειας."); // return false; // } // // if ((established.before(current_established) && dueTo.after(current_established)) // || (established.after(current_established) && dueTo.before(current_dueTo)) // || (established.before(current_dueTo) && dueTo.after(current_dueTo))) { // if (addMessages) // facesMessages // .add(Severity.ERROR, // "Υπάρχει επικαλυπτόμενο διάστημα με υπάρχουσες άδειες. Μήπως να κάνεις ένα διάλειμα για καφεδάκο για να ξεσκοτίσεις ;"); // return false; // } // // } // // return true; // // } @In(required = true) private EmployeeLeaveHome employeeLeaveHome; @Transactional @RaiseEvent("leaveCreated") public String addEmployeeLeaveAction() { if (employeeHome.isManaged() && !(employeeLeaveHome.isManaged())) { Employee employee = getEntityManager().merge(employeeHome.getInstance()); EmployeeLeave newLeave = employeeLeaveHome.getInstance(); newLeave.setEmployee(employee); newLeave.setInsertedBy(getPrincipal()); newLeave.setInsertedOn(new Date()); newLeave.setActive(leaveShouldBeActivated(newLeave, new Date())); /* check if the employee has a current regular employment */ Employment employment = employee.getCurrentEmployment(); if (employment != null && employment.getType() == EmploymentType.REGULAR) { newLeave.setRegularSchool(employment.getSchool()); } if (validateLeave(newLeave, true)) { newLeave.setNumberOfDays(computeLeaveDuration(newLeave.getEstablished(), newLeave.getDueTo())); employeeLeaveHome.persist(); setLeaveDurarionInDaysHelper(0); setLeaveDurationInDaysWithoutWeekends(0); getEntityManager().flush(); info("leave #0 for employee #1 has been created", newLeave, employee); return ACTION_OUTCOME_SUCCESS; } else { return ACTION_OUTCOME_FAILURE; } } else { facesMessages.add(Severity.ERROR, "employee home #0 is not managed.", employeeHome); return ACTION_OUTCOME_FAILURE; } } @Transactional @RaiseEvent("leaveCreated") public String triggerLeaveAddedAction() { info("triggered!"); return ACTION_OUTCOME_SUCCESS; } @Transactional @RaiseEvent("leaveDeleted") public String deleteEmployeeLeaveAction() { if (employeeHome.isManaged() && employeeLeaveHome.isManaged()) { Employee employee = getEntityManager().merge(employeeHome.getInstance()); EmployeeLeave leave = employeeLeaveHome.getInstance(); info("deleting employee #0 leave #1", employee, leave); // for (TeachingHourCDR cdr : leave.getLeaveCDRs()) { // info("deleting leave's #0 cdr #1", employee, cdr); // cdr.setLeave(null); // getEntityManager().remove(cdr); // } // // leave.getLeaveCDRs().removeAll(leave.getLeaveCDRs()); leave.setActive(Boolean.FALSE); leave.setDeleted(Boolean.TRUE); leave.setDeletedOn(new Date()); leave.setDeletedBy(getPrincipal()); employeeLeaveHome.update(); info("leave #0 for employee #1 has been deleted", leave, employee); getEntityManager().flush(); return ACTION_OUTCOME_FAILURE; } else { facesMessages .add(Severity.ERROR, "employee home #0 or leave home #1 not managed.", employeeHome, employeeLeaveHome); return ACTION_OUTCOME_FAILURE; } } @Transactional @RaiseEvent("leaveModified") public String modifyEmployeeLeaveAction() { if (employeeLeaveHome.isManaged()) { Employee employee = getEntityManager().merge(employeeHome.getInstance()); EmployeeLeave newLeave = employeeLeaveHome.getInstance(); if (validateLeave(newLeave, true)) { newLeave.setActive(leaveShouldBeActivated(newLeave, new Date())); newLeave.setNumberOfDays(computeLeaveDuration(newLeave.getEstablished(), newLeave.getDueTo())); employeeLeaveHome.update(); getEntityManager().flush(); info("leave #0 for employee #1 has been modified", newLeave, employee); return ACTION_OUTCOME_SUCCESS; } else { return ACTION_OUTCOME_FAILURE; } } else { facesMessages.add(Severity.ERROR, "leave home #0 is not managed.", employeeLeaveHome); return ACTION_OUTCOME_FAILURE; } } private static String convertToHex(byte[] data) { StringBuffer buf = new StringBuffer(); for (int i = 0; i < data.length; i++) { int halfbyte = (data[i] >>> 4) & 0x0F; int two_halfs = 0; do { if ((0 <= halfbyte) && (halfbyte <= 9)) buf.append((char) ('0' + halfbyte)); else buf.append((char) ('a' + (halfbyte - 10))); halfbyte = data[i] & 0x0F; } while (two_halfs++ < 1); } return buf.toString(); } protected Map<String, Object> prepareParametersForLeavePrintout() throws NoSuchAlgorithmException, UnsupportedEncodingException { if (employeeLeaveHome.isManaged()) { Employee employee = getEntityManager().merge(employeeHome.getInstance()); EmployeeLeave leave = employeeLeaveHome.getInstance(); Map<String, Object> parameters = new HashMap<String, Object>(); Principal currentPrincipal = getPrincipal(); parameters.put("employeeForInformation", currentPrincipal.getRealName()); if(currentPrincipal.getInformationTelephone()!=null) { parameters.put("employeeForInformationTelephone", currentPrincipal.getInformationTelephone().getNumber()); } else parameters.put("employeeForInformationTelephone", ""); parameters.put("leaveRequestDate", leavePrintoutRequestDate); parameters.put("employeeName", employee.getFirstName()); parameters.put("employeeSurname", employee.getLastName()); parameters.put("employeeSpecialization", employee.getLastSpecialization().getTitle()); + parameters.put("employeeSpecializationCode", employee.getLastSpecialization().getId()); + Employment e = employee.getCurrentEmployment(); + if(e != null) { + parameters.put("employeeRegularSchool", e.getSchool().getTitle()); + } parameters.put("leaveDueToDate", leave.getDueTo()); parameters.put("leaveEstablishedDate", leave.getEstablished()); parameters.put("leaveDayDuration", leave.getEffectiveNumberOfDays()); parameters.put("employeeFatherName", employee.getFatherName()); parameters.put("referenceNumber", leavePrintoutReferenceNumber); parameters.put("printDate", leavePrintoutDate); parameters.put("signatureTitle", leavePrintoutSignature.getSignatureTitle()); parameters.put("signatureName", leavePrintoutSignature.getSignatureName()); /* according to the leave type, populate the parameters map accordinally */ if(leave.getEmployeeLeaveType().getLegacyCode().equals("33")) { parameters.put("numberOfBirthCertificate", printHelper.getFieldText1()); parameters.put("numberOfCertificateFamilyStatus", printHelper.getFieldText2()); } else if(leave.getEmployeeLeaveType().getLegacyCode().equals("35")) { parameters.put("doctorOpinionDate", printHelper.getFieldDate1()); parameters.put("doctorName", printHelper.getFieldText1()); } else if(leave.getEmployeeLeaveType().getLegacyCode().equals("36")) { parameters.put("leaveReason", printHelper.getFieldText1()); } else if(leave.getEmployeeLeaveType().getLegacyCode().equals("37")) { parameters.put("externalDecisionNumber", printHelper.getFieldText1()); } else if(leave.getEmployeeLeaveType().getLegacyCode().equals("38")) { parameters.put("externalDecisionNumber", printHelper.getFieldText1()); } else if(leave.getEmployeeLeaveType().getLegacyCode().equals("41")) { parameters.put("externalDecisionNumber", printHelper.getFieldText1()); } else if(leave.getEmployeeLeaveType().getLegacyCode().equals("42")) { parameters.put("externalDecisionDate", printHelper.getFieldDate1()); } else if(leave.getEmployeeLeaveType().getLegacyCode().equals("45")) { parameters.put("doctorOpinionDate", printHelper.getFieldDate1()); parameters.put("doctorName", printHelper.getFieldText1()); parameters.put("externalDecisionDate", printHelper.getFieldDate2()); } else if(leave.getEmployeeLeaveType().getLegacyCode().equals("46")) { parameters.put("doctorOpinionDate", printHelper.getFieldDate1()); parameters.put("doctorName", printHelper.getFieldText1()); parameters.put("externalDecisionDate", printHelper.getFieldDate2()); parameters.put("textField2", printHelper.getFieldText2()); parameters.put("numberOfBirthCertificate", printHelper.getFieldText3()); parameters.put("textField1", printHelper.getFieldText4()); } else if(leave.getEmployeeLeaveType().getLegacyCode().equals("47")) { parameters.put("doctorOpinionDate", printHelper.getFieldDate1()); parameters.put("doctorName", printHelper.getFieldText1()); } /* compute a SHA-1 digest */ MessageDigest digest = MessageDigest.getInstance("SHA"); digest.update(String.format("%s-%d-%d", parameters.toString(), System.currentTimeMillis(), parameters.hashCode()).getBytes("UTF-8")); byte[] digest_array = digest.digest(); parameters.put("localReferenceNumber", convertToHex(digest_array)); StringBuffer sb = new StringBuffer(); sb.append("<b>"); int counter = 1; for (PrintoutRecipients recipient : leavePrintounRecipientList) { sb.append(String.format("%d %s<br />", counter++, recipient.getRecipientTitle())); } sb.append("</b>"); parameters.put("notificationList", sb.toString()); return parameters; } else { return null; } } protected Map<String, Object> prepareSpecialParametersForLeavePrintout() throws NoSuchAlgorithmException, UnsupportedEncodingException { if (employeeLeaveHome.isManaged()) { Employee employee = getEntityManager().merge(employeeHome.getInstance()); EmployeeLeave leave = employeeLeaveHome.getInstance(); Map<String, Object> parameters = new HashMap<String, Object>(); /* according to the leave type, populate the parameters map accordinally */ if(leave.getEmployeeLeaveType().getLegacyCode().equals("33")) { parameters.put("numberOfBirthCertificate", printHelper.getFieldText1()); parameters.put("numberOfCertificateFamilyStatus", printHelper.getFieldText2()); } else if(leave.getEmployeeLeaveType().getLegacyCode().equals("35")) { parameters.put("doctorOpinionDate", printHelper.getFieldDate1()); parameters.put("doctorName", printHelper.getFieldText1()); } else if(leave.getEmployeeLeaveType().getLegacyCode().equals("36")) { parameters.put("leaveReason", printHelper.getFieldText1()); } else if(leave.getEmployeeLeaveType().getLegacyCode().equals("37")) { parameters.put("externalDecisionNumber", printHelper.getFieldText1()); } else if(leave.getEmployeeLeaveType().getLegacyCode().equals("38")) { parameters.put("externalDecisionNumber", printHelper.getFieldText1()); } else if(leave.getEmployeeLeaveType().getLegacyCode().equals("41")) { parameters.put("externalDecisionNumber", printHelper.getFieldText1()); } else if(leave.getEmployeeLeaveType().getLegacyCode().equals("42")) { parameters.put("externalDecisionDate", printHelper.getFieldDate1()); } else if(leave.getEmployeeLeaveType().getLegacyCode().equals("45")) { parameters.put("doctorOpinionDate", printHelper.getFieldDate1()); parameters.put("doctorName", printHelper.getFieldText1()); parameters.put("externalDecisionDate", printHelper.getFieldDate2()); } else if(leave.getEmployeeLeaveType().getLegacyCode().equals("46")) { parameters.put("doctorOpinionDate", printHelper.getFieldDate1()); parameters.put("doctorName", printHelper.getFieldText1()); parameters.put("externalDecisionDate", printHelper.getFieldDate2()); parameters.put("textField2", printHelper.getFieldText2()); parameters.put("numberOfBirthCertificate", printHelper.getFieldText3()); parameters.put("textField1", printHelper.getFieldText4()); } else if(leave.getEmployeeLeaveType().getLegacyCode().equals("47")) { parameters.put("doctorOpinionDate", printHelper.getFieldDate1()); parameters.put("doctorName", printHelper.getFieldText1()); } return parameters; } else { return null; } } protected Map<String, Object> prepareSpecialParametersForLeaveCoverPrintout() { if (employeeLeaveHome.isManaged()) { EmployeeLeave leave = employeeLeaveHome.getInstance(); Map<String, Object> parameters = new HashMap<String, Object>(); if(leave.getEmployeeLeaveType().getLegacyCode().equals("55")) { parameters.put("textField2", printHelper.getFieldText2()); parameters.put("textField3", printHelper.getFieldText3()); parameters.put("textField4", printHelper.getFieldText4()); parameters.put("textField5", printHelper.getFieldText5()); parameters.put("textField6", printHelper.getFieldText6()); parameters.put("textField1", printHelper.getFieldText8()); parameters.put("doctorName", printHelper.getFieldText7()); parameters.put("dateField1", printHelper.getFieldDate2()); } return parameters; } else { return null; } } public String printEmployeeLeaveCoverAction() { if (employeeLeaveHome.isManaged()) { Employee employee = getEntityManager().merge(employeeHome.getInstance()); EmployeeLeave leave = employeeLeaveHome.getInstance(); try { InputStream leaveTemplateInputStream = this.getClass().getResourceAsStream(String.format("/reports/leaveHandlingRequest_%s.jasper", leave.getEmployeeLeaveType().getLegacyCode())); Map<String, Object> parameters = prepareParametersForLeavePrintout(); /* add special parameters for the cover printout */ parameters.putAll(prepareSpecialParametersForLeaveCoverPrintout()); JRBeanCollectionDataSource main = new JRBeanCollectionDataSource(Collections.EMPTY_LIST); byte[] bytes = JasperRunManager.runReportToPdf(leaveTemplateInputStream, parameters, (JRDataSource) main); HttpServletResponse response = (HttpServletResponse) CoreUtils.getFacesContext().getExternalContext() .getResponse(); response.setContentType("application/pdf"); String pdfFile = String.format("ΑΔΕΙΑ_%s_%s_(%s).pdf", employee.getLastName(), employee.getFirstName(), employee.getLastSpecialization().getTitle()); // http://greenbytes.de/tech/webdav/rfc6266.html //response.addHeader("Content-Disposition", String.format("attachment; filename*=UTF-8 ' '%s", pdfFile)); response.addHeader("Content-Disposition", String.format("attachment; filename=ADEIA.pdf", pdfFile)); response.setContentLength(bytes.length); ServletOutputStream servletOutputStream = response.getOutputStream(); servletOutputStream.write(bytes, 0, bytes.length); servletOutputStream.flush(); servletOutputStream.close(); CoreUtils.getFacesContext().responseComplete(); } catch (Exception ex) { ex.printStackTrace(System.out); } info("leave #0 for employee #1 has been printed !", leave, employee); return ACTION_OUTCOME_SUCCESS; } else { return ACTION_OUTCOME_FAILURE; } } public String printEmployeeLeaveAction() { if (employeeLeaveHome.isManaged()) { Employee employee = getEntityManager().merge(employeeHome.getInstance()); EmployeeLeave leave = employeeLeaveHome.getInstance(); try { InputStream leaveTemplateInputStream = this.getClass().getResourceAsStream(String.format("/reports/leavePrintout_%s.jasper", leave.getEmployeeLeaveType().getLegacyCode())); Map<String, Object> parameters = prepareParametersForLeavePrintout(); /* add special parameters for the printout */ parameters.putAll(prepareSpecialParametersForLeavePrintout()); JRBeanCollectionDataSource main = new JRBeanCollectionDataSource(Collections.EMPTY_LIST); byte[] bytes = JasperRunManager.runReportToPdf(leaveTemplateInputStream, parameters, (JRDataSource) main); HttpServletResponse response = (HttpServletResponse) CoreUtils.getFacesContext().getExternalContext() .getResponse(); response.setContentType("application/pdf"); String pdfFile = String.format("ΑΔΕΙΑ_%s_%s_(%s).pdf", employee.getLastName(), employee.getFirstName(), employee.getLastSpecialization().getTitle()); // http://greenbytes.de/tech/webdav/rfc6266.html //response.addHeader("Content-Disposition", String.format("attachment; filename*=UTF-8 ' '%s", pdfFile)); response.addHeader("Content-Disposition", String.format("attachment; filename=ADEIA.pdf", pdfFile)); response.setContentLength(bytes.length); ServletOutputStream servletOutputStream = response.getOutputStream(); servletOutputStream.write(bytes, 0, bytes.length); servletOutputStream.flush(); servletOutputStream.close(); CoreUtils.getFacesContext().responseComplete(); } catch (Exception ex) { ex.printStackTrace(System.out); } info("leave #0 for employee #1 has been printed !", leave, employee); return ACTION_OUTCOME_SUCCESS; } else { return ACTION_OUTCOME_FAILURE; } } @Transactional public String printWordEmployeeLeaveAction() { if (employeeLeaveHome.isManaged()) { Employee employee = getEntityManager().merge(employeeHome.getInstance()); EmployeeLeave leave = employeeLeaveHome.getInstance(); OutputStream output = null; try { Map<String, Object> parameters = prepareParametersForLeavePrintout(); JRBeanCollectionDataSource main = new JRBeanCollectionDataSource(Collections.EMPTY_LIST); JasperPrint jasperPrint = JasperFillManager.fillReport(this.getClass().getResourceAsStream( "/reports/leavePrintout_31.jasper"), parameters, main); ByteArrayOutputStream bout = new ByteArrayOutputStream(); output = new BufferedOutputStream(bout); JROdtExporter exporter = new JROdtExporter(); exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, output); exporter.setParameter(JRExporterParameter.INPUT_FILE, "ffsd"); try { exporter.exportReport(); output.flush(); } catch (Throwable t) { System.err.println(t); } byte[] bytes = bout.toByteArray(); HttpServletResponse response = (HttpServletResponse) CoreUtils.getFacesContext().getExternalContext() .getResponse(); response.setContentType("application/vnd.oasis.opendocument.text"); String pdfFile = String.format("ΑΔΕΙΑ_%s_%s_(%s).pdf", employee.getLastName(), employee.getFirstName(), employee.getLastSpecialization().getTitle()); // http://greenbytes.de/tech/webdav/rfc6266.html //response.addHeader("Content-Disposition", String.format("attachment; filename*=UTF-8 ' '%s", pdfFile)); response.addHeader("Content-Disposition", String.format("attachment; filename=lalala.odt", pdfFile)); response.setContentLength(bytes.length); ServletOutputStream servletOutputStream = response.getOutputStream(); servletOutputStream.write(bytes, 0, bytes.length); servletOutputStream.flush(); servletOutputStream.close(); CoreUtils.getFacesContext().responseComplete(); } catch (Exception ex) { ex.printStackTrace(System.out); } info("leave #0 for employee #1 has been printed !", leave, employee); return ACTION_OUTCOME_SUCCESS; } else { return ACTION_OUTCOME_FAILURE; } } protected int computeLeaveDuration(Date fromDate, Date toDate) { if (fromDate != null && toDate != null) { long DAY_TIME_IN_MILLIS = 24 * 60 * 60 * 1000; long date1DaysMS = fromDate.getTime() - (fromDate.getTime() % DAY_TIME_IN_MILLIS); long date2DaysMS = toDate.getTime() - (toDate.getTime() % DAY_TIME_IN_MILLIS); long timeInMillisDiff = (date2DaysMS - date1DaysMS); return (int) (timeInMillisDiff / DAY_TIME_IN_MILLIS); } else return 0; } protected int computeLeaveDurationWithoutWeekend(Date fromDate, Date toDate) { if (fromDate != null && toDate != null) { int countDays = 0; Calendar fromCal = Calendar.getInstance(); fromCal.setTime(fromDate); while (!(DateUtils.isSameDay(fromDate, toDate))) { int dayOfWeek = fromCal.get(Calendar.DAY_OF_WEEK); fromCal.add(Calendar.DAY_OF_YEAR, 1); fromDate = fromCal.getTime(); if (dayOfWeek == Calendar.SATURDAY || dayOfWeek == Calendar.SUNDAY) continue; // don't count sundays and saturdays else countDays++; } return countDays; } else return 0; } public void silentlyComputeLeaveDuration() { EmployeeLeave leave = employeeLeaveHome.getInstance(); Date established = leave.getEstablished() != null ? DateUtils.truncate(leave.getEstablished(), Calendar.DAY_OF_MONTH) : null; Date dueTo = leave.getDueTo() != null ? DateUtils.truncate(leave.getDueTo(), Calendar.DAY_OF_MONTH) : null; if( established!=null && dueTo !=null && established.before(dueTo) ) { setLeaveDurarionInDaysHelper(computeLeaveDuration(established, dueTo)); setLeaveDurationInDaysWithoutWeekends(computeLeaveDurationWithoutWeekend(established, dueTo)); } else { setLeaveDurarionInDaysHelper(new Integer(0)); setLeaveDurationInDaysWithoutWeekends(new Integer(0)); } /* this method is being called when the user clicks one * of the two calendars, so reset the leaves effective * duration */ leave.setEffectiveNumberOfDays(null); } public void computeLeaveDuration() { EmployeeLeave leave = employeeLeaveHome.getInstance(); Date established = leave.getEstablished() != null ? DateUtils.truncate(leave.getEstablished(), Calendar.DAY_OF_MONTH) : null; Date dueTo = leave.getDueTo() != null ? DateUtils.truncate(leave.getDueTo(), Calendar.DAY_OF_MONTH) : null; info("computeLeaveDuration: established -> '#0', due to -> '#1'", established, dueTo); if (established == null || dueTo == null) { facesMessages.add(Severity.ERROR, "Πρέπει πρώτα να συμπληρώσετε την ημ/νια έναρξης και λήξεις της άδειας"); return; } /* check if the dates are correct */ if (established.after(dueTo)) { facesMessages .add(Severity.ERROR, "H ημ/νία έναρξης είναι μεταγενέστερη της ημ/νιας λήξης της άδειας. Μάλλον πρέπει να κάνεις ενα διάλειμα."); return; } setLeaveDurarionInDaysHelper(computeLeaveDuration(established, dueTo)); setLeaveDurationInDaysWithoutWeekends(computeLeaveDurationWithoutWeekend(established, dueTo)); } /** * TODO: We need to re-fresh the method * @param leave * @param addMessages * @return */ protected boolean validateLeave(EmployeeLeave leave, boolean addMessages) { Date established = DateUtils.truncate(leave.getEstablished(), Calendar.DAY_OF_MONTH); Date dueTo = DateUtils.truncate(leave.getDueTo(), Calendar.DAY_OF_MONTH); /* check if the dates are correct */ if (established.after(dueTo)) { if (addMessages) facesMessages .add(Severity.ERROR, "H ημ/νία έναρξης είναι μεταγενέστερη της ημ/νιας λήξης της άδειας. Μάλλον πρέπει να κάνεις ενα διάλειμα."); return false; } Collection<EmployeeLeave> current_leaves = getCoreSearching().getEmployeeLeaves2(employeeHome.getInstance()); for (EmployeeLeave current_leave : current_leaves) { if (current_leave.getId().equals(leave.getId())) continue; Date current_established = DateUtils.truncate(current_leave.getEstablished(), Calendar.DAY_OF_MONTH); Date current_dueTo = DateUtils.truncate(current_leave.getDueTo(), Calendar.DAY_OF_MONTH); if (DateUtils.isSameDay(established, current_established) || DateUtils.isSameDay(dueTo, current_dueTo)) { if (addMessages) facesMessages.add(Severity.ERROR, "Υπάρχει ήδη άδεια με τις ημερομηνίες που εισάγατε. Μήπως να πιείτε κανα καφεδάκι ;"); return false; } if (DateUtils.isSameDay(established, current_dueTo)) { if (addMessages) facesMessages .add(Severity.ERROR, "Η ημ/νία έναρξης της άδειας πρέπει να είναι μεταγενέστερη της ημ/νιας λήξης της προηγούμενης άδειας."); return false; } if ((established.before(current_established) && dueTo.after(current_established)) || (established.after(current_established) && dueTo.before(current_dueTo)) || (established.before(current_dueTo) && dueTo.after(current_dueTo))) { if (addMessages) facesMessages .add(Severity.ERROR, "Υπάρχει επικαλυπτόμενο διάστημα με υπάρχουσες άδειες. Μήπως να κάνεις ένα διάλειμα για καφεδάκο για να ξεσκοτίσεις ;"); return false; } } return true; } /** * Checks if a leave should be set active in regards to the reference date. * @param leave * @param referenceDate * @return */ protected boolean leaveShouldBeActivated(EmployeeLeave leave, Date referenceDate) { Date established = DateUtils.truncate(leave.getEstablished(), Calendar.DAY_OF_MONTH); Date dueTo = DateUtils.truncate(leave.getDueTo(), Calendar.DAY_OF_MONTH); Date today = DateUtils.truncate(referenceDate, Calendar.DAY_OF_MONTH); if ((established.before(today) || established.equals(today)) && (dueTo.after(today) || dueTo.equals(today))) { return true; } else return false; } /* this method is called when the user clicks the "add new leave" */ public void prepeareNewLeave() { employeeLeaveHome.clearInstance(); EmployeeLeave leave = employeeLeaveHome.getInstance(); leave.setEstablished(new Date()); leave.setDueTo(new Date()); leave.setEmployee(employeeHome.getInstance()); } /* this method is called when the user clicks the "print leave" */ public void prepeareForLeavePrint() { this.leavePrintoutDate = new Date(); Collection<SelectItem> list = new ArrayList<SelectItem>(); for (PrintoutRecipients r : getCoreSearching().getPrintoutRecipients(getEntityManager())) { list.add(new SelectItem(r, r.getRecipientTitle())); } this.leavePrintounRecipientListSource = new ArrayList<PrintoutRecipients>(getCoreSearching() .getPrintoutRecipients(getEntityManager())); this.leavePrintoutSignatureSource = getCoreSearching().getPrintoutSignatures(getEntityManager()); } /** * @return the leavePrintoutSignature */ public PrintoutSignatures getLeavePrintoutSignature() { return leavePrintoutSignature; } /** * @param leavePrintoutSignature the leavePrintoutSignature to set */ public void setLeavePrintoutSignature(PrintoutSignatures leavePrintoutSignature) { this.leavePrintoutSignature = leavePrintoutSignature; } /** * @return the leavePrintoutDate */ public Date getLeavePrintoutDate() { return leavePrintoutDate; } /** * @param leavePrintoutDate the leavePrintoutDate to set */ public void setLeavePrintoutDate(Date leavePrintoutDate) { this.leavePrintoutDate = leavePrintoutDate; } /** * @return the leavePrintoutRequestDate */ public Date getLeavePrintoutRequestDate() { return leavePrintoutRequestDate; } /** * @param leavePrintoutRequestDate the leavePrintoutRequestDate to set */ public void setLeavePrintoutRequestDate(Date leavePrintoutRequestDate) { this.leavePrintoutRequestDate = leavePrintoutRequestDate; } /** * @return the leavePrintoutReferenceNumber */ public String getLeavePrintoutReferenceNumber() { return leavePrintoutReferenceNumber; } /** * @param leavePrintoutReferenceNumber the leavePrintoutReferenceNumber to set */ public void setLeavePrintoutReferenceNumber(String leavePrintoutReferenceNumber) { this.leavePrintoutReferenceNumber = leavePrintoutReferenceNumber; } /** * @return the leavePrintoutSignatureSource */ public Collection<PrintoutSignatures> getLeavePrintoutSignatureSource() { return leavePrintoutSignatureSource; } /** * @param leavePrintoutSignatureSource the leavePrintoutSignatureSource to set */ public void setLeavePrintoutSignatureSource(Collection<PrintoutSignatures> leavePrintoutSignatureSource) { this.leavePrintoutSignatureSource = leavePrintoutSignatureSource; } /** * @return the leavePrintounRecipientListSource */ public List<PrintoutRecipients> getLeavePrintounRecipientListSource() { return leavePrintounRecipientListSource; } /** * @param leavePrintounRecipientListSource the leavePrintounRecipientListSource to set */ public void setLeavePrintounRecipientListSource(List<PrintoutRecipients> leavePrintounRecipientListSource) { this.leavePrintounRecipientListSource = leavePrintounRecipientListSource; } /** * @return the leavePrintounRecipientList */ public List<PrintoutRecipients> getLeavePrintounRecipientList() { return leavePrintounRecipientList; } /** * @param leavePrintounRecipientList the leavePrintounRecipientList to set */ public void setLeavePrintounRecipientList(List<PrintoutRecipients> leavePrintounRecipientList) { this.leavePrintounRecipientList = leavePrintounRecipientList; } /** * @return the leaveComputationReferenceDay */ public Date getLeaveComputationReferenceDay() { return leaveComputationReferenceDay; } /** * @param leaveComputationReferenceDay the leaveComputationReferenceDay to set */ public void setLeaveComputationReferenceDay(Date leaveComputationReferenceDay) { this.leaveComputationReferenceDay = leaveComputationReferenceDay; } /* this method is being called from the page containing a list of leaves and returns the CSS class that should be used by the leave row */ public String getTableCellClassForLeave(EmployeeLeave leave) { if(leave.isFuture()) { return "rich-table-future-leave"; } else if(leave.isCurrent()) { return "rich-table-current-leave"; } else if(leave.isPast()) { return "rich-table-past-leave"; } else return ""; } /** * @return the printHelper */ public PrintingHelper getPrintHelper() { return printHelper; } /** * @param printHelper the printHelper to set */ public void setPrintHelper(PrintingHelper printHelper) { this.printHelper = printHelper; } /** * @return the leaveDurarionInDaysHelper */ public Integer getLeaveDurarionInDaysHelper() { return leaveDurarionInDaysHelper; } /** * @param leaveDurarionInDaysHelper the leaveDurarionInDaysHelper to set */ public void setLeaveDurarionInDaysHelper(Integer leaveDurarionInDaysHelper) { this.leaveDurarionInDaysHelper = leaveDurarionInDaysHelper; } /** * @return the leaveDurationInDaysWithoutWeekends */ public Integer getLeaveDurationInDaysWithoutWeekends() { return leaveDurationInDaysWithoutWeekends; } /** * @param leaveDurationInDaysWithoutWeekends the leaveDurationInDaysWithoutWeekends to set */ public void setLeaveDurationInDaysWithoutWeekends(Integer leaveDurationInDaysWithoutWeekends) { this.leaveDurationInDaysWithoutWeekends = leaveDurationInDaysWithoutWeekends; } }
true
true
protected Map<String, Object> prepareParametersForLeavePrintout() throws NoSuchAlgorithmException, UnsupportedEncodingException { if (employeeLeaveHome.isManaged()) { Employee employee = getEntityManager().merge(employeeHome.getInstance()); EmployeeLeave leave = employeeLeaveHome.getInstance(); Map<String, Object> parameters = new HashMap<String, Object>(); Principal currentPrincipal = getPrincipal(); parameters.put("employeeForInformation", currentPrincipal.getRealName()); if(currentPrincipal.getInformationTelephone()!=null) { parameters.put("employeeForInformationTelephone", currentPrincipal.getInformationTelephone().getNumber()); } else parameters.put("employeeForInformationTelephone", ""); parameters.put("leaveRequestDate", leavePrintoutRequestDate); parameters.put("employeeName", employee.getFirstName()); parameters.put("employeeSurname", employee.getLastName()); parameters.put("employeeSpecialization", employee.getLastSpecialization().getTitle()); parameters.put("leaveDueToDate", leave.getDueTo()); parameters.put("leaveEstablishedDate", leave.getEstablished()); parameters.put("leaveDayDuration", leave.getEffectiveNumberOfDays()); parameters.put("employeeFatherName", employee.getFatherName()); parameters.put("referenceNumber", leavePrintoutReferenceNumber); parameters.put("printDate", leavePrintoutDate); parameters.put("signatureTitle", leavePrintoutSignature.getSignatureTitle()); parameters.put("signatureName", leavePrintoutSignature.getSignatureName()); /* according to the leave type, populate the parameters map accordinally */ if(leave.getEmployeeLeaveType().getLegacyCode().equals("33")) { parameters.put("numberOfBirthCertificate", printHelper.getFieldText1()); parameters.put("numberOfCertificateFamilyStatus", printHelper.getFieldText2()); } else if(leave.getEmployeeLeaveType().getLegacyCode().equals("35")) { parameters.put("doctorOpinionDate", printHelper.getFieldDate1()); parameters.put("doctorName", printHelper.getFieldText1()); } else if(leave.getEmployeeLeaveType().getLegacyCode().equals("36")) { parameters.put("leaveReason", printHelper.getFieldText1()); } else if(leave.getEmployeeLeaveType().getLegacyCode().equals("37")) { parameters.put("externalDecisionNumber", printHelper.getFieldText1()); } else if(leave.getEmployeeLeaveType().getLegacyCode().equals("38")) { parameters.put("externalDecisionNumber", printHelper.getFieldText1()); } else if(leave.getEmployeeLeaveType().getLegacyCode().equals("41")) { parameters.put("externalDecisionNumber", printHelper.getFieldText1()); } else if(leave.getEmployeeLeaveType().getLegacyCode().equals("42")) { parameters.put("externalDecisionDate", printHelper.getFieldDate1()); } else if(leave.getEmployeeLeaveType().getLegacyCode().equals("45")) { parameters.put("doctorOpinionDate", printHelper.getFieldDate1()); parameters.put("doctorName", printHelper.getFieldText1()); parameters.put("externalDecisionDate", printHelper.getFieldDate2()); } else if(leave.getEmployeeLeaveType().getLegacyCode().equals("46")) { parameters.put("doctorOpinionDate", printHelper.getFieldDate1()); parameters.put("doctorName", printHelper.getFieldText1()); parameters.put("externalDecisionDate", printHelper.getFieldDate2()); parameters.put("textField2", printHelper.getFieldText2()); parameters.put("numberOfBirthCertificate", printHelper.getFieldText3()); parameters.put("textField1", printHelper.getFieldText4()); } else if(leave.getEmployeeLeaveType().getLegacyCode().equals("47")) { parameters.put("doctorOpinionDate", printHelper.getFieldDate1()); parameters.put("doctorName", printHelper.getFieldText1()); } /* compute a SHA-1 digest */ MessageDigest digest = MessageDigest.getInstance("SHA"); digest.update(String.format("%s-%d-%d", parameters.toString(), System.currentTimeMillis(), parameters.hashCode()).getBytes("UTF-8")); byte[] digest_array = digest.digest(); parameters.put("localReferenceNumber", convertToHex(digest_array)); StringBuffer sb = new StringBuffer(); sb.append("<b>"); int counter = 1; for (PrintoutRecipients recipient : leavePrintounRecipientList) { sb.append(String.format("%d %s<br />", counter++, recipient.getRecipientTitle())); } sb.append("</b>"); parameters.put("notificationList", sb.toString()); return parameters; } else { return null; } }
protected Map<String, Object> prepareParametersForLeavePrintout() throws NoSuchAlgorithmException, UnsupportedEncodingException { if (employeeLeaveHome.isManaged()) { Employee employee = getEntityManager().merge(employeeHome.getInstance()); EmployeeLeave leave = employeeLeaveHome.getInstance(); Map<String, Object> parameters = new HashMap<String, Object>(); Principal currentPrincipal = getPrincipal(); parameters.put("employeeForInformation", currentPrincipal.getRealName()); if(currentPrincipal.getInformationTelephone()!=null) { parameters.put("employeeForInformationTelephone", currentPrincipal.getInformationTelephone().getNumber()); } else parameters.put("employeeForInformationTelephone", ""); parameters.put("leaveRequestDate", leavePrintoutRequestDate); parameters.put("employeeName", employee.getFirstName()); parameters.put("employeeSurname", employee.getLastName()); parameters.put("employeeSpecialization", employee.getLastSpecialization().getTitle()); parameters.put("employeeSpecializationCode", employee.getLastSpecialization().getId()); Employment e = employee.getCurrentEmployment(); if(e != null) { parameters.put("employeeRegularSchool", e.getSchool().getTitle()); } parameters.put("leaveDueToDate", leave.getDueTo()); parameters.put("leaveEstablishedDate", leave.getEstablished()); parameters.put("leaveDayDuration", leave.getEffectiveNumberOfDays()); parameters.put("employeeFatherName", employee.getFatherName()); parameters.put("referenceNumber", leavePrintoutReferenceNumber); parameters.put("printDate", leavePrintoutDate); parameters.put("signatureTitle", leavePrintoutSignature.getSignatureTitle()); parameters.put("signatureName", leavePrintoutSignature.getSignatureName()); /* according to the leave type, populate the parameters map accordinally */ if(leave.getEmployeeLeaveType().getLegacyCode().equals("33")) { parameters.put("numberOfBirthCertificate", printHelper.getFieldText1()); parameters.put("numberOfCertificateFamilyStatus", printHelper.getFieldText2()); } else if(leave.getEmployeeLeaveType().getLegacyCode().equals("35")) { parameters.put("doctorOpinionDate", printHelper.getFieldDate1()); parameters.put("doctorName", printHelper.getFieldText1()); } else if(leave.getEmployeeLeaveType().getLegacyCode().equals("36")) { parameters.put("leaveReason", printHelper.getFieldText1()); } else if(leave.getEmployeeLeaveType().getLegacyCode().equals("37")) { parameters.put("externalDecisionNumber", printHelper.getFieldText1()); } else if(leave.getEmployeeLeaveType().getLegacyCode().equals("38")) { parameters.put("externalDecisionNumber", printHelper.getFieldText1()); } else if(leave.getEmployeeLeaveType().getLegacyCode().equals("41")) { parameters.put("externalDecisionNumber", printHelper.getFieldText1()); } else if(leave.getEmployeeLeaveType().getLegacyCode().equals("42")) { parameters.put("externalDecisionDate", printHelper.getFieldDate1()); } else if(leave.getEmployeeLeaveType().getLegacyCode().equals("45")) { parameters.put("doctorOpinionDate", printHelper.getFieldDate1()); parameters.put("doctorName", printHelper.getFieldText1()); parameters.put("externalDecisionDate", printHelper.getFieldDate2()); } else if(leave.getEmployeeLeaveType().getLegacyCode().equals("46")) { parameters.put("doctorOpinionDate", printHelper.getFieldDate1()); parameters.put("doctorName", printHelper.getFieldText1()); parameters.put("externalDecisionDate", printHelper.getFieldDate2()); parameters.put("textField2", printHelper.getFieldText2()); parameters.put("numberOfBirthCertificate", printHelper.getFieldText3()); parameters.put("textField1", printHelper.getFieldText4()); } else if(leave.getEmployeeLeaveType().getLegacyCode().equals("47")) { parameters.put("doctorOpinionDate", printHelper.getFieldDate1()); parameters.put("doctorName", printHelper.getFieldText1()); } /* compute a SHA-1 digest */ MessageDigest digest = MessageDigest.getInstance("SHA"); digest.update(String.format("%s-%d-%d", parameters.toString(), System.currentTimeMillis(), parameters.hashCode()).getBytes("UTF-8")); byte[] digest_array = digest.digest(); parameters.put("localReferenceNumber", convertToHex(digest_array)); StringBuffer sb = new StringBuffer(); sb.append("<b>"); int counter = 1; for (PrintoutRecipients recipient : leavePrintounRecipientList) { sb.append(String.format("%d %s<br />", counter++, recipient.getRecipientTitle())); } sb.append("</b>"); parameters.put("notificationList", sb.toString()); return parameters; } else { return null; } }
diff --git a/src/java/axiom/objectmodel/dom/UrlAnalyzer.java b/src/java/axiom/objectmodel/dom/UrlAnalyzer.java index 930d7c7..31d126e 100644 --- a/src/java/axiom/objectmodel/dom/UrlAnalyzer.java +++ b/src/java/axiom/objectmodel/dom/UrlAnalyzer.java @@ -1,59 +1,61 @@ package axiom.objectmodel.dom; import java.io.IOException; import java.io.Reader; import java.util.regex.*; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.Token; import org.apache.lucene.analysis.TokenStream; public class UrlAnalyzer extends Analyzer { public TokenStream tokenStream(String fieldName, final Reader reader) { return new TokenStream() { private final Pattern stripTokens = Pattern.compile("^(http:/|www|com|org|net)"); private final Pattern endTokens = Pattern.compile("(\\.|/|-|_|\\?)$"); private boolean done = false; public Token next() throws IOException { if(!done){ final char[] buffer = new char[1]; StringBuffer sb = new StringBuffer(); int length = 0; Matcher matcher = endTokens.matcher(sb); boolean found = matcher.find(); while (!found && (length = reader.read(buffer)) != -1) { sb.append(buffer, 0, length); Matcher startMatcher = stripTokens.matcher(sb); if(startMatcher.matches()){ // strip prefix String tmp = sb.toString(); sb = new StringBuffer(tmp.replaceFirst("^(http:/|www|com|org|net)", "")); } matcher = endTokens.matcher(sb); found = matcher.find(); if(found){ - final String text = sb.toString().substring(0, matcher.end()-1); + final String text = sb.toString().substring(0, matcher.end()-1).toLowerCase(); int len = text.length(); if(len > 0){ // matched a token + System.out.println("-- token: ["+text+"]"); return new Token(text, 0, len); } else { // only contains a stop token, continue reading sb = new StringBuffer(); found = false; } } } // at end of string done = true; - final String value = sb.toString(); + final String value = sb.toString().toLowerCase(); + System.out.println("-- token: ["+value+"]"); return new Token(value, 0, value.length()); } return null; } }; } }
false
true
public TokenStream tokenStream(String fieldName, final Reader reader) { return new TokenStream() { private final Pattern stripTokens = Pattern.compile("^(http:/|www|com|org|net)"); private final Pattern endTokens = Pattern.compile("(\\.|/|-|_|\\?)$"); private boolean done = false; public Token next() throws IOException { if(!done){ final char[] buffer = new char[1]; StringBuffer sb = new StringBuffer(); int length = 0; Matcher matcher = endTokens.matcher(sb); boolean found = matcher.find(); while (!found && (length = reader.read(buffer)) != -1) { sb.append(buffer, 0, length); Matcher startMatcher = stripTokens.matcher(sb); if(startMatcher.matches()){ // strip prefix String tmp = sb.toString(); sb = new StringBuffer(tmp.replaceFirst("^(http:/|www|com|org|net)", "")); } matcher = endTokens.matcher(sb); found = matcher.find(); if(found){ final String text = sb.toString().substring(0, matcher.end()-1); int len = text.length(); if(len > 0){ // matched a token return new Token(text, 0, len); } else { // only contains a stop token, continue reading sb = new StringBuffer(); found = false; } } } // at end of string done = true; final String value = sb.toString(); return new Token(value, 0, value.length()); } return null; } }; }
public TokenStream tokenStream(String fieldName, final Reader reader) { return new TokenStream() { private final Pattern stripTokens = Pattern.compile("^(http:/|www|com|org|net)"); private final Pattern endTokens = Pattern.compile("(\\.|/|-|_|\\?)$"); private boolean done = false; public Token next() throws IOException { if(!done){ final char[] buffer = new char[1]; StringBuffer sb = new StringBuffer(); int length = 0; Matcher matcher = endTokens.matcher(sb); boolean found = matcher.find(); while (!found && (length = reader.read(buffer)) != -1) { sb.append(buffer, 0, length); Matcher startMatcher = stripTokens.matcher(sb); if(startMatcher.matches()){ // strip prefix String tmp = sb.toString(); sb = new StringBuffer(tmp.replaceFirst("^(http:/|www|com|org|net)", "")); } matcher = endTokens.matcher(sb); found = matcher.find(); if(found){ final String text = sb.toString().substring(0, matcher.end()-1).toLowerCase(); int len = text.length(); if(len > 0){ // matched a token System.out.println("-- token: ["+text+"]"); return new Token(text, 0, len); } else { // only contains a stop token, continue reading sb = new StringBuffer(); found = false; } } } // at end of string done = true; final String value = sb.toString().toLowerCase(); System.out.println("-- token: ["+value+"]"); return new Token(value, 0, value.length()); } return null; } }; }
diff --git a/core/src/main/java/org/kohsuke/stapler/jsr269/QueryParameterAnnotationProcessor.java b/core/src/main/java/org/kohsuke/stapler/jsr269/QueryParameterAnnotationProcessor.java index 628371865..df7de2509 100644 --- a/core/src/main/java/org/kohsuke/stapler/jsr269/QueryParameterAnnotationProcessor.java +++ b/core/src/main/java/org/kohsuke/stapler/jsr269/QueryParameterAnnotationProcessor.java @@ -1,77 +1,81 @@ package org.kohsuke.stapler.jsr269; import org.apache.commons.io.IOUtils; import org.kohsuke.MetaInfServices; import org.kohsuke.stapler.QueryParameter; import javax.annotation.processing.Processor; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; import javax.annotation.processing.SupportedSourceVersion; import javax.lang.model.SourceVersion; import javax.lang.model.element.Element; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.tools.FileObject; import java.io.IOException; import java.io.OutputStream; import java.util.HashSet; import java.util.Set; /** * @author Kohsuke Kawaguchi */ @SuppressWarnings({"Since15"}) @SupportedSourceVersion(SourceVersion.RELEASE_6) @SupportedAnnotationTypes("*") @MetaInfServices(Processor.class) public class QueryParameterAnnotationProcessor extends AbstractProcessorImpl { @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { try { Set<? extends Element> params = roundEnv.getElementsAnnotatedWith(QueryParameter.class); Set<ExecutableElement> methods = new HashSet<ExecutableElement>(); - for (Element p : params) - methods.add((ExecutableElement)p.getEnclosingElement()); + for (Element p : params) { + // at least in JDK7u3, if some of the annotation types doesn't resolve, they end up showing up + // in the result from the getElementsAnnotatedWith method. This check rejects those bogus matches + if (p.getAnnotation(QueryParameter.class)!=null) + methods.add((ExecutableElement)p.getEnclosingElement()); + } for (ExecutableElement m : methods) { write(m); } } catch (IOException e) { error(e); } catch (RuntimeException e) { // javac sucks at reporting errors in annotation processors e.printStackTrace(); throw e; } catch (Error e) { e.printStackTrace(); throw e; } return false; } /** * @param m * Method whose parameter has {@link QueryParameter} */ private void write(ExecutableElement m) throws IOException { StringBuffer buf = new StringBuffer(); for( VariableElement p : m.getParameters() ) { if(buf.length()>0) buf.append(','); buf.append(p.getSimpleName()); } TypeElement t = (TypeElement)m.getEnclosingElement(); FileObject f = createResource(t.getQualifiedName().toString().replace('.', '/') + "/" + m.getSimpleName() + ".stapler"); notice("Generating " + f, m); OutputStream os = f.openOutputStream(); try { IOUtils.write(buf, os, "UTF-8"); } finally { os.close(); } } }
true
true
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { try { Set<? extends Element> params = roundEnv.getElementsAnnotatedWith(QueryParameter.class); Set<ExecutableElement> methods = new HashSet<ExecutableElement>(); for (Element p : params) methods.add((ExecutableElement)p.getEnclosingElement()); for (ExecutableElement m : methods) { write(m); } } catch (IOException e) { error(e); } catch (RuntimeException e) { // javac sucks at reporting errors in annotation processors e.printStackTrace(); throw e; } catch (Error e) { e.printStackTrace(); throw e; } return false; }
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { try { Set<? extends Element> params = roundEnv.getElementsAnnotatedWith(QueryParameter.class); Set<ExecutableElement> methods = new HashSet<ExecutableElement>(); for (Element p : params) { // at least in JDK7u3, if some of the annotation types doesn't resolve, they end up showing up // in the result from the getElementsAnnotatedWith method. This check rejects those bogus matches if (p.getAnnotation(QueryParameter.class)!=null) methods.add((ExecutableElement)p.getEnclosingElement()); } for (ExecutableElement m : methods) { write(m); } } catch (IOException e) { error(e); } catch (RuntimeException e) { // javac sucks at reporting errors in annotation processors e.printStackTrace(); throw e; } catch (Error e) { e.printStackTrace(); throw e; } return false; }
diff --git a/src/org/objectweb/proactive/examples/nbody/barneshut/Domain.java b/src/org/objectweb/proactive/examples/nbody/barneshut/Domain.java index 9a8df9c74..d6a645d64 100644 --- a/src/org/objectweb/proactive/examples/nbody/barneshut/Domain.java +++ b/src/org/objectweb/proactive/examples/nbody/barneshut/Domain.java @@ -1,145 +1,144 @@ /* * ################################################################ * * ProActive: The Java(TM) library for Parallel, Distributed, * Concurrent computing with Security and Mobility * * Copyright (C) 1997-2005 INRIA/University of Nice-Sophia Antipolis * Contact: [email protected] * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * Initial developer(s): The ProActive Team * http://www.inria.fr/oasis/ProActive/contacts.html * Contributor(s): * * Nicolas BUSSIERE * Fabien GARGNE * Christian KNOFF * Julien PUGLIESI * * * ################################################################ */ package org.objectweb.proactive.examples.nbody.barneshut; import java.io.Serializable; import java.net.InetAddress; import java.net.UnknownHostException; import org.apache.log4j.Logger; import org.objectweb.proactive.core.util.log.Loggers; import org.objectweb.proactive.core.util.log.ProActiveLogger; import org.objectweb.proactive.examples.nbody.common.Displayer; public class Domain implements Serializable { protected static final Logger logger = ProActiveLogger.getLogger(Loggers.EXAMPLES); /** a unique number to differentiate this Domain from the others */ private int identification; /** to display on which host we're running */ private String hostName = "unknown"; /** used for synchronization between domains */ private Maestro maestro; /** optional, to have a nice output with java3D */ private Displayer display; /** the planet associed to the domain */ private Planet rock; /** OctTree for this domain */ private OctTree octTree; /** * Empty constructor, required by ProActive */ public Domain() { } /** * Creates a container for a Planet, within a region of space. * @param i The unique identifier of this Domain * @param planet The Planet controlled by this Domain * @param oct The OctTree corresponding of this Domain */ public Domain(Integer i, Planet planet, OctTree oct) { this.identification = i.intValue(); this.rock = planet; this.octTree = oct; try { this.hostName = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { e.printStackTrace(); } } /** * Sets some execution-time related variables. * @param dp The Displayer used to show on screen the movement of the objects. * @param master Maestro used to synchronize the computations. */ public void init(Displayer dp, Maestro master) { this.display = dp; // even if Displayer is null this.maestro = master; maestro.notifyFinished(this.identification, this.rock); // say we're ready to start . } /** * Calculate the force exerted on this body and move it. */ public void moveBody() { Force force = this.octTree.computeForce(this.rock); this.rock.moveWithForce(force); } /** * Move the body, Draw the planet on the displayer and inform the Maestro */ public void moveAndDraw() { this.maestro.notifyFinished(this.identification, this.rock); this.moveBody(); if (this.display == null) { // if no display, only the first Domain outputs message to say recompute is going on if (this.identification == 0) { logger.info("Compute movement."); } } else { - this.display.drawBody((int) this.rock.x, (int) this.rock.y, - (int) this.rock.z, (int) this.rock.vx, (int) this.rock.vy, - (int) this.rock.vz, (int) this.rock.mass, + this.display.drawBody(this.rock.x, this.rock.y, this.rock.z, + this.rock.vx, this.rock.vy, this.rock.vz, (int) this.rock.mass, (int) this.rock.diameter, this.identification, this.hostName); } } /** * Method called when the object is redeployed on a new Node (Fault recovery, or migration). */ private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { in.defaultReadObject(); try { this.hostName = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { hostName = "unknown"; e.printStackTrace(); } } }
true
true
public void moveAndDraw() { this.maestro.notifyFinished(this.identification, this.rock); this.moveBody(); if (this.display == null) { // if no display, only the first Domain outputs message to say recompute is going on if (this.identification == 0) { logger.info("Compute movement."); } } else { this.display.drawBody((int) this.rock.x, (int) this.rock.y, (int) this.rock.z, (int) this.rock.vx, (int) this.rock.vy, (int) this.rock.vz, (int) this.rock.mass, (int) this.rock.diameter, this.identification, this.hostName); } }
public void moveAndDraw() { this.maestro.notifyFinished(this.identification, this.rock); this.moveBody(); if (this.display == null) { // if no display, only the first Domain outputs message to say recompute is going on if (this.identification == 0) { logger.info("Compute movement."); } } else { this.display.drawBody(this.rock.x, this.rock.y, this.rock.z, this.rock.vx, this.rock.vy, this.rock.vz, (int) this.rock.mass, (int) this.rock.diameter, this.identification, this.hostName); } }
diff --git a/ratpack-groovy/src/main/java/ratpack/groovy/templating/internal/TemplateCompiler.java b/ratpack-groovy/src/main/java/ratpack/groovy/templating/internal/TemplateCompiler.java index ef4827c4e..6bb8eb8a6 100644 --- a/ratpack-groovy/src/main/java/ratpack/groovy/templating/internal/TemplateCompiler.java +++ b/ratpack-groovy/src/main/java/ratpack/groovy/templating/internal/TemplateCompiler.java @@ -1,66 +1,67 @@ /* * Copyright 2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ratpack.groovy.templating.internal; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; import io.netty.util.CharsetUtil; import org.codehaus.groovy.control.CompilationFailedException; import ratpack.groovy.script.internal.ScriptEngine; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; public class TemplateCompiler { private final Logger logger = Logger.getLogger(getClass().getName()); private final ByteBufAllocator byteBufAllocator; private boolean verbose; private final TemplateParser parser = new TemplateParser(); private final ScriptEngine<DefaultTemplateScript> scriptEngine; public TemplateCompiler(ScriptEngine<DefaultTemplateScript> scriptEngine, ByteBufAllocator byteBufAllocator) { this(scriptEngine, false, byteBufAllocator); } public TemplateCompiler(ScriptEngine<DefaultTemplateScript> scriptEngine, boolean verbose, ByteBufAllocator byteBufAllocator) { this.scriptEngine = scriptEngine; this.verbose = verbose; this.byteBufAllocator = byteBufAllocator; } public CompiledTemplate compile(ByteBuf templateSource, String name) throws CompilationFailedException, IOException { ByteBuf scriptSource = byteBufAllocator.buffer(templateSource.capacity()); parser.parse(templateSource, scriptSource); String scriptSourceString = scriptSource.toString(CharsetUtil.UTF_8); + scriptSource.release(); if (verbose && logger.isLoggable(Level.INFO)) { logger.info("\n-- script source --\n" + scriptSourceString + "\n-- script end --\n"); } try { Class<DefaultTemplateScript> scriptClass = scriptEngine.compile(name, scriptSourceString); return new CompiledTemplate(name, scriptClass); } catch (Exception e) { throw new InvalidTemplateException(name, "compilation failure", e); } } }
true
true
public CompiledTemplate compile(ByteBuf templateSource, String name) throws CompilationFailedException, IOException { ByteBuf scriptSource = byteBufAllocator.buffer(templateSource.capacity()); parser.parse(templateSource, scriptSource); String scriptSourceString = scriptSource.toString(CharsetUtil.UTF_8); if (verbose && logger.isLoggable(Level.INFO)) { logger.info("\n-- script source --\n" + scriptSourceString + "\n-- script end --\n"); } try { Class<DefaultTemplateScript> scriptClass = scriptEngine.compile(name, scriptSourceString); return new CompiledTemplate(name, scriptClass); } catch (Exception e) { throw new InvalidTemplateException(name, "compilation failure", e); } }
public CompiledTemplate compile(ByteBuf templateSource, String name) throws CompilationFailedException, IOException { ByteBuf scriptSource = byteBufAllocator.buffer(templateSource.capacity()); parser.parse(templateSource, scriptSource); String scriptSourceString = scriptSource.toString(CharsetUtil.UTF_8); scriptSource.release(); if (verbose && logger.isLoggable(Level.INFO)) { logger.info("\n-- script source --\n" + scriptSourceString + "\n-- script end --\n"); } try { Class<DefaultTemplateScript> scriptClass = scriptEngine.compile(name, scriptSourceString); return new CompiledTemplate(name, scriptClass); } catch (Exception e) { throw new InvalidTemplateException(name, "compilation failure", e); } }
diff --git a/src/de/anormalmedia/vividswinganimations/bounds/BoundsAnimation.java b/src/de/anormalmedia/vividswinganimations/bounds/BoundsAnimation.java index 7789170..c1d6ef9 100644 --- a/src/de/anormalmedia/vividswinganimations/bounds/BoundsAnimation.java +++ b/src/de/anormalmedia/vividswinganimations/bounds/BoundsAnimation.java @@ -1,67 +1,67 @@ package de.anormalmedia.vividswinganimations.bounds; import java.awt.Component; import java.awt.Rectangle; import de.anormalmedia.vividswinganimations.AbstractAnimation; public class BoundsAnimation extends AbstractAnimation { private Component target; private final Rectangle targetBounds; private Rectangle initialBounds; public BoundsAnimation( Component target, Rectangle targetBounds ) { this.target = target; this.targetBounds = targetBounds; } @Override public void prepare() { initialBounds = target.getBounds(); super.prepare(); } @Override public void animate( long timeProgress ) { int nextX = targetBounds.x; int nextY = targetBounds.y; int nextWidth = targetBounds.width; int nextHeight = targetBounds.height; if( targetBounds.x != -1 ) { int deltaX = targetBounds.x - initialBounds.x; nextX = initialBounds.x + (int)Math.round( (float)deltaX / (float)getDuration() * (float)timeProgress ); } if( targetBounds.y != -1 ) { int deltaY = targetBounds.y - initialBounds.y; nextY = initialBounds.y + (int)Math.round( (float)deltaY / (float)getDuration() * (float)timeProgress ); } if( targetBounds.width != -1 ) { int deltaWidth = targetBounds.width - initialBounds.width; nextWidth = initialBounds.width + (int)Math.round( (float)deltaWidth / (float)getDuration() * (float)timeProgress ); } if( targetBounds.height != -1 ) { int deltaHeight = targetBounds.height - initialBounds.height; nextHeight = initialBounds.height + (int)Math.round( (float)deltaHeight / (float)getDuration() * (float)timeProgress ); } Rectangle currentBounds = target.getBounds(); if( targetBounds.x == -1 ) { nextX = currentBounds.x; } if( targetBounds.y == -1 ) { nextY = currentBounds.y; } if( targetBounds.width == -1 ) { nextWidth = currentBounds.width; } - if( targetBounds.width == -1 ) { + if( targetBounds.height == -1 ) { nextHeight = currentBounds.height; } target.setBounds( nextX, nextY, nextWidth, nextHeight ); } public Rectangle getTargetBounds() { return targetBounds; } }
true
true
public void animate( long timeProgress ) { int nextX = targetBounds.x; int nextY = targetBounds.y; int nextWidth = targetBounds.width; int nextHeight = targetBounds.height; if( targetBounds.x != -1 ) { int deltaX = targetBounds.x - initialBounds.x; nextX = initialBounds.x + (int)Math.round( (float)deltaX / (float)getDuration() * (float)timeProgress ); } if( targetBounds.y != -1 ) { int deltaY = targetBounds.y - initialBounds.y; nextY = initialBounds.y + (int)Math.round( (float)deltaY / (float)getDuration() * (float)timeProgress ); } if( targetBounds.width != -1 ) { int deltaWidth = targetBounds.width - initialBounds.width; nextWidth = initialBounds.width + (int)Math.round( (float)deltaWidth / (float)getDuration() * (float)timeProgress ); } if( targetBounds.height != -1 ) { int deltaHeight = targetBounds.height - initialBounds.height; nextHeight = initialBounds.height + (int)Math.round( (float)deltaHeight / (float)getDuration() * (float)timeProgress ); } Rectangle currentBounds = target.getBounds(); if( targetBounds.x == -1 ) { nextX = currentBounds.x; } if( targetBounds.y == -1 ) { nextY = currentBounds.y; } if( targetBounds.width == -1 ) { nextWidth = currentBounds.width; } if( targetBounds.width == -1 ) { nextHeight = currentBounds.height; } target.setBounds( nextX, nextY, nextWidth, nextHeight ); }
public void animate( long timeProgress ) { int nextX = targetBounds.x; int nextY = targetBounds.y; int nextWidth = targetBounds.width; int nextHeight = targetBounds.height; if( targetBounds.x != -1 ) { int deltaX = targetBounds.x - initialBounds.x; nextX = initialBounds.x + (int)Math.round( (float)deltaX / (float)getDuration() * (float)timeProgress ); } if( targetBounds.y != -1 ) { int deltaY = targetBounds.y - initialBounds.y; nextY = initialBounds.y + (int)Math.round( (float)deltaY / (float)getDuration() * (float)timeProgress ); } if( targetBounds.width != -1 ) { int deltaWidth = targetBounds.width - initialBounds.width; nextWidth = initialBounds.width + (int)Math.round( (float)deltaWidth / (float)getDuration() * (float)timeProgress ); } if( targetBounds.height != -1 ) { int deltaHeight = targetBounds.height - initialBounds.height; nextHeight = initialBounds.height + (int)Math.round( (float)deltaHeight / (float)getDuration() * (float)timeProgress ); } Rectangle currentBounds = target.getBounds(); if( targetBounds.x == -1 ) { nextX = currentBounds.x; } if( targetBounds.y == -1 ) { nextY = currentBounds.y; } if( targetBounds.width == -1 ) { nextWidth = currentBounds.width; } if( targetBounds.height == -1 ) { nextHeight = currentBounds.height; } target.setBounds( nextX, nextY, nextWidth, nextHeight ); }
diff --git a/plugins/org.eclipse.bpel.model/src/org/eclipse/bpel/model/util/ElementPlacer.java b/plugins/org.eclipse.bpel.model/src/org/eclipse/bpel/model/util/ElementPlacer.java index c757d9ce..509e2986 100644 --- a/plugins/org.eclipse.bpel.model/src/org/eclipse/bpel/model/util/ElementPlacer.java +++ b/plugins/org.eclipse.bpel.model/src/org/eclipse/bpel/model/util/ElementPlacer.java @@ -1,324 +1,324 @@ /******************************************************************************* * Copyright (c) 2007 Intel Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Dennis Ushakov, Intel - Initial API and Implementation * Oleg Danilov, Intel * *******************************************************************************/ package org.eclipse.bpel.model.util; import java.util.Arrays; import java.util.HashMap; import java.util.List; import org.eclipse.bpel.model.ExtensionActivity; import org.eclipse.wst.wsdl.WSDLElement; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.Text; public class ElementPlacer { private static HashMap<String, List<String>> mapper = new HashMap<String, List<String>>(); private static final String ACTIVITY = "activity"; static { // TODO: (DU) add other activities // Process String processElements[] = { BPELConstants.ND_EXTENSIONS, BPELConstants.ND_IMPORT, BPELConstants.ND_PARTNER_LINKS, BPELConstants.ND_MESSAGE_EXCHANGES, BPELConstants.ND_VARIABLES, BPELConstants.ND_CORRELATION_SETS, BPELConstants.ND_FAULT_HANDLERS, BPELConstants.ND_EVENT_HANDLERS, ACTIVITY }; mapper.put(BPELConstants.ND_PROCESS, Arrays.asList(processElements)); // FaultHandlers String faultHandlersElements[] = { BPELConstants.ND_CATCH, BPELConstants.ND_CATCH_ALL }; mapper.put(BPELConstants.ND_FAULT_HANDLERS, Arrays .asList(faultHandlersElements)); // EventHandlers String eventHandlersElements[] = { BPELConstants.ND_ON_EVENT, BPELConstants.ND_ON_ALARM }; mapper.put(BPELConstants.ND_EVENT_HANDLERS, Arrays .asList(eventHandlersElements)); // Invoke String invokeElements[] = { BPELConstants.ND_CORRELATIONS, BPELConstants.ND_CATCH, BPELConstants.ND_CATCH_ALL, BPELConstants.ND_COMPENSATION_HANDLER, BPELConstants.ND_TO_PARTS, BPELConstants.ND_FROM_PARTS }; mapper.put(BPELConstants.ND_INVOKE, Arrays.asList(invokeElements)); // While String whileElements[] = { BPELConstants.ND_CONDITION, ACTIVITY }; mapper.put(BPELConstants.ND_WHILE, Arrays.asList(whileElements)); // ForEach String forEachElements[] = { BPELConstants.ND_START_COUNTER_VALUE, BPELConstants.ND_FINAL_COUNTER_VALUE, BPELConstants.ND_COMPLETION_CONDITION, ACTIVITY }; mapper.put(BPELConstants.ND_FOR_EACH, Arrays.asList(forEachElements)); // RepeatUntil String repeatElements[] = { ACTIVITY, BPELConstants.ND_CONDITION }; mapper .put(BPELConstants.ND_REPEAT_UNTIL, Arrays .asList(repeatElements)); // If String ifElements[] = { BPELConstants.ND_CONDITION, ACTIVITY, BPELConstants.ND_ELSEIF, BPELConstants.ND_ELSE }; mapper.put(BPELConstants.ND_IF, Arrays.asList(ifElements)); // ElseIf String elseIfElements[] = { BPELConstants.ND_CONDITION, ACTIVITY }; mapper.put(BPELConstants.ND_ELSEIF, Arrays.asList(elseIfElements)); } public static void placeChild(WSDLElement parent, Node child) { Element parentElement = parent.getElement(); if (parent instanceof ExtensionActivity){ parentElement = ReconciliationHelper.getExtensionActivityChildElement(parentElement); } List<String> nodeTypeList = mapper.get(parentElement.getLocalName()); if (nodeTypeList != null) { String nodeName = child.getLocalName(); String nodeType = findType(nodeName, nodeTypeList); if (nodeType != null) { Node beforeElement = parentElement.getFirstChild(); while (beforeElement != null && (!isPreviousType(nodeType, findType(beforeElement .getLocalName(), nodeTypeList), nodeTypeList) || beforeElement .getNodeType() != Node.ELEMENT_NODE)) { beforeElement = beforeElement.getNextSibling(); } while (beforeElement != null && (isType(beforeElement.getLocalName(), nodeType) || beforeElement .getNodeType() != Node.ELEMENT_NODE)) { beforeElement = beforeElement.getNextSibling(); } ElementPlacer.niceInsertBefore(parent, child, beforeElement); return; } } ElementPlacer.niceAppend(parent, child); } private static String findType(String nodeName, List<String> nodeTypeList) { for (String nodeType : nodeTypeList) { if (isType(nodeName, nodeType)) { return nodeType; } } return null; } private static boolean isPreviousType(String typeName1, String typeName2, List<String> nodeTypeList) { int type1Index = nodeTypeList.indexOf(typeName1); int type2Index = nodeTypeList.indexOf(typeName2); return type1Index < type2Index || (type2Index < 0 && type1Index >= 0); } private static boolean isType(String nodeName, String typeName) { return ACTIVITY.equals(typeName) ? isActivity(nodeName) : typeName .equals(nodeName); } private static boolean isActivity(String nodeName) { return BPELConstants.ND_ASSIGN.equals(nodeName) || BPELConstants.ND_COMPENSATE.equals(nodeName) || BPELConstants.ND_COMPENSATE_SCOPE.equals(nodeName) || BPELConstants.ND_EMPTY.equals(nodeName) || BPELConstants.ND_EXIT.equals(nodeName) || BPELConstants.ND_EXTENSION_ACTIVITY.equals(nodeName) || BPELConstants.ND_FLOW.equals(nodeName) || BPELConstants.ND_FOR_EACH.equals(nodeName) || BPELConstants.ND_IF.equals(nodeName) || BPELConstants.ND_INVOKE.equals(nodeName) || BPELConstants.ND_PICK.equals(nodeName) || BPELConstants.ND_RECEIVE.equals(nodeName) || BPELConstants.ND_REPEAT_UNTIL.equals(nodeName) || BPELConstants.ND_REPLY.equals(nodeName) || BPELConstants.ND_RETHROW.equals(nodeName) || BPELConstants.ND_SCOPE.equals(nodeName) || BPELConstants.ND_SEQUENCE.equals(nodeName) || BPELConstants.ND_THROW.equals(nodeName) || BPELConstants.ND_VALIDATE.equals(nodeName) || BPELConstants.ND_WAIT.equals(nodeName) || BPELConstants.ND_WHILE.equals(nodeName) || BPELConstants.ND_OPAQUEACTIVITY.equals(nodeName); } public static void niceInsertBefore(WSDLElement parent, Node newChild, Node referenceChild) { boolean was = ReconciliationHelper.isUpdatingDom(parent); Element parentElement = parent.getElement(); if (parent instanceof ExtensionActivity){ parentElement = ReconciliationHelper.getExtensionActivityChildElement(parentElement); } ReconciliationHelper.setUpdatingDom(parent, true); Node child = (referenceChild == null) ? parentElement.getLastChild() : referenceChild.getPreviousSibling(); // DO: parentElement has no children ( <tag /> ) if (child == null) { StringBuffer indent = new StringBuffer(); for (Node ancestor = parentElement.getParentNode(); ancestor != null && ancestor.getNodeType() != Node.DOCUMENT_NODE; ancestor = ancestor .getParentNode()) { indent.append(" "); } Text text = parentElement.getOwnerDocument().createTextNode( "\n" + indent + " "); parentElement.insertBefore(text, referenceChild); text = parentElement.getOwnerDocument().createTextNode( "\n" + indent); referenceChild = parentElement.insertBefore(text, referenceChild); parentElement.insertBefore(newChild, referenceChild); return; } while (child != null) { short nodeType = child.getNodeType(); if (nodeType == Node.ELEMENT_NODE) break; if (nodeType != Node.TEXT_NODE) { child = child.getPreviousSibling(); continue; } Text text = (Text) child; String data = text.getData(); int index = data.lastIndexOf('\n'); if (index == -1) { child = child.getPreviousSibling(); continue; } StringBuffer indent = new StringBuffer(); for (Node ancestor = parentElement.getParentNode(); ancestor != null && ancestor.getNodeType() != Node.DOCUMENT_NODE; ancestor = ancestor .getParentNode()) { indent.append(" "); } if (index + 1 < data.length() && data.charAt(index + 1) == '\r') { index++; } text.replaceData(index + 1, data.length() - index - 1, indent + " "); // DO: // Format children of the newChild. // https://bugs.eclipse.org/bugs/show_bug.cgi?id=335458 // traverse the child's descendants also, inserting the // proper indentation for each StringBuffer childIndent = new StringBuffer(indent); Node nextNewChild = newChild; Node innerChild = newChild.getFirstChild(); while (innerChild != null) { // add "\n" + indent before every child Node nextInnerChild = innerChild; while (nextInnerChild != null) { boolean textNodeIsWhitespaceOnly = false; - if (nextInnerChild.getNodeType() == Node.TEXT_NODE) { - String content = nextInnerChild.getTextContent(); + if (nextInnerChild instanceof Text) { + String content = ((Text)nextInnerChild).getData(); textNodeIsWhitespaceOnly = (content==null || content.trim().isEmpty()); } if (textNodeIsWhitespaceOnly) { // remove an old indentation nextNewChild.removeChild(nextInnerChild); } else { nextNewChild.insertBefore(nextNewChild.getOwnerDocument() .createTextNode("\n" + childIndent + " "), nextInnerChild); } nextInnerChild = nextInnerChild.getNextSibling(); } // add "\n" after the last child nextNewChild.appendChild(nextNewChild.getOwnerDocument() .createTextNode("\n" + childIndent + " ")); childIndent.append(" "); nextNewChild = innerChild; innerChild = innerChild.getFirstChild(); } if (referenceChild != null) { indent.append(" "); } text = parentElement.getOwnerDocument().createTextNode( "\n" + indent); parentElement.insertBefore(text, referenceChild); referenceChild = text; break; } parentElement.insertBefore(newChild, referenceChild); ReconciliationHelper.setUpdatingDom(parent, was); } public static void niceAppend(WSDLElement parent, Node child) { niceInsertBefore(parent, child, null); } public static void niceRemoveChild(WSDLElement parent, Node child) { boolean was = ReconciliationHelper.isUpdatingDom(parent); ReconciliationHelper.setUpdatingDom(parent, true); Element parseElement = parent.getElement(); if (parent instanceof ExtensionActivity) { parseElement = ReconciliationHelper.getExtensionActivityChildElement(parseElement); } boolean done = false; Node previous = child.getPreviousSibling(); if (previous != null && previous.getNodeType() == Node.TEXT_NODE) { Text text = (Text) previous; String data = text.getData(); int index = data.lastIndexOf('\n'); if (index != -1) { if (index - 1 > 0 && data.charAt(index - 1) == '\r') { text.deleteData(index - 1, data.length() - index + 1); } else { text.deleteData(index, data.length() - index); } done = true; } } if (!done) { for (Node next = child.getNextSibling(); next != null; next = next .getNextSibling()) { if (next.getNodeType() == Node.TEXT_NODE) { Text text = (Text) next; String data = text.getData(); int index = data.indexOf('\n'); if (index != -1) { if (index + 1 < data.length() && data.charAt(index + 1) == '\r') { text.deleteData(0, index + 2); } else { text.deleteData(0, index + 1); } break; } continue; } if (next.getNodeType() == Node.ELEMENT_NODE) { break; } } } parseElement.removeChild(child); ReconciliationHelper.setUpdatingDom(parent, was); } }
true
true
public static void niceInsertBefore(WSDLElement parent, Node newChild, Node referenceChild) { boolean was = ReconciliationHelper.isUpdatingDom(parent); Element parentElement = parent.getElement(); if (parent instanceof ExtensionActivity){ parentElement = ReconciliationHelper.getExtensionActivityChildElement(parentElement); } ReconciliationHelper.setUpdatingDom(parent, true); Node child = (referenceChild == null) ? parentElement.getLastChild() : referenceChild.getPreviousSibling(); // DO: parentElement has no children ( <tag /> ) if (child == null) { StringBuffer indent = new StringBuffer(); for (Node ancestor = parentElement.getParentNode(); ancestor != null && ancestor.getNodeType() != Node.DOCUMENT_NODE; ancestor = ancestor .getParentNode()) { indent.append(" "); } Text text = parentElement.getOwnerDocument().createTextNode( "\n" + indent + " "); parentElement.insertBefore(text, referenceChild); text = parentElement.getOwnerDocument().createTextNode( "\n" + indent); referenceChild = parentElement.insertBefore(text, referenceChild); parentElement.insertBefore(newChild, referenceChild); return; } while (child != null) { short nodeType = child.getNodeType(); if (nodeType == Node.ELEMENT_NODE) break; if (nodeType != Node.TEXT_NODE) { child = child.getPreviousSibling(); continue; } Text text = (Text) child; String data = text.getData(); int index = data.lastIndexOf('\n'); if (index == -1) { child = child.getPreviousSibling(); continue; } StringBuffer indent = new StringBuffer(); for (Node ancestor = parentElement.getParentNode(); ancestor != null && ancestor.getNodeType() != Node.DOCUMENT_NODE; ancestor = ancestor .getParentNode()) { indent.append(" "); } if (index + 1 < data.length() && data.charAt(index + 1) == '\r') { index++; } text.replaceData(index + 1, data.length() - index - 1, indent + " "); // DO: // Format children of the newChild. // https://bugs.eclipse.org/bugs/show_bug.cgi?id=335458 // traverse the child's descendants also, inserting the // proper indentation for each StringBuffer childIndent = new StringBuffer(indent); Node nextNewChild = newChild; Node innerChild = newChild.getFirstChild(); while (innerChild != null) { // add "\n" + indent before every child Node nextInnerChild = innerChild; while (nextInnerChild != null) { boolean textNodeIsWhitespaceOnly = false; if (nextInnerChild.getNodeType() == Node.TEXT_NODE) { String content = nextInnerChild.getTextContent(); textNodeIsWhitespaceOnly = (content==null || content.trim().isEmpty()); } if (textNodeIsWhitespaceOnly) { // remove an old indentation nextNewChild.removeChild(nextInnerChild); } else { nextNewChild.insertBefore(nextNewChild.getOwnerDocument() .createTextNode("\n" + childIndent + " "), nextInnerChild); } nextInnerChild = nextInnerChild.getNextSibling(); } // add "\n" after the last child nextNewChild.appendChild(nextNewChild.getOwnerDocument() .createTextNode("\n" + childIndent + " ")); childIndent.append(" "); nextNewChild = innerChild; innerChild = innerChild.getFirstChild(); } if (referenceChild != null) { indent.append(" "); } text = parentElement.getOwnerDocument().createTextNode( "\n" + indent); parentElement.insertBefore(text, referenceChild); referenceChild = text; break; } parentElement.insertBefore(newChild, referenceChild); ReconciliationHelper.setUpdatingDom(parent, was); }
public static void niceInsertBefore(WSDLElement parent, Node newChild, Node referenceChild) { boolean was = ReconciliationHelper.isUpdatingDom(parent); Element parentElement = parent.getElement(); if (parent instanceof ExtensionActivity){ parentElement = ReconciliationHelper.getExtensionActivityChildElement(parentElement); } ReconciliationHelper.setUpdatingDom(parent, true); Node child = (referenceChild == null) ? parentElement.getLastChild() : referenceChild.getPreviousSibling(); // DO: parentElement has no children ( <tag /> ) if (child == null) { StringBuffer indent = new StringBuffer(); for (Node ancestor = parentElement.getParentNode(); ancestor != null && ancestor.getNodeType() != Node.DOCUMENT_NODE; ancestor = ancestor .getParentNode()) { indent.append(" "); } Text text = parentElement.getOwnerDocument().createTextNode( "\n" + indent + " "); parentElement.insertBefore(text, referenceChild); text = parentElement.getOwnerDocument().createTextNode( "\n" + indent); referenceChild = parentElement.insertBefore(text, referenceChild); parentElement.insertBefore(newChild, referenceChild); return; } while (child != null) { short nodeType = child.getNodeType(); if (nodeType == Node.ELEMENT_NODE) break; if (nodeType != Node.TEXT_NODE) { child = child.getPreviousSibling(); continue; } Text text = (Text) child; String data = text.getData(); int index = data.lastIndexOf('\n'); if (index == -1) { child = child.getPreviousSibling(); continue; } StringBuffer indent = new StringBuffer(); for (Node ancestor = parentElement.getParentNode(); ancestor != null && ancestor.getNodeType() != Node.DOCUMENT_NODE; ancestor = ancestor .getParentNode()) { indent.append(" "); } if (index + 1 < data.length() && data.charAt(index + 1) == '\r') { index++; } text.replaceData(index + 1, data.length() - index - 1, indent + " "); // DO: // Format children of the newChild. // https://bugs.eclipse.org/bugs/show_bug.cgi?id=335458 // traverse the child's descendants also, inserting the // proper indentation for each StringBuffer childIndent = new StringBuffer(indent); Node nextNewChild = newChild; Node innerChild = newChild.getFirstChild(); while (innerChild != null) { // add "\n" + indent before every child Node nextInnerChild = innerChild; while (nextInnerChild != null) { boolean textNodeIsWhitespaceOnly = false; if (nextInnerChild instanceof Text) { String content = ((Text)nextInnerChild).getData(); textNodeIsWhitespaceOnly = (content==null || content.trim().isEmpty()); } if (textNodeIsWhitespaceOnly) { // remove an old indentation nextNewChild.removeChild(nextInnerChild); } else { nextNewChild.insertBefore(nextNewChild.getOwnerDocument() .createTextNode("\n" + childIndent + " "), nextInnerChild); } nextInnerChild = nextInnerChild.getNextSibling(); } // add "\n" after the last child nextNewChild.appendChild(nextNewChild.getOwnerDocument() .createTextNode("\n" + childIndent + " ")); childIndent.append(" "); nextNewChild = innerChild; innerChild = innerChild.getFirstChild(); } if (referenceChild != null) { indent.append(" "); } text = parentElement.getOwnerDocument().createTextNode( "\n" + indent); parentElement.insertBefore(text, referenceChild); referenceChild = text; break; } parentElement.insertBefore(newChild, referenceChild); ReconciliationHelper.setUpdatingDom(parent, was); }
diff --git a/src/xmlvm2objc/compat-lib/java/org/xmlvm/iphone/UIAlertView.java b/src/xmlvm2objc/compat-lib/java/org/xmlvm/iphone/UIAlertView.java index 92ed2401..d2881107 100644 --- a/src/xmlvm2objc/compat-lib/java/org/xmlvm/iphone/UIAlertView.java +++ b/src/xmlvm2objc/compat-lib/java/org/xmlvm/iphone/UIAlertView.java @@ -1,294 +1,294 @@ package org.xmlvm.iphone; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Font; import java.awt.GradientPaint; import java.awt.Graphics2D; import java.awt.Stroke; import java.awt.geom.AffineTransform; import java.awt.geom.Path2D; import java.util.ArrayList; import java.util.List; import org.xmlvm.iphone.internal.Display; import org.xmlvm.iphone.internal.Simulator; public class UIAlertView extends UIView { class ButtonClickCallback extends UIControlDelegate { private int buttonIndex; public ButtonClickCallback(int buttonIndex) { this.buttonIndex = buttonIndex; } @Override public void raiseEvent() { buttonClicked(buttonIndex); } } private static final int FRAME_SIZE = 2; private static final int EDGE_DIAMETER = 16; private static final int INSETS = 6; private static final int LABEL_INSETS = 12; private static final int FULL_BUTTON_WIDTH = 260; private static final int SMALL_BUTTON_WIDTH = 124; private static final int BUTTON_HEIGHT = 42; private static final int TITLE_FONT_SIZE = 16; private static final int MESSAGE_FONT_SIZE = 14; private String title; private String message; private UIAlertViewDelegate delegate; private String cancelButtonTitle; private List<UIButton> buttons = new ArrayList<UIButton>(); private UILabel titleView; private UILabel messageView; public UIAlertView(String title, String message, UIAlertViewDelegate delegate, String cancelButtonTitle) { this.title = title; this.message = message; this.delegate = delegate; this.cancelButtonTitle = cancelButtonTitle; titleView = new UILabel(); titleView.setBackgroundColor(new Color(0, 0, 0, 0)); titleView.setFontColor(Color.WHITE); titleView.setShadowColor(Color.DARK_GRAY); titleView.setShadowOffset(new CGSize(0, -1)); titleView.setFont(new Font("Arial", Font.BOLD, TITLE_FONT_SIZE)); titleView.setTextAlignment(UITextAlignment.UITextAlignmentCenter); if (title != null && title.length() > 0) { titleView.setText(title); addSubview(titleView); } messageView = new UILabel(); messageView.setBackgroundColor(new Color(0, 0, 0, 0)); messageView.setFontColor(Color.WHITE); messageView.setShadowColor(Color.DARK_GRAY); messageView.setShadowOffset(new CGSize(0, -1)); messageView.setFont(new Font("Arial", Font.BOLD, MESSAGE_FONT_SIZE)); messageView.setTextAlignment(UITextAlignment.UITextAlignmentCenter); if (message != null && message.length() > 0) { messageView.setText(message); addSubview(messageView); } initTransformation(); // TODO: This will be done by layout() - remove this this.setFrame(new CGRect(196, 130, 90, 60)); } public void show() { if (buttons.size() == 0) { addButtonWithTitle(cancelButtonTitle); } ((Display) Simulator.getDisplay()).setAlertView(this); doLayout(); setNeedsDisplay(); } public void setTitle(String title) { this.title = title; titleView.setText(title); if (title != null && title.length() > 0 && !getSubviews().contains(titleView)) { addSubview(titleView); } if ((title == null || title.length() == 0) && getSubviews().contains(titleView)) { titleView.removeFromSuperview(); } } public int addButtonWithTitle(String title) { UIButton button = UIButton.buttonWithType(UIButtonType.UIButtonTypeRoundedRect); button.setTitle(title, UIControlState.UIControlStateNormal); button.setEdgeDiameter(8); button.addTarget(new ButtonClickCallback(buttons.size()), UIControl.UIControlEventTouchUpInside); // Set color, opacity and font style/color button.setFont(new Font("Arial", Font.BOLD, 14)); button.setTitleColor(Color.WHITE, UIControlState.UIControlStateNormal); button.setTitleShadowColor(Color.DARK_GRAY, UIControlState.UIControlStateNormal); button.setTitleShadowOffset(new CGSize(0, -1), UIControlState.UIControlStateNormal); button.setBackgroundColor(new Color(150, 170, 190)); button.setAlpha(200); button.setEdgeDiameter(8); addSubview(button); buttons.add(button); return buttons.size() - 1; } public void drawRect(CGRect rect) { setTransformForThisView(); Graphics2D g = CGContext.theContext.graphicsContext; CGRect displayRect = getDisplayRect(); int x = (int) displayRect.origin.x; int y = (int) displayRect.origin.y; int w = (int) displayRect.size.width; int h = (int) displayRect.size.height; // Paint dark screen overlay g.setPaint(new Color(20, 20, 20, 80)); g.fillRect(0, 0, getScreenWidth(), getScreenHeight()); // Paint the surrounding border Stroke stroke = g.getStroke(); g.setPaint(Color.WHITE); g.setStroke(new BasicStroke(FRAME_SIZE)); g.drawRoundRect(x, y, w, h, EDGE_DIAMETER, EDGE_DIAMETER); g.setStroke(stroke); // Paint the view's background g.setPaint(new Color(5, 10, 80, 180)); g.fillRoundRect(x + 1, y + 1, w - 2, h - 2, EDGE_DIAMETER, EDGE_DIAMETER); // Paint the background's shine Path2D shineShape = new Path2D.Double(); shineShape.moveTo(x + FRAME_SIZE - 1, y + FRAME_SIZE + EDGE_DIAMETER / 2 + 4); shineShape.lineTo(x + FRAME_SIZE - 1, y + FRAME_SIZE + EDGE_DIAMETER / 2); shineShape.quadTo(x, y, x + FRAME_SIZE + EDGE_DIAMETER / 2, y + FRAME_SIZE - 1); shineShape.lineTo(x + w - FRAME_SIZE - EDGE_DIAMETER / 2, y + FRAME_SIZE - 1); shineShape.quadTo(x + w, y, x + w - FRAME_SIZE + 1, y + FRAME_SIZE + EDGE_DIAMETER / 2); shineShape.lineTo(x + w - FRAME_SIZE + 1, y + FRAME_SIZE + EDGE_DIAMETER / 2 + 4); shineShape.quadTo(x + w / 2, y + 42, x + FRAME_SIZE - 1, y + FRAME_SIZE + EDGE_DIAMETER / 2 + 4); GradientPaint shineGradient = new GradientPaint(0, y + 1, new Color(150, 190, 200, 180), 0, y + 28, new Color(135, 153, 171, 180)); g.setPaint(shineGradient); g.fill(shineShape); restoreLastTransform(); for (UIView v : subViews) { v.drawRect(rect); } } private void doLayout() { int x; int y; int width; int height; // Compute AlertView's boundary if (buttons.size() != 2) { width = 2 * FRAME_SIZE + 2 * INSETS + FULL_BUTTON_WIDTH; height = 2 * FRAME_SIZE + LABEL_INSETS + buttons.size() * INSETS + (buttons.size() * BUTTON_HEIGHT); } else { width = 2 * FRAME_SIZE + 4 * INSETS + 2 * SMALL_BUTTON_WIDTH; height = 2 * FRAME_SIZE + LABEL_INSETS + INSETS + BUTTON_HEIGHT; } if (title != null && title.length() > 0) { height += LABEL_INSETS + TITLE_FONT_SIZE; } if (message != null && message.length() > 0) { height += LABEL_INSETS + MESSAGE_FONT_SIZE; } x = getScreenWidth() / 2 - width / 2; y = getScreenHeight() / 2 - height / 2; setFrame(new CGRect(x, y, width, height)); // Compute title and message boundaries int buttonYOffset = FRAME_SIZE; int messageYOffset = FRAME_SIZE; if (title != null && title.length() > 0) { buttonYOffset += LABEL_INSETS + TITLE_FONT_SIZE; messageYOffset += LABEL_INSETS + TITLE_FONT_SIZE; titleView.setFrame(new CGRect(FRAME_SIZE + INSETS, LABEL_INSETS, - buttons.size() != 2 ? FULL_BUTTON_WIDTH : SMALL_BUTTON_WIDTH, TITLE_FONT_SIZE)); + buttons.size() != 2 ? FULL_BUTTON_WIDTH : 2 * (SMALL_BUTTON_WIDTH + INSETS), + TITLE_FONT_SIZE)); } if (message != null && message.length() > 0) { buttonYOffset += LABEL_INSETS + MESSAGE_FONT_SIZE; - messageView - .setFrame(new CGRect(FRAME_SIZE + INSETS, LABEL_INSETS + messageYOffset, - buttons.size() != 2 ? FULL_BUTTON_WIDTH : SMALL_BUTTON_WIDTH, - MESSAGE_FONT_SIZE)); + messageView.setFrame(new CGRect(FRAME_SIZE + INSETS, LABEL_INSETS + messageYOffset, + buttons.size() != 2 ? FULL_BUTTON_WIDTH : 2 * (SMALL_BUTTON_WIDTH + INSETS), + MESSAGE_FONT_SIZE)); } // Compute buttons' boundaries if (buttons.size() != 2) { for (int i = 0; i < buttons.size(); i++) { int buttonY = LABEL_INSETS + i * (INSETS + BUTTON_HEIGHT); UIButton button = buttons.get(i); button.setFrame(new CGRect(FRAME_SIZE + INSETS, buttonYOffset + buttonY, FULL_BUTTON_WIDTH, BUTTON_HEIGHT)); } } else { UIButton b1 = buttons.get(0); UIButton b2 = buttons.get(1); b1.setFrame(new CGRect(FRAME_SIZE + INSETS, buttonYOffset + LABEL_INSETS, SMALL_BUTTON_WIDTH, BUTTON_HEIGHT)); - b2.setFrame(new CGRect(FRAME_SIZE + 3 * INSETS, buttonYOffset + LABEL_INSETS, - SMALL_BUTTON_WIDTH, BUTTON_HEIGHT)); + b2.setFrame(new CGRect(FRAME_SIZE + 3 * INSETS + SMALL_BUTTON_WIDTH, buttonYOffset + + LABEL_INSETS, SMALL_BUTTON_WIDTH, BUTTON_HEIGHT)); } } private void initTransformation() { int orientation = Simulator.getStatusBarOrientation(); switch (orientation) { case UIInterfaceOrientation.UIInterfaceOrientationPortrait: // this.setFrame(new CGRect(0, 0, 320, statusBarHeight)); this.affineTransform = new AffineTransform(); break; case UIInterfaceOrientation.UIInterfaceOrientationLandscapeRight: // this.setFrame(new CGRect(0, 0, 480, statusBarHeight)); this.affineTransform = new AffineTransform(); this.affineTransform.translate(0, 320 + 320 / 2); this.affineTransform.rotate((float) ((Math.PI / 180) * -90)); break; case UIInterfaceOrientation.UIInterfaceOrientationLandscapeLeft: // this.setFrame(new CGRect(0, 0, 480, statusBarHeight)); this.affineTransform = new AffineTransform(); this.affineTransform.translate(320, 0); this.affineTransform.rotate((float) ((Math.PI / 180) * 90)); break; case UIInterfaceOrientation.UIInterfaceOrientationPortraitUpsideDown: // TODO break; } computeCombinedTransforms(); } private void buttonClicked(int buttonIndex) { delegate.clickedButtonAtIndex(this, buttonIndex); if (((Display) Simulator.getDisplay()).getAlertView() == this) { ((Display) Simulator.getDisplay()).setAlertView(null); } setNeedsDisplay(); } private int getScreenWidth() { return Simulator.getStatusBarOrientation() == UIInterfaceOrientation.UIInterfaceOrientationPortrait || Simulator.getStatusBarOrientation() == UIInterfaceOrientation.UIInterfaceOrientationPortraitUpsideDown ? 320 : 480; } private int getScreenHeight() { return Simulator.getStatusBarOrientation() == UIInterfaceOrientation.UIInterfaceOrientationPortrait || Simulator.getStatusBarOrientation() == UIInterfaceOrientation.UIInterfaceOrientationPortraitUpsideDown ? 480 : 320; } }
false
true
private void doLayout() { int x; int y; int width; int height; // Compute AlertView's boundary if (buttons.size() != 2) { width = 2 * FRAME_SIZE + 2 * INSETS + FULL_BUTTON_WIDTH; height = 2 * FRAME_SIZE + LABEL_INSETS + buttons.size() * INSETS + (buttons.size() * BUTTON_HEIGHT); } else { width = 2 * FRAME_SIZE + 4 * INSETS + 2 * SMALL_BUTTON_WIDTH; height = 2 * FRAME_SIZE + LABEL_INSETS + INSETS + BUTTON_HEIGHT; } if (title != null && title.length() > 0) { height += LABEL_INSETS + TITLE_FONT_SIZE; } if (message != null && message.length() > 0) { height += LABEL_INSETS + MESSAGE_FONT_SIZE; } x = getScreenWidth() / 2 - width / 2; y = getScreenHeight() / 2 - height / 2; setFrame(new CGRect(x, y, width, height)); // Compute title and message boundaries int buttonYOffset = FRAME_SIZE; int messageYOffset = FRAME_SIZE; if (title != null && title.length() > 0) { buttonYOffset += LABEL_INSETS + TITLE_FONT_SIZE; messageYOffset += LABEL_INSETS + TITLE_FONT_SIZE; titleView.setFrame(new CGRect(FRAME_SIZE + INSETS, LABEL_INSETS, buttons.size() != 2 ? FULL_BUTTON_WIDTH : SMALL_BUTTON_WIDTH, TITLE_FONT_SIZE)); } if (message != null && message.length() > 0) { buttonYOffset += LABEL_INSETS + MESSAGE_FONT_SIZE; messageView .setFrame(new CGRect(FRAME_SIZE + INSETS, LABEL_INSETS + messageYOffset, buttons.size() != 2 ? FULL_BUTTON_WIDTH : SMALL_BUTTON_WIDTH, MESSAGE_FONT_SIZE)); } // Compute buttons' boundaries if (buttons.size() != 2) { for (int i = 0; i < buttons.size(); i++) { int buttonY = LABEL_INSETS + i * (INSETS + BUTTON_HEIGHT); UIButton button = buttons.get(i); button.setFrame(new CGRect(FRAME_SIZE + INSETS, buttonYOffset + buttonY, FULL_BUTTON_WIDTH, BUTTON_HEIGHT)); } } else { UIButton b1 = buttons.get(0); UIButton b2 = buttons.get(1); b1.setFrame(new CGRect(FRAME_SIZE + INSETS, buttonYOffset + LABEL_INSETS, SMALL_BUTTON_WIDTH, BUTTON_HEIGHT)); b2.setFrame(new CGRect(FRAME_SIZE + 3 * INSETS, buttonYOffset + LABEL_INSETS, SMALL_BUTTON_WIDTH, BUTTON_HEIGHT)); } }
private void doLayout() { int x; int y; int width; int height; // Compute AlertView's boundary if (buttons.size() != 2) { width = 2 * FRAME_SIZE + 2 * INSETS + FULL_BUTTON_WIDTH; height = 2 * FRAME_SIZE + LABEL_INSETS + buttons.size() * INSETS + (buttons.size() * BUTTON_HEIGHT); } else { width = 2 * FRAME_SIZE + 4 * INSETS + 2 * SMALL_BUTTON_WIDTH; height = 2 * FRAME_SIZE + LABEL_INSETS + INSETS + BUTTON_HEIGHT; } if (title != null && title.length() > 0) { height += LABEL_INSETS + TITLE_FONT_SIZE; } if (message != null && message.length() > 0) { height += LABEL_INSETS + MESSAGE_FONT_SIZE; } x = getScreenWidth() / 2 - width / 2; y = getScreenHeight() / 2 - height / 2; setFrame(new CGRect(x, y, width, height)); // Compute title and message boundaries int buttonYOffset = FRAME_SIZE; int messageYOffset = FRAME_SIZE; if (title != null && title.length() > 0) { buttonYOffset += LABEL_INSETS + TITLE_FONT_SIZE; messageYOffset += LABEL_INSETS + TITLE_FONT_SIZE; titleView.setFrame(new CGRect(FRAME_SIZE + INSETS, LABEL_INSETS, buttons.size() != 2 ? FULL_BUTTON_WIDTH : 2 * (SMALL_BUTTON_WIDTH + INSETS), TITLE_FONT_SIZE)); } if (message != null && message.length() > 0) { buttonYOffset += LABEL_INSETS + MESSAGE_FONT_SIZE; messageView.setFrame(new CGRect(FRAME_SIZE + INSETS, LABEL_INSETS + messageYOffset, buttons.size() != 2 ? FULL_BUTTON_WIDTH : 2 * (SMALL_BUTTON_WIDTH + INSETS), MESSAGE_FONT_SIZE)); } // Compute buttons' boundaries if (buttons.size() != 2) { for (int i = 0; i < buttons.size(); i++) { int buttonY = LABEL_INSETS + i * (INSETS + BUTTON_HEIGHT); UIButton button = buttons.get(i); button.setFrame(new CGRect(FRAME_SIZE + INSETS, buttonYOffset + buttonY, FULL_BUTTON_WIDTH, BUTTON_HEIGHT)); } } else { UIButton b1 = buttons.get(0); UIButton b2 = buttons.get(1); b1.setFrame(new CGRect(FRAME_SIZE + INSETS, buttonYOffset + LABEL_INSETS, SMALL_BUTTON_WIDTH, BUTTON_HEIGHT)); b2.setFrame(new CGRect(FRAME_SIZE + 3 * INSETS + SMALL_BUTTON_WIDTH, buttonYOffset + LABEL_INSETS, SMALL_BUTTON_WIDTH, BUTTON_HEIGHT)); } }
diff --git a/src/main/ed/appserver/URLFixer.java b/src/main/ed/appserver/URLFixer.java index 80f013c7b..0e6639e8d 100644 --- a/src/main/ed/appserver/URLFixer.java +++ b/src/main/ed/appserver/URLFixer.java @@ -1,203 +1,206 @@ // URLFixer.java /** * Copyright (C) 2008 10gen Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ed.appserver; import java.io.*; import ed.util.*; import ed.net.httpserver.*; public class URLFixer { public static final boolean NOCDN = Config.get().getBoolean( "NO-CDN" ); public URLFixer( HttpRequest request , AppRequest ar ){ this( getStaticPrefix( request , ar ) , getStaticSuffix( request , ar ) , ar.getContext() ); _ar = ar; } public URLFixer( String cdnPrefix , String cdnSuffix , AppContext context ){ _cdnPrefix = cdnPrefix; _cdnSuffix = cdnSuffix; _context = context; } public String fix( String url ){ StringBuilder buf = new StringBuilder(); fix( url , buf ); return buf.toString(); } public void fix( String url , Appendable a ){ if ( url == null ) return; if ( url.length() == 0 ) return; // parse out options boolean nocdn = false; boolean forcecdn = false; if ( url.startsWith( "NOCDN" ) ){ nocdn = true; url = url.substring( 5 ); } else if ( url.startsWith( "CDN/" ) ){ forcecdn = true; url = url.substring( 3 ); } boolean doVersioning = true; // weird special cases if ( ! url.startsWith( "/" ) ){ if ( _ar == null || url.startsWith( "http://" ) || url.startsWith( "https://" ) ){ nocdn = true; doVersioning = false; } else { url = _ar.getDirectory() + url; } } if ( url.startsWith( "//" ) ){ // this is the special //www.slashdot.org/foo.jpg syntax nocdn = true; doVersioning = false; } // setup String uri = url; int questionIndex = url.indexOf( "?" ); if ( questionIndex >= 0 ) uri = uri.substring( 0 , questionIndex ); String cdnTags = null; if ( uri.equals( "/~f" ) || uri.equals( "/~~/f" ) ){ cdnTags = ""; // TODO: should i put a version or timestamp here? } else { cdnTags = _cdnSuffix; if ( cdnTags == null ) cdnTags = ""; else if ( cdnTags.length() > 0 ) cdnTags += "&"; if ( doVersioning && _context != null ){ File f = _context.getFileSafe( uri ); - if ( f != null && f.exists() ){ + if ( f == null ) + cdnTags += "lm=cantfind"; + else if ( ! f.exists() ) + cdnTags += "lm=doesntexist"; + else cdnTags += "lm=" + f.lastModified(); - } } } // print try { if ( forcecdn || ( ! nocdn && cdnTags != null ) ) a.append( cdnPrefix() ); a.append( url ); if ( cdnTags != null && cdnTags.length() > 0 ){ if ( questionIndex < 0 ) a.append( "?" ); else a.append( "&" ); a.append( cdnTags ); } } catch ( IOException ioe ){ throw new RuntimeException( "couldn't append" , ioe ); } } public String getCDNPrefix(){ return cdnPrefix(); } public String getCDNSuffix(){ return _cdnSuffix; } public String setCDNPrefix( String s ){ _cdnPrefix = s; return cdnPrefix(); } public String setCDNSuffix( String s ){ _cdnSuffix = s; return _cdnSuffix; } String cdnPrefix(){ if ( _ar != null && _ar.isScopeInited() ){ Object foo = _ar.getScope().get( "CDN" ); if ( foo != null ) return foo.toString(); } return _cdnPrefix; } static String getStaticPrefix( HttpRequest request , AppRequest ar ){ if ( NOCDN ) return ""; String host = ar.getHost(); if ( host == null ) return ""; if ( host.indexOf( "." ) < 0 ) return ""; if ( request.getPort() > 0 ) return ""; if ( request.getHeader( "X-SSL" ) != null ) return ""; String prefix= "http://static"; if ( host.indexOf( "local." ) >= 0 ) prefix += "-local"; prefix += ".10gen.com/" + host; return prefix; } static String getStaticSuffix( HttpRequest request , AppRequest ar ){ final AppContext ctxt = ar.getContext(); return "ctxt=" + ctxt.getEnvironmentName() + "" + ctxt.getGitBranch() ; } private final AppContext _context; private AppRequest _ar; private String _cdnPrefix; private String _cdnSuffix; }
false
true
public void fix( String url , Appendable a ){ if ( url == null ) return; if ( url.length() == 0 ) return; // parse out options boolean nocdn = false; boolean forcecdn = false; if ( url.startsWith( "NOCDN" ) ){ nocdn = true; url = url.substring( 5 ); } else if ( url.startsWith( "CDN/" ) ){ forcecdn = true; url = url.substring( 3 ); } boolean doVersioning = true; // weird special cases if ( ! url.startsWith( "/" ) ){ if ( _ar == null || url.startsWith( "http://" ) || url.startsWith( "https://" ) ){ nocdn = true; doVersioning = false; } else { url = _ar.getDirectory() + url; } } if ( url.startsWith( "//" ) ){ // this is the special //www.slashdot.org/foo.jpg syntax nocdn = true; doVersioning = false; } // setup String uri = url; int questionIndex = url.indexOf( "?" ); if ( questionIndex >= 0 ) uri = uri.substring( 0 , questionIndex ); String cdnTags = null; if ( uri.equals( "/~f" ) || uri.equals( "/~~/f" ) ){ cdnTags = ""; // TODO: should i put a version or timestamp here? } else { cdnTags = _cdnSuffix; if ( cdnTags == null ) cdnTags = ""; else if ( cdnTags.length() > 0 ) cdnTags += "&"; if ( doVersioning && _context != null ){ File f = _context.getFileSafe( uri ); if ( f != null && f.exists() ){ cdnTags += "lm=" + f.lastModified(); } } } // print try { if ( forcecdn || ( ! nocdn && cdnTags != null ) ) a.append( cdnPrefix() ); a.append( url ); if ( cdnTags != null && cdnTags.length() > 0 ){ if ( questionIndex < 0 ) a.append( "?" ); else a.append( "&" ); a.append( cdnTags ); } } catch ( IOException ioe ){ throw new RuntimeException( "couldn't append" , ioe ); } }
public void fix( String url , Appendable a ){ if ( url == null ) return; if ( url.length() == 0 ) return; // parse out options boolean nocdn = false; boolean forcecdn = false; if ( url.startsWith( "NOCDN" ) ){ nocdn = true; url = url.substring( 5 ); } else if ( url.startsWith( "CDN/" ) ){ forcecdn = true; url = url.substring( 3 ); } boolean doVersioning = true; // weird special cases if ( ! url.startsWith( "/" ) ){ if ( _ar == null || url.startsWith( "http://" ) || url.startsWith( "https://" ) ){ nocdn = true; doVersioning = false; } else { url = _ar.getDirectory() + url; } } if ( url.startsWith( "//" ) ){ // this is the special //www.slashdot.org/foo.jpg syntax nocdn = true; doVersioning = false; } // setup String uri = url; int questionIndex = url.indexOf( "?" ); if ( questionIndex >= 0 ) uri = uri.substring( 0 , questionIndex ); String cdnTags = null; if ( uri.equals( "/~f" ) || uri.equals( "/~~/f" ) ){ cdnTags = ""; // TODO: should i put a version or timestamp here? } else { cdnTags = _cdnSuffix; if ( cdnTags == null ) cdnTags = ""; else if ( cdnTags.length() > 0 ) cdnTags += "&"; if ( doVersioning && _context != null ){ File f = _context.getFileSafe( uri ); if ( f == null ) cdnTags += "lm=cantfind"; else if ( ! f.exists() ) cdnTags += "lm=doesntexist"; else cdnTags += "lm=" + f.lastModified(); } } // print try { if ( forcecdn || ( ! nocdn && cdnTags != null ) ) a.append( cdnPrefix() ); a.append( url ); if ( cdnTags != null && cdnTags.length() > 0 ){ if ( questionIndex < 0 ) a.append( "?" ); else a.append( "&" ); a.append( cdnTags ); } } catch ( IOException ioe ){ throw new RuntimeException( "couldn't append" , ioe ); } }
diff --git a/ajax-components/src/access-policy-editor/java/org/wyona/security/gwt/accesspolicyeditor/client/AsynchronousPolicyGetter.java b/ajax-components/src/access-policy-editor/java/org/wyona/security/gwt/accesspolicyeditor/client/AsynchronousPolicyGetter.java index 538be47..24ac77a 100644 --- a/ajax-components/src/access-policy-editor/java/org/wyona/security/gwt/accesspolicyeditor/client/AsynchronousPolicyGetter.java +++ b/ajax-components/src/access-policy-editor/java/org/wyona/security/gwt/accesspolicyeditor/client/AsynchronousPolicyGetter.java @@ -1,152 +1,152 @@ /* * Copyright 2008 Wyona * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.wyona.security.gwt.accesspolicyeditor.client; import org.wyona.yanel.gwt.client.AsynchronousAgent; import com.google.gwt.http.client.Request; import com.google.gwt.http.client.Response; import com.google.gwt.xml.client.Element; import com.google.gwt.xml.client.NodeList; import com.google.gwt.xml.client.XMLParser; import com.google.gwt.user.client.Window; import java.util.Vector; /** * */ public class AsynchronousPolicyGetter extends AsynchronousAgent { boolean useInheritedPolicies = true; Vector users = new Vector(); Vector groups = new Vector(); /** * */ public AsynchronousPolicyGetter(String url) { super(url); } /** * See src/gallery/src/java/org/wyona/yanel/gwt/client/ui/gallery/AsynchronousGalleryBuilder.java * Also see src/access-policy-editor/java/org/wyona/security/gwt/accesspolicyeditor/public/sample-policy.xml */ public void onResponseReceived(final Request request, final Response response) { Element rootElement = XMLParser.parse(response.getText()).getDocumentElement(); //Window.alert("Root element: " + rootElement.getTagName()); // Get use-inherited-policies attribute String useInheritedPoliciesString = rootElement.getAttribute("use-inherited-policies"); if (useInheritedPoliciesString == null) { useInheritedPolicies = true; } else { if (useInheritedPoliciesString.equals("false")) { useInheritedPolicies = false; } else { useInheritedPolicies = true; } } //Window.alert("use-inherited-policies: " + useInheritedPoliciesString); // TODO: Parse rights and use labels for formatting, e.g. "u: (Read,Write) benjamin", "u: (Read,-) susi" Element worldElement = getFirstChildElement(rootElement, "world"); if (worldElement != null) { // TODO: ... //identities.add("WORLD (Read,Write)"); //Window.alert("World: " + (String) identities.elementAt(identities.size() - 1)); } NodeList userElements = rootElement.getElementsByTagName("user"); for (int i = 0; i < userElements.getLength(); i++) { Element userE = (Element) userElements.item(i); NodeList rightElements = userE.getElementsByTagName("right"); Right[] rights = new Right[rightElements.getLength()]; for (int k = 0; k < rights.length; k++) { Element rightE = (Element) rightElements.item(k); // TODO: Do not hardcode permission rights[k] = new Right(rightE.getAttribute("id"), true); - //Window.alert("User Right: " + rights[k]); + //Window.alert("User Right: " + rights[k].getId()); } - users.add(new User(((Element) userElements.item(i)).getAttribute("id"), rights)); + users.add(new User(userE.getAttribute("id"), rights)); //Window.alert("User: " + ((User) users.elementAt(users.size() - 1)).getId()); } NodeList groupElements = rootElement.getElementsByTagName("group"); for (int i = 0; i < groupElements.getLength(); i++) { Element groupE = (Element) groupElements.item(i); NodeList rightElements = groupE.getElementsByTagName("right"); Right[] rights = new Right[rightElements.getLength()]; for (int k = 0; k < rights.length; k++) { Element rightE = (Element) rightElements.item(k); // TODO: Do not hardcode permission rights[k] = new Right(rightE.getAttribute("id"), true); - //Window.alert("Group Right: " + rights[k]); + //Window.alert("Group Right: " + rights[k].getId()); } groups.add(new Group(groupE.getAttribute("id"), rights)); //Window.alert("Group: " + ((Group) groups.elementAt(groups.size() - 1)).getId()); } //Window.alert("Policy response processed!"); } /** * Get users from access policy */ public User[] getUsers() { User[] ids = new User[users.size()]; for (int i = 0; i < ids.length; i++) { ids[i] = (User)users.elementAt(i); } return ids; } /** * Get groups from access policy */ public Group[] getGroups() { Group[] ids = new Group[groups.size()]; for (int i = 0; i < ids.length; i++) { ids[i] = (Group)groups.elementAt(i); } return ids; } /** * Get flag use-inherited-policies */ public boolean getUseInheritedPolicies() { return useInheritedPolicies; } /** * */ private Element getFirstChildElement(Element parent, String name) { NodeList nl = parent.getElementsByTagName(name); if (nl.getLength() > 0) { return (Element) nl.item(0); } else { return null; } } }
false
true
public void onResponseReceived(final Request request, final Response response) { Element rootElement = XMLParser.parse(response.getText()).getDocumentElement(); //Window.alert("Root element: " + rootElement.getTagName()); // Get use-inherited-policies attribute String useInheritedPoliciesString = rootElement.getAttribute("use-inherited-policies"); if (useInheritedPoliciesString == null) { useInheritedPolicies = true; } else { if (useInheritedPoliciesString.equals("false")) { useInheritedPolicies = false; } else { useInheritedPolicies = true; } } //Window.alert("use-inherited-policies: " + useInheritedPoliciesString); // TODO: Parse rights and use labels for formatting, e.g. "u: (Read,Write) benjamin", "u: (Read,-) susi" Element worldElement = getFirstChildElement(rootElement, "world"); if (worldElement != null) { // TODO: ... //identities.add("WORLD (Read,Write)"); //Window.alert("World: " + (String) identities.elementAt(identities.size() - 1)); } NodeList userElements = rootElement.getElementsByTagName("user"); for (int i = 0; i < userElements.getLength(); i++) { Element userE = (Element) userElements.item(i); NodeList rightElements = userE.getElementsByTagName("right"); Right[] rights = new Right[rightElements.getLength()]; for (int k = 0; k < rights.length; k++) { Element rightE = (Element) rightElements.item(k); // TODO: Do not hardcode permission rights[k] = new Right(rightE.getAttribute("id"), true); //Window.alert("User Right: " + rights[k]); } users.add(new User(((Element) userElements.item(i)).getAttribute("id"), rights)); //Window.alert("User: " + ((User) users.elementAt(users.size() - 1)).getId()); } NodeList groupElements = rootElement.getElementsByTagName("group"); for (int i = 0; i < groupElements.getLength(); i++) { Element groupE = (Element) groupElements.item(i); NodeList rightElements = groupE.getElementsByTagName("right"); Right[] rights = new Right[rightElements.getLength()]; for (int k = 0; k < rights.length; k++) { Element rightE = (Element) rightElements.item(k); // TODO: Do not hardcode permission rights[k] = new Right(rightE.getAttribute("id"), true); //Window.alert("Group Right: " + rights[k]); } groups.add(new Group(groupE.getAttribute("id"), rights)); //Window.alert("Group: " + ((Group) groups.elementAt(groups.size() - 1)).getId()); } //Window.alert("Policy response processed!"); }
public void onResponseReceived(final Request request, final Response response) { Element rootElement = XMLParser.parse(response.getText()).getDocumentElement(); //Window.alert("Root element: " + rootElement.getTagName()); // Get use-inherited-policies attribute String useInheritedPoliciesString = rootElement.getAttribute("use-inherited-policies"); if (useInheritedPoliciesString == null) { useInheritedPolicies = true; } else { if (useInheritedPoliciesString.equals("false")) { useInheritedPolicies = false; } else { useInheritedPolicies = true; } } //Window.alert("use-inherited-policies: " + useInheritedPoliciesString); // TODO: Parse rights and use labels for formatting, e.g. "u: (Read,Write) benjamin", "u: (Read,-) susi" Element worldElement = getFirstChildElement(rootElement, "world"); if (worldElement != null) { // TODO: ... //identities.add("WORLD (Read,Write)"); //Window.alert("World: " + (String) identities.elementAt(identities.size() - 1)); } NodeList userElements = rootElement.getElementsByTagName("user"); for (int i = 0; i < userElements.getLength(); i++) { Element userE = (Element) userElements.item(i); NodeList rightElements = userE.getElementsByTagName("right"); Right[] rights = new Right[rightElements.getLength()]; for (int k = 0; k < rights.length; k++) { Element rightE = (Element) rightElements.item(k); // TODO: Do not hardcode permission rights[k] = new Right(rightE.getAttribute("id"), true); //Window.alert("User Right: " + rights[k].getId()); } users.add(new User(userE.getAttribute("id"), rights)); //Window.alert("User: " + ((User) users.elementAt(users.size() - 1)).getId()); } NodeList groupElements = rootElement.getElementsByTagName("group"); for (int i = 0; i < groupElements.getLength(); i++) { Element groupE = (Element) groupElements.item(i); NodeList rightElements = groupE.getElementsByTagName("right"); Right[] rights = new Right[rightElements.getLength()]; for (int k = 0; k < rights.length; k++) { Element rightE = (Element) rightElements.item(k); // TODO: Do not hardcode permission rights[k] = new Right(rightE.getAttribute("id"), true); //Window.alert("Group Right: " + rights[k].getId()); } groups.add(new Group(groupE.getAttribute("id"), rights)); //Window.alert("Group: " + ((Group) groups.elementAt(groups.size() - 1)).getId()); } //Window.alert("Policy response processed!"); }
diff --git a/src/org/vamp/util/blur/gaussian/GaussianBlurRenderFrameForkJoin.java b/src/org/vamp/util/blur/gaussian/GaussianBlurRenderFrameForkJoin.java index f226dc9..1510717 100644 --- a/src/org/vamp/util/blur/gaussian/GaussianBlurRenderFrameForkJoin.java +++ b/src/org/vamp/util/blur/gaussian/GaussianBlurRenderFrameForkJoin.java @@ -1,78 +1,78 @@ package org.vamp.util.blur.gaussian; import org.vamp.util.blur.BlurRenderFrameForkJoin; public abstract class GaussianBlurRenderFrameForkJoin extends BlurRenderFrameForkJoin { // =========================================================== // Constants // =========================================================== private static final long serialVersionUID = 4633412215367996025L; // =========================================================== // Fields // =========================================================== protected float[] mKernel; // =========================================================== // Constructors // =========================================================== public GaussianBlurRenderFrameForkJoin(final int[] pInputRenderFrameBuffer, final int pWidth, final int pHeight, final int[] pOutputRenderFrameBuffer, final int pBlurRadius) { this(pInputRenderFrameBuffer, pWidth, pHeight, 0, 0, pWidth, pHeight, pOutputRenderFrameBuffer, pBlurRadius); } public GaussianBlurRenderFrameForkJoin(final int[] pInputRenderFrameBuffer, final int pWidth, final int pHeight, final int pWindowLeft, final int pWindowTop, final int pWindowRight, final int pWindowBottom, final int[] pOutputRenderFrameBuffer, final int pBlurRadius) { this(pInputRenderFrameBuffer, pWidth, pHeight, pWindowLeft, pWindowTop, pWindowRight, pWindowBottom, pOutputRenderFrameBuffer, pBlurRadius, GaussianBlurRenderFrameForkJoin.makeKernel(pBlurRadius)); } public GaussianBlurRenderFrameForkJoin(final int[] pInputRenderFrameBuffer, final int pWidth, final int pHeight, final int pWindowLeft, final int pWindowTop, final int pWindowRight, final int pWindowBottom, final int[] pOutputRenderFrameBuffer, final int pBlurRadius, final float[] pKernel) { super(pInputRenderFrameBuffer, pWidth, pHeight, pWindowLeft, pWindowTop, pWindowRight, pWindowBottom, pOutputRenderFrameBuffer, pBlurRadius); this.mKernel = pKernel; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public static float[] makeKernel(final int pRadius) { - final float sigma = pRadius / 3; + final float sigma = pRadius / 3f; final float sigmaSquared2 = 2 * sigma * sigma; final float sqrtSigmaPi2 = (float) Math.sqrt(2 * Math.PI * sigma); final float radiusSquared = pRadius * pRadius; final int rowCount = (pRadius * 2) + 1; final float[] kernel = new float[rowCount]; float total = 0; for (int index = 0, row = -pRadius; row <= pRadius; index++, row++) { final float distance = row * row; if (distance > radiusSquared) { kernel[index] = 0; } else { kernel[index] = (float) Math.exp(-(distance) / sigmaSquared2) / sqrtSigmaPi2; } total += kernel[index]; } for (int i = 0; i < rowCount; i++) { kernel[i] /= total; } return kernel; } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
true
true
public static float[] makeKernel(final int pRadius) { final float sigma = pRadius / 3; final float sigmaSquared2 = 2 * sigma * sigma; final float sqrtSigmaPi2 = (float) Math.sqrt(2 * Math.PI * sigma); final float radiusSquared = pRadius * pRadius; final int rowCount = (pRadius * 2) + 1; final float[] kernel = new float[rowCount]; float total = 0; for (int index = 0, row = -pRadius; row <= pRadius; index++, row++) { final float distance = row * row; if (distance > radiusSquared) { kernel[index] = 0; } else { kernel[index] = (float) Math.exp(-(distance) / sigmaSquared2) / sqrtSigmaPi2; } total += kernel[index]; } for (int i = 0; i < rowCount; i++) { kernel[i] /= total; } return kernel; }
public static float[] makeKernel(final int pRadius) { final float sigma = pRadius / 3f; final float sigmaSquared2 = 2 * sigma * sigma; final float sqrtSigmaPi2 = (float) Math.sqrt(2 * Math.PI * sigma); final float radiusSquared = pRadius * pRadius; final int rowCount = (pRadius * 2) + 1; final float[] kernel = new float[rowCount]; float total = 0; for (int index = 0, row = -pRadius; row <= pRadius; index++, row++) { final float distance = row * row; if (distance > radiusSquared) { kernel[index] = 0; } else { kernel[index] = (float) Math.exp(-(distance) / sigmaSquared2) / sqrtSigmaPi2; } total += kernel[index]; } for (int i = 0; i < rowCount; i++) { kernel[i] /= total; } return kernel; }
diff --git a/src/com/dmdirc/logger/Logger.java b/src/com/dmdirc/logger/Logger.java index 4e0e1a2e8..be4ffe067 100644 --- a/src/com/dmdirc/logger/Logger.java +++ b/src/com/dmdirc/logger/Logger.java @@ -1,197 +1,200 @@ /* * Copyright (c) 2006-2007 Chris Smith, Shane Mc Cormack, Gregory Holmes * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.dmdirc.logger; import com.dmdirc.Config; import com.dmdirc.ui.dialogs.error.FatalErrorDialog; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Date; /** * Logger class for the application. */ public final class Logger { /** ProgramError folder. */ private static File errorDir; /** Prevent instantiation of a new instance of Logger. */ private Logger() { //Ignore } /** * Called when a user correctable error occurs. * * @param level Severity of the error * @param message Brief error description */ public static void userError(final ErrorLevel level, final String message) { error(level, message, null, false); } /** * Called when a non user correctable error occurs, the error will be * logged and optionally sent to the developers. * * @param level Severity of the error * @param message Brief error description * @param exception Cause of error */ public static void appError(final ErrorLevel level, final String message, final Throwable exception) { error(level, message, exception, true); } /** * Handles an error in the program. * * @param level Severity of the error * @param message Brief error description * @param error Cause of error * @param sendable Whether the error is sendable */ private static void error(final ErrorLevel level, final String message, final Throwable exception, final boolean sendable) { final ProgramError error = createError(level, message, exception); if (!sendable) { error.setStatus(ErrorStatus.NOT_APPLICABLE); } if (sendable && Config.getOptionBool("general", "submitErrors")) { ErrorManager.getErrorManager().sendError(error); } if (level == ErrorLevel.FATAL) { if (!Config.getOptionBool("general", "submitErrors")) { error.setStatus(ErrorStatus.FINISHED); } new FatalErrorDialog(error); return; } ErrorManager.getErrorManager().addError(error); } /** * Creates a new ProgramError from the supplied information, and writes * the error to a file. * * @param level Error level * @param message Error message * @param exception Error cause * * @return ProgramError encapsulating the supplied information */ private static ProgramError createError(final ErrorLevel level, final String message, final Throwable exception) { final String[] trace; final StackTraceElement[] traceElements; if (exception == null) { trace = new String[0]; } else { traceElements = exception.getStackTrace(); trace = new String[traceElements.length + 1]; trace[0] = exception.toString(); for (int i = 1; i < traceElements.length; i++) { trace[i] = traceElements[i].toString(); } } final ProgramError error = new ProgramError(level, message, trace, new Date(System.currentTimeMillis())); writeError(error); return error; } /** * Writes the specified error to a file. * * @param error ProgramError to write to a file. */ private static void writeError(final ProgramError error) { final PrintWriter out = new PrintWriter(createNewErrorFile(error), true); out.println("Date:" + error.getDate()); out.println("Level: " + error.getLevel()); out.println("Description: " + error.getMessage()); out.println("Details:"); final String[] trace = error.getTrace(); for (String traceLine : trace) { out.println('\t' + traceLine); } out.close(); } /** * Creates a new file for an error and returns the output stream. * * @param error Error to create file for * * @return BufferedOutputStream to write to the error file */ @SuppressWarnings("PMD.SystemPrintln") private static synchronized OutputStream createNewErrorFile(final ProgramError error) { if (errorDir == null) { errorDir = new File(Config.getConfigDir() + "errors"); if (!errorDir.exists()) { errorDir.mkdirs(); } } - final File errorFile = new File(errorDir, "" + error.getLevel() + "-" + error.getDate()); + final File errorFile = new File(errorDir, "" + error.getLevel() + "-" + + error.getDate().getTime() + ".log"); if (errorFile.exists()) { boolean rename = false; while (!rename) { rename = errorFile.renameTo(new File(errorFile.getAbsolutePath() + '_')); } } try { errorFile.createNewFile(); } catch (IOException ex) { - System.err.println("Error creating new file: " + ex); + System.err.println("Error creating new file: "); + ex.printStackTrace(System.err); return new NullOutputStream(); } try { return new FileOutputStream(errorFile); } catch (FileNotFoundException ex) { - System.err.println("Error creating new stream: " + ex); + System.err.println("Error creating new stream: "); + ex.printStackTrace(System.err); return new NullOutputStream(); } } }
false
true
private static synchronized OutputStream createNewErrorFile(final ProgramError error) { if (errorDir == null) { errorDir = new File(Config.getConfigDir() + "errors"); if (!errorDir.exists()) { errorDir.mkdirs(); } } final File errorFile = new File(errorDir, "" + error.getLevel() + "-" + error.getDate()); if (errorFile.exists()) { boolean rename = false; while (!rename) { rename = errorFile.renameTo(new File(errorFile.getAbsolutePath() + '_')); } } try { errorFile.createNewFile(); } catch (IOException ex) { System.err.println("Error creating new file: " + ex); return new NullOutputStream(); } try { return new FileOutputStream(errorFile); } catch (FileNotFoundException ex) { System.err.println("Error creating new stream: " + ex); return new NullOutputStream(); } }
private static synchronized OutputStream createNewErrorFile(final ProgramError error) { if (errorDir == null) { errorDir = new File(Config.getConfigDir() + "errors"); if (!errorDir.exists()) { errorDir.mkdirs(); } } final File errorFile = new File(errorDir, "" + error.getLevel() + "-" + error.getDate().getTime() + ".log"); if (errorFile.exists()) { boolean rename = false; while (!rename) { rename = errorFile.renameTo(new File(errorFile.getAbsolutePath() + '_')); } } try { errorFile.createNewFile(); } catch (IOException ex) { System.err.println("Error creating new file: "); ex.printStackTrace(System.err); return new NullOutputStream(); } try { return new FileOutputStream(errorFile); } catch (FileNotFoundException ex) { System.err.println("Error creating new stream: "); ex.printStackTrace(System.err); return new NullOutputStream(); } }
diff --git a/activemq-core/src/test/java/org/apache/activemq/broker/util/PluginBrokerTest.java b/activemq-core/src/test/java/org/apache/activemq/broker/util/PluginBrokerTest.java index 940b57652..13c03c3e5 100644 --- a/activemq-core/src/test/java/org/apache/activemq/broker/util/PluginBrokerTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/broker/util/PluginBrokerTest.java @@ -1,88 +1,88 @@ /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq.broker.util; import java.net.URI; import javax.jms.JMSException; import javax.jms.Message; import org.apache.activemq.broker.BrokerFactory; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.command.ActiveMQMessage; import org.apache.activemq.test.JmsTopicSendReceiveTest; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * * @version $Revision: 564271 $ */ public class PluginBrokerTest extends JmsTopicSendReceiveTest { private static final Log LOG = LogFactory.getLog(PluginBrokerTest.class); private BrokerService broker; protected void setUp() throws Exception { broker = createBroker(); super.setUp(); } protected void tearDown() throws Exception { super.tearDown(); if (broker != null) { broker.stop(); } } protected BrokerService createBroker() throws Exception { return createBroker("org/apache/activemq/util/plugin-broker.xml"); } protected BrokerService createBroker(String uri) throws Exception { LOG.info("Loading broker configuration from the classpath with URI: " + uri); return BrokerFactory.createBroker(new URI("xbean:" + uri)); } protected void assertMessageValid(int index, Message message) throws JMSException { // check if broker path has been set assertEquals("localhost", message.getStringProperty("BrokerPath")); ActiveMQMessage amqMsg = (ActiveMQMessage)message; if (index == 7) { // check custom expiration - assertEquals(2000, amqMsg.getExpiration() - amqMsg.getTimestamp()); + assertTrue("expiration is in range, depends on two distinct calls to System.currentTimeMillis", 1500 < amqMsg.getExpiration() - amqMsg.getTimestamp()); } else if (index == 9) { // check ceiling - assertEquals(60000, amqMsg.getExpiration() - amqMsg.getTimestamp()); + assertTrue("expiration ceeling is in range, depends on two distinct calls to System.currentTimeMillis", 59500 < amqMsg.getExpiration() - amqMsg.getTimestamp()); } else { // check default expiration assertEquals(1000, amqMsg.getExpiration() - amqMsg.getTimestamp()); } super.assertMessageValid(index, message); } protected void sendMessage(int index, Message message) throws Exception { if (index == 7) { producer.send(producerDestination, message, Message.DEFAULT_DELIVERY_MODE, Message.DEFAULT_PRIORITY, 2000); } else if (index == 9) { producer.send(producerDestination, message, Message.DEFAULT_DELIVERY_MODE, Message.DEFAULT_PRIORITY, 200000); } else { super.sendMessage(index, message); } } }
false
true
protected void assertMessageValid(int index, Message message) throws JMSException { // check if broker path has been set assertEquals("localhost", message.getStringProperty("BrokerPath")); ActiveMQMessage amqMsg = (ActiveMQMessage)message; if (index == 7) { // check custom expiration assertEquals(2000, amqMsg.getExpiration() - amqMsg.getTimestamp()); } else if (index == 9) { // check ceiling assertEquals(60000, amqMsg.getExpiration() - amqMsg.getTimestamp()); } else { // check default expiration assertEquals(1000, amqMsg.getExpiration() - amqMsg.getTimestamp()); } super.assertMessageValid(index, message); }
protected void assertMessageValid(int index, Message message) throws JMSException { // check if broker path has been set assertEquals("localhost", message.getStringProperty("BrokerPath")); ActiveMQMessage amqMsg = (ActiveMQMessage)message; if (index == 7) { // check custom expiration assertTrue("expiration is in range, depends on two distinct calls to System.currentTimeMillis", 1500 < amqMsg.getExpiration() - amqMsg.getTimestamp()); } else if (index == 9) { // check ceiling assertTrue("expiration ceeling is in range, depends on two distinct calls to System.currentTimeMillis", 59500 < amqMsg.getExpiration() - amqMsg.getTimestamp()); } else { // check default expiration assertEquals(1000, amqMsg.getExpiration() - amqMsg.getTimestamp()); } super.assertMessageValid(index, message); }
diff --git a/gui/src/main/java/org/jboss/as/console/client/shared/viewframework/builder/SimpleLayout.java b/gui/src/main/java/org/jboss/as/console/client/shared/viewframework/builder/SimpleLayout.java index 417ad074..e522211e 100644 --- a/gui/src/main/java/org/jboss/as/console/client/shared/viewframework/builder/SimpleLayout.java +++ b/gui/src/main/java/org/jboss/as/console/client/shared/viewframework/builder/SimpleLayout.java @@ -1,135 +1,135 @@ package org.jboss.as.console.client.shared.viewframework.builder; import com.google.gwt.dom.client.Style; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.LayoutPanel; import com.google.gwt.user.client.ui.ScrollPanel; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; import org.jboss.ballroom.client.widgets.ContentHeaderLabel; import org.jboss.ballroom.client.widgets.tabs.FakeTabPanel; import java.util.ArrayList; import java.util.List; /** * Simple row based layout for RHS content sections * * @author Heiko Braun * @date 11/28/11 */ public class SimpleLayout { private LayoutPanel layout = null; private String title = "TITLE"; private String headline = "HEADLINE"; private String description = "DESCRIPTION"; private Widget toolStrip = null; private List<NamedWidget> details = new ArrayList<NamedWidget>(); private boolean isPlain = false; private Widget headlineWidget; public SimpleLayout setPlain(boolean isPlain) { this.isPlain = isPlain; return this; } public SimpleLayout setTitle(String title) { this.title = title; return this; } public SimpleLayout setTopLevelTools(Widget toolstrip) { this.toolStrip = toolstrip; return this; } public SimpleLayout addContent(String title, Widget detail) { details.add(new NamedWidget(title, detail)); return this; } public SimpleLayout setDescription(String description) { this.description = description; return this; } public SimpleLayout setHeadline(String headline) { this.headline = headline; return this; } public Widget build() { layout = new LayoutPanel(); layout.setStyleName("fill-layout"); FakeTabPanel titleBar = null; if(!isPlain) { titleBar = new FakeTabPanel(title); layout.add(titleBar); } if(this.toolStrip !=null) { layout.add(toolStrip); } VerticalPanel panel = new VerticalPanel(); panel.setStyleName("rhs-content-panel"); ScrollPanel scroll = new ScrollPanel(panel); layout.add(scroll); // titlebar offset, if exists - int offset = isPlain ? 0 : 28; + int offset = isPlain ? 0 : 40; if(toolStrip!=null) { if(!isPlain) layout.setWidgetTopHeight(titleBar, 0, Style.Unit.PX, 40, Style.Unit.PX); layout.setWidgetTopHeight(toolStrip, offset, Style.Unit.PX, 30, Style.Unit.PX); layout.setWidgetTopHeight(scroll, offset+30, Style.Unit.PX, 100, Style.Unit.PCT); } else { if(!isPlain) layout.setWidgetTopHeight(titleBar, 0, Style.Unit.PX, 40, Style.Unit.PX); layout.setWidgetTopHeight(scroll, offset, Style.Unit.PX, 100, Style.Unit.PCT); } if(null==headlineWidget) { panel.add(new ContentHeaderLabel(headline)); } else { panel.add(headlineWidget); } panel.add(new HTML(description)); for(NamedWidget item : details) { panel.add(item.widget); item.widget.getElement().addClassName("fill-layout-width"); } return layout; } public SimpleLayout setHeadlineWidget(Widget header) { this.headlineWidget = header; return this; } }
true
true
public Widget build() { layout = new LayoutPanel(); layout.setStyleName("fill-layout"); FakeTabPanel titleBar = null; if(!isPlain) { titleBar = new FakeTabPanel(title); layout.add(titleBar); } if(this.toolStrip !=null) { layout.add(toolStrip); } VerticalPanel panel = new VerticalPanel(); panel.setStyleName("rhs-content-panel"); ScrollPanel scroll = new ScrollPanel(panel); layout.add(scroll); // titlebar offset, if exists int offset = isPlain ? 0 : 28; if(toolStrip!=null) { if(!isPlain) layout.setWidgetTopHeight(titleBar, 0, Style.Unit.PX, 40, Style.Unit.PX); layout.setWidgetTopHeight(toolStrip, offset, Style.Unit.PX, 30, Style.Unit.PX); layout.setWidgetTopHeight(scroll, offset+30, Style.Unit.PX, 100, Style.Unit.PCT); } else { if(!isPlain) layout.setWidgetTopHeight(titleBar, 0, Style.Unit.PX, 40, Style.Unit.PX); layout.setWidgetTopHeight(scroll, offset, Style.Unit.PX, 100, Style.Unit.PCT); } if(null==headlineWidget) { panel.add(new ContentHeaderLabel(headline)); } else { panel.add(headlineWidget); } panel.add(new HTML(description)); for(NamedWidget item : details) { panel.add(item.widget); item.widget.getElement().addClassName("fill-layout-width"); } return layout; }
public Widget build() { layout = new LayoutPanel(); layout.setStyleName("fill-layout"); FakeTabPanel titleBar = null; if(!isPlain) { titleBar = new FakeTabPanel(title); layout.add(titleBar); } if(this.toolStrip !=null) { layout.add(toolStrip); } VerticalPanel panel = new VerticalPanel(); panel.setStyleName("rhs-content-panel"); ScrollPanel scroll = new ScrollPanel(panel); layout.add(scroll); // titlebar offset, if exists int offset = isPlain ? 0 : 40; if(toolStrip!=null) { if(!isPlain) layout.setWidgetTopHeight(titleBar, 0, Style.Unit.PX, 40, Style.Unit.PX); layout.setWidgetTopHeight(toolStrip, offset, Style.Unit.PX, 30, Style.Unit.PX); layout.setWidgetTopHeight(scroll, offset+30, Style.Unit.PX, 100, Style.Unit.PCT); } else { if(!isPlain) layout.setWidgetTopHeight(titleBar, 0, Style.Unit.PX, 40, Style.Unit.PX); layout.setWidgetTopHeight(scroll, offset, Style.Unit.PX, 100, Style.Unit.PCT); } if(null==headlineWidget) { panel.add(new ContentHeaderLabel(headline)); } else { panel.add(headlineWidget); } panel.add(new HTML(description)); for(NamedWidget item : details) { panel.add(item.widget); item.widget.getElement().addClassName("fill-layout-width"); } return layout; }
diff --git a/src/main/java/net/pms/network/RequestV2.java b/src/main/java/net/pms/network/RequestV2.java index 453a64cd2..a88ad195c 100644 --- a/src/main/java/net/pms/network/RequestV2.java +++ b/src/main/java/net/pms/network/RequestV2.java @@ -1,964 +1,964 @@ /* * PS3 Media Server, for streaming any medias to your PS3. * Copyright (C) 2008 A.Brochard * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; version 2 * of the License only. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package net.pms.network; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.Socket; import java.net.URL; import java.text.SimpleDateFormat; import java.util.*; import net.pms.PMS; import net.pms.configuration.PmsConfiguration; import net.pms.configuration.RendererConfiguration; import net.pms.dlna.*; import net.pms.external.StartStopListenerDelegate; import net.pms.util.StringUtil; import static net.pms.util.StringUtil.convertStringToTime; import static org.apache.commons.lang3.StringUtils.isNotBlank; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelFutureListener; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.handler.codec.http.HttpHeaders; import org.jboss.netty.handler.codec.http.HttpResponse; import org.jboss.netty.handler.stream.ChunkedStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class handles all forms of incoming HTTP requests by constructing a proper HTTP response. */ public class RequestV2 extends HTTPResource { private static final Logger LOGGER = LoggerFactory.getLogger(RequestV2.class); private final static String CRLF = "\r\n"; private final SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss", Locale.US); private static int BUFFER_SIZE = 8 * 1024; private final String method; private static final PmsConfiguration configuration = PMS.getConfiguration(); /** * A {@link String} that contains the argument with which this {@link RequestV2} was * created. It contains a command, a unique resource id and a resource name, all * separated by slashes. For example: "get/0$0$2$17/big_buck_bunny_1080p_h264.mov" or * "get/0$0$2$13/thumbnail0000Sintel.2010.1080p.mkv" */ private String argument; private String soapaction; private String content; private String objectID; private int startingIndex; private int requestCount; private String browseFlag; /** * When sending an input stream, the lowRange indicates which byte to start from. */ private long lowRange; private InputStream inputStream; private RendererConfiguration mediaRenderer; private String transferMode; private String contentFeatures; private final Range.Time range = new Range.Time(); /** * When sending an input stream, the highRange indicates which byte to stop at. */ private long highRange; private boolean http10; public RendererConfiguration getMediaRenderer() { return mediaRenderer; } public void setMediaRenderer(RendererConfiguration mediaRenderer) { this.mediaRenderer = mediaRenderer; } public InputStream getInputStream() { return inputStream; } /** * When sending an input stream, the lowRange indicates which byte to start from. * @return The byte to start from */ public long getLowRange() { return lowRange; } /** * Set the byte from which to start when sending an input stream. This value will * be used to send a CONTENT_RANGE header with the response. * @param lowRange The byte to start from. */ public void setLowRange(long lowRange) { this.lowRange = lowRange; } public String getTransferMode() { return transferMode; } public void setTransferMode(String transferMode) { this.transferMode = transferMode; } public String getContentFeatures() { return contentFeatures; } public void setContentFeatures(String contentFeatures) { this.contentFeatures = contentFeatures; } public void setTimeRangeStart(Double timeseek) { this.range.setStart(timeseek); } public void setTimeRangeStartString(String str) { setTimeRangeStart(convertStringToTime(str)); } public void setTimeRangeEnd(Double rangeEnd) { this.range.setEnd(rangeEnd); } public void setTimeRangeEndString(String str) { setTimeRangeEnd(convertStringToTime(str)); } /** * When sending an input stream, the highRange indicates which byte to stop at. * @return The byte to stop at. */ public long getHighRange() { return highRange; } /** * Set the byte at which to stop when sending an input stream. This value will * be used to send a CONTENT_RANGE header with the response. * @param highRange The byte to stop at. */ public void setHighRange(long highRange) { this.highRange = highRange; } public boolean isHttp10() { return http10; } public void setHttp10(boolean http10) { this.http10 = http10; } /** * This class will construct and transmit a proper HTTP response to a given HTTP request. * Rewritten version of the {@link Request} class. * @param method The {@link String} that defines the HTTP method to be used. * @param argument The {@link String} containing instructions for PMS. It contains a command, * a unique resource id and a resource name, all separated by slashes. */ public RequestV2(String method, String argument) { this.method = method; this.argument = argument; } public String getSoapaction() { return soapaction; } public void setSoapaction(String soapaction) { this.soapaction = soapaction; } public String getTextContent() { return content; } public void setTextContent(String content) { this.content = content; } /** * Retrieves the HTTP method with which this {@link RequestV2} was created. * @return The (@link String} containing the HTTP method. */ public String getMethod() { return method; } /** * Retrieves the argument with which this {@link RequestV2} was created. It contains * a command, a unique resource id and a resource name, all separated by slashes. For * example: "get/0$0$2$17/big_buck_bunny_1080p_h264.mov" or "get/0$0$2$13/thumbnail0000Sintel.2010.1080p.mkv" * @return The {@link String} containing the argument. */ public String getArgument() { return argument; } /** * Construct a proper HTTP response to a received request. After the response has been * created, it is sent and the resulting {@link ChannelFuture} object is returned. * See <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html">RFC-2616</a> * for HTTP header field definitions. * @param output The {@link HttpResponse} object that will be used to construct the response. * @param e The {@link MessageEvent} object used to communicate with the client that sent * the request. * @param close Set to true to close the channel after sending the response. By default the * channel is not closed after sending. * @param startStopListenerDelegate The {@link StartStopListenerDelegate} object that is used * to notify plugins that the {@link DLNAResource} is about to start playing. * @return The {@link ChannelFuture} object via which the response was sent. * @throws IOException */ public ChannelFuture answer( HttpResponse output, MessageEvent e, final boolean close, final StartStopListenerDelegate startStopListenerDelegate ) throws IOException { ChannelFuture future = null; long CLoverride = -2; // 0 and above are valid Content-Length values, -1 means omit StringBuilder response = new StringBuilder(); DLNAResource dlna = null; boolean xbox = mediaRenderer.isXBOX(); // Samsung 2012 TVs have a problematic preceding slash that needs to be removed. if (argument.startsWith("/")) { LOGGER.trace("Stripping preceding slash from: " + argument); argument = argument.substring(1); } if ((method.equals("GET") || method.equals("HEAD")) && argument.startsWith("console/")) { // Request to output a page to the HTML console. output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/html"); response.append(HTMLConsole.servePage(argument.substring(8))); } else if ((method.equals("GET") || method.equals("HEAD")) && argument.startsWith("get/")) { // Request to retrieve a file /** * Skip the leading "get/" and extract the resource ID from the first path element * e.g. "get/0$1$5$3$4/Foo.mp4" -> "0$1$5$3$4" * * ExSport: I spotted on Android it is asking for "/get/0$2$4$2$1$3" which generates exception with response: * "Http: Response, HTTP/1.1, Status: Internal server error, URL: /get/0$2$4$2$1$3" * This should fix it */ String id = argument.substring(4); if (argument.substring(4).contains("/")) { id = argument.substring(4, argument.lastIndexOf("/")); } // Some clients escape the separators in their request: unescape them. id = id.replace("%24", "$"); // Retrieve the DLNAresource itself. List<DLNAResource> files = PMS.get().getRootFolder(mediaRenderer).getDLNAResources(id, false, 0, 0, mediaRenderer); if (transferMode != null) { output.setHeader("TransferMode.DLNA.ORG", transferMode); } if (files.size() == 1) { // DLNAresource was found. dlna = files.get(0); String fileName = argument.substring(argument.lastIndexOf("/") + 1); if (fileName.startsWith("thumbnail0000")) { // This is a request for a thumbnail file. output.setHeader(HttpHeaders.Names.CONTENT_TYPE, dlna.getThumbnailContentType()); output.setHeader(HttpHeaders.Names.ACCEPT_RANGES, "bytes"); output.setHeader(HttpHeaders.Names.EXPIRES, getFUTUREDATE() + " GMT"); output.setHeader(HttpHeaders.Names.CONNECTION, "keep-alive"); if (mediaRenderer.isMediaParserV2()) { dlna.checkThumbnail(); } inputStream = dlna.getThumbnailInputStream(); } else if (fileName.indexOf("subtitle0000") > -1) { // This is a request for a subtitle file output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/plain"); output.setHeader(HttpHeaders.Names.EXPIRES, getFUTUREDATE() + " GMT"); List<DLNAMediaSubtitle> subs = dlna.getMedia().getSubtitleTracksList(); if (subs != null && !subs.isEmpty()) { // TODO: maybe loop subs to get the requested subtitle type instead of using the first one DLNAMediaSubtitle sub = subs.get(0); try { // XXX external file is null if the first subtitle track is embedded: // http://www.ps3mediaserver.org/forum/viewtopic.php?f=3&t=15805&p=75534#p75534 if (sub.isExternal()) { inputStream = new java.io.FileInputStream(sub.getExternalFile()); } } catch (NullPointerException npe) { LOGGER.trace("Could not find external subtitles: " + sub); } } } else { // This is a request for a regular file. // If range has not been initialized yet and the DLNAResource has its // own start and end defined, initialize range with those values before // requesting the input stream. Range.Time splitRange = dlna.getSplitRange(); if (range.getStart() == null && splitRange.getStart() != null) { range.setStart(splitRange.getStart()); } if (range.getEnd() == null && splitRange.getEnd() != null) { range.setEnd(splitRange.getEnd()); } inputStream = dlna.getInputStream(Range.create(lowRange, highRange, range.getStart(), range.getEnd()), mediaRenderer); if (!configuration.isDisableSubtitles()) { // Some renderers (like Samsung devices) allow a custom header for a subtitle URL String subtitleHttpHeader = mediaRenderer.getSubtitleHttpHeader(); if (subtitleHttpHeader != null && !"".equals(subtitleHttpHeader)) { // Device allows a custom subtitle HTTP header; construct it List<DLNAMediaSubtitle> subs = dlna.getMedia().getSubtitleTracksList(); if (subs != null && !subs.isEmpty()) { DLNAMediaSubtitle sub = subs.get(0); String subtitleUrl; String subExtension = sub.getType().getExtension(); if (isNotBlank(subExtension)) { subtitleUrl = "http://" + PMS.get().getServer().getHost() + ':' + PMS.get().getServer().getPort() + "/get/" + id + "/subtitle0000." + subExtension; } else { subtitleUrl = "http://" + PMS.get().getServer().getHost() + ':' + PMS.get().getServer().getPort() + "/get/" + id + "/subtitle0000"; } output.setHeader(subtitleHttpHeader, subtitleUrl); } } } String name = dlna.getDisplayName(mediaRenderer); if (dlna.isNoName()) { name = dlna.getName() + " " + dlna.getDisplayName(mediaRenderer); } if (inputStream == null) { // No inputStream indicates that transcoding / remuxing probably crashed. LOGGER.error("There is no inputstream to return for " + name); } else { // Notify plugins that the DLNAresource is about to start playing startStopListenerDelegate.start(dlna); // Try to determine the content type of the file String rendererMimeType = getRendererMimeType(dlna.mimeType(), mediaRenderer); if (rendererMimeType != null && !"".equals(rendererMimeType)) { output.setHeader(HttpHeaders.Names.CONTENT_TYPE, rendererMimeType); } PMS.get().getFrame().setStatusLine("Serving " + name); // Response generation: // We use -1 for arithmetic convenience but don't send it as a value. // If Content-Length < 0 we omit it, for Content-Range we use '*' to signify unspecified. boolean chunked = mediaRenderer.isChunkedTransfer(); // Determine the total size. Note: when transcoding the length is // not known in advance, so DLNAMediaInfo.TRANS_SIZE will be returned instead. long totalsize = dlna.length(mediaRenderer); if (chunked && totalsize == DLNAMediaInfo.TRANS_SIZE) { // In chunked mode we try to avoid arbitrary values. totalsize = -1; } long remaining = totalsize - lowRange; long requested = highRange - lowRange; if (requested != 0) { // Determine the range (i.e. smaller of known or requested bytes) long bytes = remaining > -1 ? remaining : inputStream.available(); if (requested > 0 && bytes > requested) { bytes = requested + 1; } // Calculate the corresponding highRange (this is usually redundant). highRange = lowRange + bytes - (bytes > 0 ? 1 : 0); LOGGER.trace((chunked ? "Using chunked response. " : "") + "Sending " + bytes + " bytes."); output.setHeader(HttpHeaders.Names.CONTENT_RANGE, "bytes " + lowRange + "-" + (highRange > -1 ? highRange : "*") + "/" + (totalsize > -1 ? totalsize : "*")); // Content-Length refers to the current chunk size here, though in chunked // mode if the request is open-ended and totalsize is unknown we omit it. if (chunked && requested < 0 && totalsize < 0) { CLoverride = -1; } else { CLoverride = bytes; } } else { // Content-Length refers to the total remaining size of the stream here. CLoverride = remaining; } // Calculate the corresponding highRange (this is usually redundant). highRange = lowRange + CLoverride - (CLoverride > 0 ? 1 : 0); if (contentFeatures != null) { output.setHeader("ContentFeatures.DLNA.ORG", dlna.getDlnaContentFeatures()); } output.setHeader(HttpHeaders.Names.ACCEPT_RANGES, "bytes"); output.setHeader(HttpHeaders.Names.CONNECTION, "keep-alive"); } } } } else if ((method.equals("GET") || method.equals("HEAD")) && (argument.toLowerCase().endsWith(".png") || argument.toLowerCase().endsWith(".jpg") || argument.toLowerCase().endsWith(".jpeg"))) { if (argument.toLowerCase().endsWith(".png")) { output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "image/png"); } else { output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "image/jpeg"); } output.setHeader(HttpHeaders.Names.ACCEPT_RANGES, "bytes"); output.setHeader(HttpHeaders.Names.CONNECTION, "keep-alive"); output.setHeader(HttpHeaders.Names.EXPIRES, getFUTUREDATE() + " GMT"); inputStream = getResourceInputStream(argument); } else if ((method.equals("GET") || method.equals("HEAD")) && (argument.equals("description/fetch") || argument.endsWith("1.0.xml"))) { output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/xml; charset=\"utf-8\""); output.setHeader(HttpHeaders.Names.CACHE_CONTROL, "no-cache"); output.setHeader(HttpHeaders.Names.EXPIRES, "0"); output.setHeader(HttpHeaders.Names.ACCEPT_RANGES, "bytes"); output.setHeader(HttpHeaders.Names.CONNECTION, "keep-alive"); inputStream = getResourceInputStream((argument.equals("description/fetch") ? "PMS.xml" : argument)); if (argument.equals("description/fetch")) { byte b[] = new byte[inputStream.available()]; inputStream.read(b); String s = new String(b); s = s.replace("[uuid]", PMS.get().usn()); //.substring(0, PMS.get().usn().length()-2)); String profileName = configuration.getProfileName(); if (PMS.get().getServer().getHost() != null) { s = s.replace("[host]", PMS.get().getServer().getHost()); s = s.replace("[port]", "" + PMS.get().getServer().getPort()); } if (xbox) { LOGGER.debug("DLNA changes for Xbox 360"); s = s.replace("Universal Media Server", "Universal Media Server [" + profileName + "] : Windows Media Connect"); s = s.replace("<modelName>UMS</modelName>", "<modelName>Windows Media Connect</modelName>"); s = s.replace("<serviceList>", "<serviceList>" + CRLF + "<service>" + CRLF + "<serviceType>urn:microsoft.com:service:X_MS_MediaReceiverRegistrar:1</serviceType>" + CRLF + "<serviceId>urn:microsoft.com:serviceId:X_MS_MediaReceiverRegistrar</serviceId>" + CRLF + "<SCPDURL>/upnp/mrr/scpd</SCPDURL>" + CRLF + "<controlURL>/upnp/mrr/control</controlURL>" + CRLF + "</service>" + CRLF); } else { s = s.replace("Universal Media Server", "Universal Media Server [" + profileName + "]"); } response.append(s); inputStream = null; } } else if (method.equals("POST") && (argument.contains("MS_MediaReceiverRegistrar_control") || argument.contains("mrr/control"))) { output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/xml; charset=\"utf-8\""); response.append(HTTPXMLHelper.XML_HEADER); response.append(CRLF); response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER); response.append(CRLF); if (soapaction != null && soapaction.contains("IsAuthorized")) { response.append(HTTPXMLHelper.XBOX_2); response.append(CRLF); } else if (soapaction != null && soapaction.contains("IsValidated")) { response.append(HTTPXMLHelper.XBOX_1); response.append(CRLF); } response.append(HTTPXMLHelper.BROWSERESPONSE_FOOTER); response.append(CRLF); response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER); response.append(CRLF); } else if (method.equals("POST") && argument.endsWith("upnp/control/connection_manager")) { output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/xml; charset=\"utf-8\""); if (soapaction != null && soapaction.indexOf("ConnectionManager:1#GetProtocolInfo") > -1) { response.append(HTTPXMLHelper.XML_HEADER); response.append(CRLF); response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER); response.append(CRLF); response.append(HTTPXMLHelper.PROTOCOLINFO_RESPONSE); response.append(CRLF); response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER); response.append(CRLF); } } else if (method.equals("POST") && argument.endsWith("upnp/control/content_directory")) { output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/xml; charset=\"utf-8\""); if (soapaction != null && soapaction.indexOf("ContentDirectory:1#GetSystemUpdateID") > -1) { response.append(HTTPXMLHelper.XML_HEADER); response.append(CRLF); response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER); response.append(CRLF); response.append(HTTPXMLHelper.GETSYSTEMUPDATEID_HEADER); response.append(CRLF); response.append("<Id>").append(DLNAResource.getSystemUpdateId()).append("</Id>"); response.append(CRLF); response.append(HTTPXMLHelper.GETSYSTEMUPDATEID_FOOTER); response.append(CRLF); response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER); response.append(CRLF); } else if (soapaction != null && soapaction.indexOf("ContentDirectory:1#X_GetFeatureList") > -1) { // Added for Samsung 2012 TVs response.append(HTTPXMLHelper.XML_HEADER); response.append(CRLF); response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER); response.append(CRLF); response.append(HTTPXMLHelper.SAMSUNG_ERROR_RESPONSE); response.append(CRLF); response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER); response.append(CRLF); } else if (soapaction != null && soapaction.indexOf("ContentDirectory:1#GetSortCapabilities") > -1) { response.append(HTTPXMLHelper.XML_HEADER); response.append(CRLF); response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER); response.append(CRLF); response.append(HTTPXMLHelper.SORTCAPS_RESPONSE); response.append(CRLF); response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER); response.append(CRLF); } else if (soapaction != null && soapaction.indexOf("ContentDirectory:1#GetSearchCapabilities") > -1) { response.append(HTTPXMLHelper.XML_HEADER); response.append(CRLF); response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER); response.append(CRLF); response.append(HTTPXMLHelper.SEARCHCAPS_RESPONSE); response.append(CRLF); response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER); response.append(CRLF); } else if (soapaction != null && (soapaction.contains("ContentDirectory:1#Browse") || soapaction.contains("ContentDirectory:1#Search"))) { objectID = getEnclosingValue(content, "<ObjectID>", "</ObjectID>"); String containerID = null; if ((objectID == null || objectID.length() == 0)) { containerID = getEnclosingValue(content, "<ContainerID>", "</ContainerID>"); if (containerID == null || !containerID.contains("$")) { objectID = "0"; } else { objectID = containerID; containerID = null; } } Object sI = getEnclosingValue(content, "<StartingIndex>", "</StartingIndex>"); Object rC = getEnclosingValue(content, "<RequestedCount>", "</RequestedCount>"); browseFlag = getEnclosingValue(content, "<BrowseFlag>", "</BrowseFlag>"); if (sI != null) { startingIndex = Integer.parseInt(sI.toString()); } if (rC != null) { requestCount = Integer.parseInt(rC.toString()); } response.append(HTTPXMLHelper.XML_HEADER); response.append(CRLF); response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER); response.append(CRLF); if (soapaction != null && soapaction.contains("ContentDirectory:1#Search")) { response.append(HTTPXMLHelper.SEARCHRESPONSE_HEADER); } else { response.append(HTTPXMLHelper.BROWSERESPONSE_HEADER); } response.append(CRLF); response.append(HTTPXMLHelper.RESULT_HEADER); response.append(HTTPXMLHelper.DIDL_HEADER); if (soapaction != null && soapaction.contains("ContentDirectory:1#Search")) { browseFlag = "BrowseDirectChildren"; } // Xbox virtual containers ... d'oh! String searchCriteria = null; if (xbox && configuration.getUseCache() && PMS.get().getLibrary() != null && containerID != null) { if (containerID.equals("7") && PMS.get().getLibrary().getAlbumFolder() != null) { objectID = PMS.get().getLibrary().getAlbumFolder().getResourceId(); } else if (containerID.equals("6") && PMS.get().getLibrary().getArtistFolder() != null) { objectID = PMS.get().getLibrary().getArtistFolder().getResourceId(); } else if (containerID.equals("5") && PMS.get().getLibrary().getGenreFolder() != null) { objectID = PMS.get().getLibrary().getGenreFolder().getResourceId(); } else if (containerID.equals("F") && PMS.get().getLibrary().getPlaylistFolder() != null) { objectID = PMS.get().getLibrary().getPlaylistFolder().getResourceId(); } else if (containerID.equals("4") && PMS.get().getLibrary().getAllFolder() != null) { objectID = PMS.get().getLibrary().getAllFolder().getResourceId(); } else if (containerID.equals("1")) { String artist = getEnclosingValue(content, "upnp:artist = &quot;", "&quot;)"); if (artist != null) { objectID = PMS.get().getLibrary().getArtistFolder().getResourceId(); searchCriteria = artist; } } } else if (soapaction.contains("ContentDirectory:1#Search")) { searchCriteria = getEnclosingValue(content, "<SearchCriteria>", "</SearchCriteria>"); } List<DLNAResource> files = PMS.get().getRootFolder(mediaRenderer).getDLNAResources( objectID, browseFlag != null && browseFlag.equals("BrowseDirectChildren"), startingIndex, requestCount, mediaRenderer, searchCriteria ); if (searchCriteria != null && files != null) { searchCriteria = searchCriteria.toLowerCase(); for (int i = files.size() - 1; i >= 0; i--) { DLNAResource res = files.get(i); if (res.isSearched()) { continue; } boolean keep = res.getName().toLowerCase().indexOf(searchCriteria) != -1; final DLNAMediaInfo media = res.getMedia(); if (media!=null) { for (int j = 0;j < media.getAudioTracksList().size(); j++) { DLNAMediaAudio audio = media.getAudioTracksList().get(j); keep |= audio.getAlbum().toLowerCase().indexOf(searchCriteria) != -1; keep |= audio.getArtist().toLowerCase().indexOf(searchCriteria) != -1; keep |= audio.getSongname().toLowerCase().indexOf(searchCriteria) != -1; } } if (!keep) { // dump it files.remove(i); } } if (xbox) { if (files.size() > 0) { files = files.get(0).getChildren(); } } } int minus = 0; if (files != null) { for (DLNAResource uf : files) { if (xbox && containerID != null) { uf.setFakeParentId(containerID); } if (uf.isCompatible(mediaRenderer) && (uf.getPlayer() == null || uf.getPlayer().isPlayerCompatible(mediaRenderer))) { response.append(uf.getDidlString(mediaRenderer)); } else { minus++; } } } response.append(HTTPXMLHelper.DIDL_FOOTER); response.append(HTTPXMLHelper.RESULT_FOOTER); response.append(CRLF); int filessize = 0; if (files != null) { filessize = files.size(); } response.append("<NumberReturned>").append(filessize - minus).append("</NumberReturned>"); response.append(CRLF); DLNAResource parentFolder = null; if (files != null && filessize > 0) { parentFolder = files.get(0).getParent(); } if (browseFlag != null && browseFlag.equals("BrowseDirectChildren") && mediaRenderer.isMediaParserV2() && mediaRenderer.isDLNATreeHack()) { // with the new parser, files are parsed and analyzed *before* // creating the DLNA tree, every 10 items (the ps3 asks 10 by 10), // so we do not know exactly the total number of items in the DLNA folder to send // (regular files, plus the #transcode folder, maybe the #imdb one, also files can be // invalidated and hidden if format is broken or encrypted, etc.). // let's send a fake total size to force the renderer to ask following items int totalCount = startingIndex + requestCount + 1; // returns 11 when 10 asked // If no more elements, send the startingIndex if (filessize - minus <= 0) { totalCount = startingIndex; } response.append("<TotalMatches>").append(totalCount).append("</TotalMatches>"); } else if (browseFlag != null && browseFlag.equals("BrowseDirectChildren")) { response.append("<TotalMatches>").append(((parentFolder != null) ? parentFolder.childrenNumber() : filessize) - minus).append("</TotalMatches>"); } else { // From upnp spec: If BrowseMetadata is specified in the BrowseFlags then TotalMatches = 1 response.append("<TotalMatches>1</TotalMatches>"); } response.append(CRLF); response.append("<UpdateID>"); if (parentFolder != null) { response.append(parentFolder.getUpdateId()); } else { response.append("1"); } response.append("</UpdateID>"); response.append(CRLF); if (soapaction != null && soapaction.contains("ContentDirectory:1#Search")) { response.append(HTTPXMLHelper.SEARCHRESPONSE_FOOTER); } else { response.append(HTTPXMLHelper.BROWSERESPONSE_FOOTER); } response.append(CRLF); response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER); response.append(CRLF); LOGGER.trace(response.toString()); } } else if (method.equals("SUBSCRIBE")) { output.setHeader("SID", PMS.get().usn()); output.setHeader("TIMEOUT", "Second-1800"); if (soapaction != null) { String cb = soapaction.replace("<", "").replace(">", ""); try { URL soapActionUrl = new URL(cb); String addr = soapActionUrl.getHost(); int port = soapActionUrl.getPort(); Socket sock = new Socket(addr,port); try (OutputStream out = sock.getOutputStream()) { out.write(("NOTIFY /" + argument + " HTTP/1.1").getBytes()); out.write(CRLF.getBytes()); out.write(("SID: " + PMS.get().usn()).getBytes()); out.write(CRLF.getBytes()); out.write(("SEQ: " + 0).getBytes()); out.write(CRLF.getBytes()); out.write(("NT: upnp:event").getBytes()); out.write(CRLF.getBytes()); out.write(("NTS: upnp:propchange").getBytes()); out.write(CRLF.getBytes()); out.write(("HOST: " + addr + ":" + port).getBytes()); out.write(CRLF.getBytes()); out.flush(); sock.close(); } } catch (MalformedURLException ex) { LOGGER.debug("Cannot parse address and port from soap action \"" + soapaction + "\"", ex); } } else { LOGGER.debug("Expected soap action in request"); } if (argument.contains("connection_manager")) { response.append(HTTPXMLHelper.eventHeader("urn:schemas-upnp-org:service:ConnectionManager:1")); response.append(HTTPXMLHelper.eventProp("SinkProtocolInfo")); response.append(HTTPXMLHelper.eventProp("SourceProtocolInfo")); response.append(HTTPXMLHelper.eventProp("CurrentConnectionIDs")); response.append(HTTPXMLHelper.EVENT_FOOTER); } else if (argument.contains("content_directory")) { response.append(HTTPXMLHelper.eventHeader("urn:schemas-upnp-org:service:ContentDirectory:1")); response.append(HTTPXMLHelper.eventProp("TransferIDs")); response.append(HTTPXMLHelper.eventProp("ContainerUpdateIDs")); response.append(HTTPXMLHelper.eventProp("SystemUpdateID", "" + DLNAResource.getSystemUpdateId())); response.append(HTTPXMLHelper.EVENT_FOOTER); } } else if (method.equals("NOTIFY")) { output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/xml"); output.setHeader("NT", "upnp:event"); output.setHeader("NTS", "upnp:propchange"); output.setHeader("SID", PMS.get().usn()); output.setHeader("SEQ", "0"); response.append("<e:propertyset xmlns:e=\"urn:schemas-upnp-org:event-1-0\">"); response.append("<e:property>"); response.append("<TransferIDs></TransferIDs>"); response.append("</e:property>"); response.append("<e:property>"); response.append("<ContainerUpdateIDs></ContainerUpdateIDs>"); response.append("</e:property>"); response.append("<e:property>"); response.append("<SystemUpdateID>").append(DLNAResource.getSystemUpdateId()).append("</SystemUpdateID>"); response.append("</e:property>"); response.append("</e:propertyset>"); } output.setHeader("Server", PMS.get().getServerName()); if (response.length() > 0) { // A response message was constructed; convert it to data ready to be sent. byte responseData[] = response.toString().getBytes("UTF-8"); output.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "" + responseData.length); // HEAD requests only require headers to be set, no need to set contents. if (!method.equals("HEAD")) { // Not a HEAD request, so set the contents of the response. ChannelBuffer buf = ChannelBuffers.copiedBuffer(responseData); output.setContent(buf); } // Send the response to the client. future = e.getChannel().write(output); if (close) { // Close the channel after the response is sent. future.addListener(ChannelFutureListener.CLOSE); } } else if (inputStream != null) { // There is an input stream to send as a response. if (CLoverride > -2) { // Content-Length override has been set, send or omit as appropriate if (CLoverride > -1 && CLoverride != DLNAMediaInfo.TRANS_SIZE) { // Since PS3 firmware 2.50, it is wiser not to send an arbitrary Content-Length, // as the PS3 will display a network error and request the last seconds of the // transcoded video. Better to send no Content-Length at all. output.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "" + CLoverride); } } else { int cl = inputStream.available(); LOGGER.trace("Available Content-Length: " + cl); output.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "" + cl); } if (range.isStartOffsetAvailable() && dlna != null) { // Add timeseek information headers. - String timeseekValue = DLNAMediaInfo.getDurationString(range.getStartOrZero()); + String timeseekValue = StringUtil.convertTimeToString(range.getStartOrZero(), StringUtil.DURATION_TIME_FORMAT); String timetotalValue = dlna.getMedia().getDurationString(); - String timeEndValue = range.isEndLimitAvailable() ? DLNAMediaInfo.getDurationString(range.getEnd()) : timetotalValue; + String timeEndValue = range.isEndLimitAvailable() ? StringUtil.convertTimeToString(range.getEnd(), StringUtil.DURATION_TIME_FORMAT) : timetotalValue; output.setHeader("TimeSeekRange.dlna.org", "npt=" + timeseekValue + "-" + timeEndValue + "/" + timetotalValue); output.setHeader("X-Seek-Range", "npt=" + timeseekValue + "-" + timeEndValue + "/" + timetotalValue); } // Send the response headers to the client. future = e.getChannel().write(output); if (lowRange != DLNAMediaInfo.ENDFILE_POS && !method.equals("HEAD")) { // Send the response body to the client in chunks. ChannelFuture chunkWriteFuture = e.getChannel().write(new ChunkedStream(inputStream, BUFFER_SIZE)); // Add a listener to clean up after sending the entire response body. chunkWriteFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) { try { PMS.get().getRegistry().reenableGoToSleep(); inputStream.close(); } catch (IOException e) { LOGGER.debug("Caught exception", e); } // Always close the channel after the response is sent because of // a freeze at the end of video when the channel is not closed. future.getChannel().close(); startStopListenerDelegate.stop(); } }); } else { // HEAD method is being used, so simply clean up after the response was sent. try { PMS.get().getRegistry().reenableGoToSleep(); inputStream.close(); } catch (IOException ioe) { LOGGER.debug("Caught exception", ioe); } if (close) { // Close the channel after the response is sent future.addListener(ChannelFutureListener.CLOSE); } startStopListenerDelegate.stop(); } } else { // No response data and no input stream. Seems we are merely serving up headers. if (lowRange > 0 && highRange > 0) { // FIXME: There is no content, so why set a length? output.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "" + (highRange - lowRange + 1)); } else { output.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "0"); } // Send the response headers to the client. future = e.getChannel().write(output); if (close) { // Close the channel after the response is sent. future.addListener(ChannelFutureListener.CLOSE); } } // Log trace information Iterator<String> it = output.getHeaderNames().iterator(); while (it.hasNext()) { String headerName = it.next(); LOGGER.trace("Sent to socket: " + headerName + ": " + output.getHeader(headerName)); } return future; } /** * Returns a date somewhere in the far future. * @return The {@link String} containing the date */ private String getFUTUREDATE() { sdf.setTimeZone(TimeZone.getTimeZone("GMT")); return sdf.format(new Date(10000000000L + System.currentTimeMillis())); } /** * Returns the string value that is enclosed by the left and right tag in a content string. * Only the first match of each tag is used to determine positions. If either of the tags * cannot be found, null is returned. * @param content The entire {@link String} that needs to be searched for the left and right tag. * @param leftTag The {@link String} determining the match for the left tag. * @param rightTag The {@link String} determining the match for the right tag. * @return The {@link String} that was enclosed by the left and right tag. */ private String getEnclosingValue(String content, String leftTag, String rightTag) { String result = null; int leftTagPos = content.indexOf(leftTag); int rightTagPos = content.indexOf(rightTag, leftTagPos + 1); if (leftTagPos > -1 && rightTagPos > leftTagPos) { result = content.substring(leftTagPos + leftTag.length(), rightTagPos); } return result; } }
false
true
public ChannelFuture answer( HttpResponse output, MessageEvent e, final boolean close, final StartStopListenerDelegate startStopListenerDelegate ) throws IOException { ChannelFuture future = null; long CLoverride = -2; // 0 and above are valid Content-Length values, -1 means omit StringBuilder response = new StringBuilder(); DLNAResource dlna = null; boolean xbox = mediaRenderer.isXBOX(); // Samsung 2012 TVs have a problematic preceding slash that needs to be removed. if (argument.startsWith("/")) { LOGGER.trace("Stripping preceding slash from: " + argument); argument = argument.substring(1); } if ((method.equals("GET") || method.equals("HEAD")) && argument.startsWith("console/")) { // Request to output a page to the HTML console. output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/html"); response.append(HTMLConsole.servePage(argument.substring(8))); } else if ((method.equals("GET") || method.equals("HEAD")) && argument.startsWith("get/")) { // Request to retrieve a file /** * Skip the leading "get/" and extract the resource ID from the first path element * e.g. "get/0$1$5$3$4/Foo.mp4" -> "0$1$5$3$4" * * ExSport: I spotted on Android it is asking for "/get/0$2$4$2$1$3" which generates exception with response: * "Http: Response, HTTP/1.1, Status: Internal server error, URL: /get/0$2$4$2$1$3" * This should fix it */ String id = argument.substring(4); if (argument.substring(4).contains("/")) { id = argument.substring(4, argument.lastIndexOf("/")); } // Some clients escape the separators in their request: unescape them. id = id.replace("%24", "$"); // Retrieve the DLNAresource itself. List<DLNAResource> files = PMS.get().getRootFolder(mediaRenderer).getDLNAResources(id, false, 0, 0, mediaRenderer); if (transferMode != null) { output.setHeader("TransferMode.DLNA.ORG", transferMode); } if (files.size() == 1) { // DLNAresource was found. dlna = files.get(0); String fileName = argument.substring(argument.lastIndexOf("/") + 1); if (fileName.startsWith("thumbnail0000")) { // This is a request for a thumbnail file. output.setHeader(HttpHeaders.Names.CONTENT_TYPE, dlna.getThumbnailContentType()); output.setHeader(HttpHeaders.Names.ACCEPT_RANGES, "bytes"); output.setHeader(HttpHeaders.Names.EXPIRES, getFUTUREDATE() + " GMT"); output.setHeader(HttpHeaders.Names.CONNECTION, "keep-alive"); if (mediaRenderer.isMediaParserV2()) { dlna.checkThumbnail(); } inputStream = dlna.getThumbnailInputStream(); } else if (fileName.indexOf("subtitle0000") > -1) { // This is a request for a subtitle file output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/plain"); output.setHeader(HttpHeaders.Names.EXPIRES, getFUTUREDATE() + " GMT"); List<DLNAMediaSubtitle> subs = dlna.getMedia().getSubtitleTracksList(); if (subs != null && !subs.isEmpty()) { // TODO: maybe loop subs to get the requested subtitle type instead of using the first one DLNAMediaSubtitle sub = subs.get(0); try { // XXX external file is null if the first subtitle track is embedded: // http://www.ps3mediaserver.org/forum/viewtopic.php?f=3&t=15805&p=75534#p75534 if (sub.isExternal()) { inputStream = new java.io.FileInputStream(sub.getExternalFile()); } } catch (NullPointerException npe) { LOGGER.trace("Could not find external subtitles: " + sub); } } } else { // This is a request for a regular file. // If range has not been initialized yet and the DLNAResource has its // own start and end defined, initialize range with those values before // requesting the input stream. Range.Time splitRange = dlna.getSplitRange(); if (range.getStart() == null && splitRange.getStart() != null) { range.setStart(splitRange.getStart()); } if (range.getEnd() == null && splitRange.getEnd() != null) { range.setEnd(splitRange.getEnd()); } inputStream = dlna.getInputStream(Range.create(lowRange, highRange, range.getStart(), range.getEnd()), mediaRenderer); if (!configuration.isDisableSubtitles()) { // Some renderers (like Samsung devices) allow a custom header for a subtitle URL String subtitleHttpHeader = mediaRenderer.getSubtitleHttpHeader(); if (subtitleHttpHeader != null && !"".equals(subtitleHttpHeader)) { // Device allows a custom subtitle HTTP header; construct it List<DLNAMediaSubtitle> subs = dlna.getMedia().getSubtitleTracksList(); if (subs != null && !subs.isEmpty()) { DLNAMediaSubtitle sub = subs.get(0); String subtitleUrl; String subExtension = sub.getType().getExtension(); if (isNotBlank(subExtension)) { subtitleUrl = "http://" + PMS.get().getServer().getHost() + ':' + PMS.get().getServer().getPort() + "/get/" + id + "/subtitle0000." + subExtension; } else { subtitleUrl = "http://" + PMS.get().getServer().getHost() + ':' + PMS.get().getServer().getPort() + "/get/" + id + "/subtitle0000"; } output.setHeader(subtitleHttpHeader, subtitleUrl); } } } String name = dlna.getDisplayName(mediaRenderer); if (dlna.isNoName()) { name = dlna.getName() + " " + dlna.getDisplayName(mediaRenderer); } if (inputStream == null) { // No inputStream indicates that transcoding / remuxing probably crashed. LOGGER.error("There is no inputstream to return for " + name); } else { // Notify plugins that the DLNAresource is about to start playing startStopListenerDelegate.start(dlna); // Try to determine the content type of the file String rendererMimeType = getRendererMimeType(dlna.mimeType(), mediaRenderer); if (rendererMimeType != null && !"".equals(rendererMimeType)) { output.setHeader(HttpHeaders.Names.CONTENT_TYPE, rendererMimeType); } PMS.get().getFrame().setStatusLine("Serving " + name); // Response generation: // We use -1 for arithmetic convenience but don't send it as a value. // If Content-Length < 0 we omit it, for Content-Range we use '*' to signify unspecified. boolean chunked = mediaRenderer.isChunkedTransfer(); // Determine the total size. Note: when transcoding the length is // not known in advance, so DLNAMediaInfo.TRANS_SIZE will be returned instead. long totalsize = dlna.length(mediaRenderer); if (chunked && totalsize == DLNAMediaInfo.TRANS_SIZE) { // In chunked mode we try to avoid arbitrary values. totalsize = -1; } long remaining = totalsize - lowRange; long requested = highRange - lowRange; if (requested != 0) { // Determine the range (i.e. smaller of known or requested bytes) long bytes = remaining > -1 ? remaining : inputStream.available(); if (requested > 0 && bytes > requested) { bytes = requested + 1; } // Calculate the corresponding highRange (this is usually redundant). highRange = lowRange + bytes - (bytes > 0 ? 1 : 0); LOGGER.trace((chunked ? "Using chunked response. " : "") + "Sending " + bytes + " bytes."); output.setHeader(HttpHeaders.Names.CONTENT_RANGE, "bytes " + lowRange + "-" + (highRange > -1 ? highRange : "*") + "/" + (totalsize > -1 ? totalsize : "*")); // Content-Length refers to the current chunk size here, though in chunked // mode if the request is open-ended and totalsize is unknown we omit it. if (chunked && requested < 0 && totalsize < 0) { CLoverride = -1; } else { CLoverride = bytes; } } else { // Content-Length refers to the total remaining size of the stream here. CLoverride = remaining; } // Calculate the corresponding highRange (this is usually redundant). highRange = lowRange + CLoverride - (CLoverride > 0 ? 1 : 0); if (contentFeatures != null) { output.setHeader("ContentFeatures.DLNA.ORG", dlna.getDlnaContentFeatures()); } output.setHeader(HttpHeaders.Names.ACCEPT_RANGES, "bytes"); output.setHeader(HttpHeaders.Names.CONNECTION, "keep-alive"); } } } } else if ((method.equals("GET") || method.equals("HEAD")) && (argument.toLowerCase().endsWith(".png") || argument.toLowerCase().endsWith(".jpg") || argument.toLowerCase().endsWith(".jpeg"))) { if (argument.toLowerCase().endsWith(".png")) { output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "image/png"); } else { output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "image/jpeg"); } output.setHeader(HttpHeaders.Names.ACCEPT_RANGES, "bytes"); output.setHeader(HttpHeaders.Names.CONNECTION, "keep-alive"); output.setHeader(HttpHeaders.Names.EXPIRES, getFUTUREDATE() + " GMT"); inputStream = getResourceInputStream(argument); } else if ((method.equals("GET") || method.equals("HEAD")) && (argument.equals("description/fetch") || argument.endsWith("1.0.xml"))) { output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/xml; charset=\"utf-8\""); output.setHeader(HttpHeaders.Names.CACHE_CONTROL, "no-cache"); output.setHeader(HttpHeaders.Names.EXPIRES, "0"); output.setHeader(HttpHeaders.Names.ACCEPT_RANGES, "bytes"); output.setHeader(HttpHeaders.Names.CONNECTION, "keep-alive"); inputStream = getResourceInputStream((argument.equals("description/fetch") ? "PMS.xml" : argument)); if (argument.equals("description/fetch")) { byte b[] = new byte[inputStream.available()]; inputStream.read(b); String s = new String(b); s = s.replace("[uuid]", PMS.get().usn()); //.substring(0, PMS.get().usn().length()-2)); String profileName = configuration.getProfileName(); if (PMS.get().getServer().getHost() != null) { s = s.replace("[host]", PMS.get().getServer().getHost()); s = s.replace("[port]", "" + PMS.get().getServer().getPort()); } if (xbox) { LOGGER.debug("DLNA changes for Xbox 360"); s = s.replace("Universal Media Server", "Universal Media Server [" + profileName + "] : Windows Media Connect"); s = s.replace("<modelName>UMS</modelName>", "<modelName>Windows Media Connect</modelName>"); s = s.replace("<serviceList>", "<serviceList>" + CRLF + "<service>" + CRLF + "<serviceType>urn:microsoft.com:service:X_MS_MediaReceiverRegistrar:1</serviceType>" + CRLF + "<serviceId>urn:microsoft.com:serviceId:X_MS_MediaReceiverRegistrar</serviceId>" + CRLF + "<SCPDURL>/upnp/mrr/scpd</SCPDURL>" + CRLF + "<controlURL>/upnp/mrr/control</controlURL>" + CRLF + "</service>" + CRLF); } else { s = s.replace("Universal Media Server", "Universal Media Server [" + profileName + "]"); } response.append(s); inputStream = null; } } else if (method.equals("POST") && (argument.contains("MS_MediaReceiverRegistrar_control") || argument.contains("mrr/control"))) { output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/xml; charset=\"utf-8\""); response.append(HTTPXMLHelper.XML_HEADER); response.append(CRLF); response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER); response.append(CRLF); if (soapaction != null && soapaction.contains("IsAuthorized")) { response.append(HTTPXMLHelper.XBOX_2); response.append(CRLF); } else if (soapaction != null && soapaction.contains("IsValidated")) { response.append(HTTPXMLHelper.XBOX_1); response.append(CRLF); } response.append(HTTPXMLHelper.BROWSERESPONSE_FOOTER); response.append(CRLF); response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER); response.append(CRLF); } else if (method.equals("POST") && argument.endsWith("upnp/control/connection_manager")) { output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/xml; charset=\"utf-8\""); if (soapaction != null && soapaction.indexOf("ConnectionManager:1#GetProtocolInfo") > -1) { response.append(HTTPXMLHelper.XML_HEADER); response.append(CRLF); response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER); response.append(CRLF); response.append(HTTPXMLHelper.PROTOCOLINFO_RESPONSE); response.append(CRLF); response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER); response.append(CRLF); } } else if (method.equals("POST") && argument.endsWith("upnp/control/content_directory")) { output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/xml; charset=\"utf-8\""); if (soapaction != null && soapaction.indexOf("ContentDirectory:1#GetSystemUpdateID") > -1) { response.append(HTTPXMLHelper.XML_HEADER); response.append(CRLF); response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER); response.append(CRLF); response.append(HTTPXMLHelper.GETSYSTEMUPDATEID_HEADER); response.append(CRLF); response.append("<Id>").append(DLNAResource.getSystemUpdateId()).append("</Id>"); response.append(CRLF); response.append(HTTPXMLHelper.GETSYSTEMUPDATEID_FOOTER); response.append(CRLF); response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER); response.append(CRLF); } else if (soapaction != null && soapaction.indexOf("ContentDirectory:1#X_GetFeatureList") > -1) { // Added for Samsung 2012 TVs response.append(HTTPXMLHelper.XML_HEADER); response.append(CRLF); response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER); response.append(CRLF); response.append(HTTPXMLHelper.SAMSUNG_ERROR_RESPONSE); response.append(CRLF); response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER); response.append(CRLF); } else if (soapaction != null && soapaction.indexOf("ContentDirectory:1#GetSortCapabilities") > -1) { response.append(HTTPXMLHelper.XML_HEADER); response.append(CRLF); response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER); response.append(CRLF); response.append(HTTPXMLHelper.SORTCAPS_RESPONSE); response.append(CRLF); response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER); response.append(CRLF); } else if (soapaction != null && soapaction.indexOf("ContentDirectory:1#GetSearchCapabilities") > -1) { response.append(HTTPXMLHelper.XML_HEADER); response.append(CRLF); response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER); response.append(CRLF); response.append(HTTPXMLHelper.SEARCHCAPS_RESPONSE); response.append(CRLF); response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER); response.append(CRLF); } else if (soapaction != null && (soapaction.contains("ContentDirectory:1#Browse") || soapaction.contains("ContentDirectory:1#Search"))) { objectID = getEnclosingValue(content, "<ObjectID>", "</ObjectID>"); String containerID = null; if ((objectID == null || objectID.length() == 0)) { containerID = getEnclosingValue(content, "<ContainerID>", "</ContainerID>"); if (containerID == null || !containerID.contains("$")) { objectID = "0"; } else { objectID = containerID; containerID = null; } } Object sI = getEnclosingValue(content, "<StartingIndex>", "</StartingIndex>"); Object rC = getEnclosingValue(content, "<RequestedCount>", "</RequestedCount>"); browseFlag = getEnclosingValue(content, "<BrowseFlag>", "</BrowseFlag>"); if (sI != null) { startingIndex = Integer.parseInt(sI.toString()); } if (rC != null) { requestCount = Integer.parseInt(rC.toString()); } response.append(HTTPXMLHelper.XML_HEADER); response.append(CRLF); response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER); response.append(CRLF); if (soapaction != null && soapaction.contains("ContentDirectory:1#Search")) { response.append(HTTPXMLHelper.SEARCHRESPONSE_HEADER); } else { response.append(HTTPXMLHelper.BROWSERESPONSE_HEADER); } response.append(CRLF); response.append(HTTPXMLHelper.RESULT_HEADER); response.append(HTTPXMLHelper.DIDL_HEADER); if (soapaction != null && soapaction.contains("ContentDirectory:1#Search")) { browseFlag = "BrowseDirectChildren"; } // Xbox virtual containers ... d'oh! String searchCriteria = null; if (xbox && configuration.getUseCache() && PMS.get().getLibrary() != null && containerID != null) { if (containerID.equals("7") && PMS.get().getLibrary().getAlbumFolder() != null) { objectID = PMS.get().getLibrary().getAlbumFolder().getResourceId(); } else if (containerID.equals("6") && PMS.get().getLibrary().getArtistFolder() != null) { objectID = PMS.get().getLibrary().getArtistFolder().getResourceId(); } else if (containerID.equals("5") && PMS.get().getLibrary().getGenreFolder() != null) { objectID = PMS.get().getLibrary().getGenreFolder().getResourceId(); } else if (containerID.equals("F") && PMS.get().getLibrary().getPlaylistFolder() != null) { objectID = PMS.get().getLibrary().getPlaylistFolder().getResourceId(); } else if (containerID.equals("4") && PMS.get().getLibrary().getAllFolder() != null) { objectID = PMS.get().getLibrary().getAllFolder().getResourceId(); } else if (containerID.equals("1")) { String artist = getEnclosingValue(content, "upnp:artist = &quot;", "&quot;)"); if (artist != null) { objectID = PMS.get().getLibrary().getArtistFolder().getResourceId(); searchCriteria = artist; } } } else if (soapaction.contains("ContentDirectory:1#Search")) { searchCriteria = getEnclosingValue(content, "<SearchCriteria>", "</SearchCriteria>"); } List<DLNAResource> files = PMS.get().getRootFolder(mediaRenderer).getDLNAResources( objectID, browseFlag != null && browseFlag.equals("BrowseDirectChildren"), startingIndex, requestCount, mediaRenderer, searchCriteria ); if (searchCriteria != null && files != null) { searchCriteria = searchCriteria.toLowerCase(); for (int i = files.size() - 1; i >= 0; i--) { DLNAResource res = files.get(i); if (res.isSearched()) { continue; } boolean keep = res.getName().toLowerCase().indexOf(searchCriteria) != -1; final DLNAMediaInfo media = res.getMedia(); if (media!=null) { for (int j = 0;j < media.getAudioTracksList().size(); j++) { DLNAMediaAudio audio = media.getAudioTracksList().get(j); keep |= audio.getAlbum().toLowerCase().indexOf(searchCriteria) != -1; keep |= audio.getArtist().toLowerCase().indexOf(searchCriteria) != -1; keep |= audio.getSongname().toLowerCase().indexOf(searchCriteria) != -1; } } if (!keep) { // dump it files.remove(i); } } if (xbox) { if (files.size() > 0) { files = files.get(0).getChildren(); } } } int minus = 0; if (files != null) { for (DLNAResource uf : files) { if (xbox && containerID != null) { uf.setFakeParentId(containerID); } if (uf.isCompatible(mediaRenderer) && (uf.getPlayer() == null || uf.getPlayer().isPlayerCompatible(mediaRenderer))) { response.append(uf.getDidlString(mediaRenderer)); } else { minus++; } } } response.append(HTTPXMLHelper.DIDL_FOOTER); response.append(HTTPXMLHelper.RESULT_FOOTER); response.append(CRLF); int filessize = 0; if (files != null) { filessize = files.size(); } response.append("<NumberReturned>").append(filessize - minus).append("</NumberReturned>"); response.append(CRLF); DLNAResource parentFolder = null; if (files != null && filessize > 0) { parentFolder = files.get(0).getParent(); } if (browseFlag != null && browseFlag.equals("BrowseDirectChildren") && mediaRenderer.isMediaParserV2() && mediaRenderer.isDLNATreeHack()) { // with the new parser, files are parsed and analyzed *before* // creating the DLNA tree, every 10 items (the ps3 asks 10 by 10), // so we do not know exactly the total number of items in the DLNA folder to send // (regular files, plus the #transcode folder, maybe the #imdb one, also files can be // invalidated and hidden if format is broken or encrypted, etc.). // let's send a fake total size to force the renderer to ask following items int totalCount = startingIndex + requestCount + 1; // returns 11 when 10 asked // If no more elements, send the startingIndex if (filessize - minus <= 0) { totalCount = startingIndex; } response.append("<TotalMatches>").append(totalCount).append("</TotalMatches>"); } else if (browseFlag != null && browseFlag.equals("BrowseDirectChildren")) { response.append("<TotalMatches>").append(((parentFolder != null) ? parentFolder.childrenNumber() : filessize) - minus).append("</TotalMatches>"); } else { // From upnp spec: If BrowseMetadata is specified in the BrowseFlags then TotalMatches = 1 response.append("<TotalMatches>1</TotalMatches>"); } response.append(CRLF); response.append("<UpdateID>"); if (parentFolder != null) { response.append(parentFolder.getUpdateId()); } else { response.append("1"); } response.append("</UpdateID>"); response.append(CRLF); if (soapaction != null && soapaction.contains("ContentDirectory:1#Search")) { response.append(HTTPXMLHelper.SEARCHRESPONSE_FOOTER); } else { response.append(HTTPXMLHelper.BROWSERESPONSE_FOOTER); } response.append(CRLF); response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER); response.append(CRLF); LOGGER.trace(response.toString()); } } else if (method.equals("SUBSCRIBE")) { output.setHeader("SID", PMS.get().usn()); output.setHeader("TIMEOUT", "Second-1800"); if (soapaction != null) { String cb = soapaction.replace("<", "").replace(">", ""); try { URL soapActionUrl = new URL(cb); String addr = soapActionUrl.getHost(); int port = soapActionUrl.getPort(); Socket sock = new Socket(addr,port); try (OutputStream out = sock.getOutputStream()) { out.write(("NOTIFY /" + argument + " HTTP/1.1").getBytes()); out.write(CRLF.getBytes()); out.write(("SID: " + PMS.get().usn()).getBytes()); out.write(CRLF.getBytes()); out.write(("SEQ: " + 0).getBytes()); out.write(CRLF.getBytes()); out.write(("NT: upnp:event").getBytes()); out.write(CRLF.getBytes()); out.write(("NTS: upnp:propchange").getBytes()); out.write(CRLF.getBytes()); out.write(("HOST: " + addr + ":" + port).getBytes()); out.write(CRLF.getBytes()); out.flush(); sock.close(); } } catch (MalformedURLException ex) { LOGGER.debug("Cannot parse address and port from soap action \"" + soapaction + "\"", ex); } } else { LOGGER.debug("Expected soap action in request"); } if (argument.contains("connection_manager")) { response.append(HTTPXMLHelper.eventHeader("urn:schemas-upnp-org:service:ConnectionManager:1")); response.append(HTTPXMLHelper.eventProp("SinkProtocolInfo")); response.append(HTTPXMLHelper.eventProp("SourceProtocolInfo")); response.append(HTTPXMLHelper.eventProp("CurrentConnectionIDs")); response.append(HTTPXMLHelper.EVENT_FOOTER); } else if (argument.contains("content_directory")) { response.append(HTTPXMLHelper.eventHeader("urn:schemas-upnp-org:service:ContentDirectory:1")); response.append(HTTPXMLHelper.eventProp("TransferIDs")); response.append(HTTPXMLHelper.eventProp("ContainerUpdateIDs")); response.append(HTTPXMLHelper.eventProp("SystemUpdateID", "" + DLNAResource.getSystemUpdateId())); response.append(HTTPXMLHelper.EVENT_FOOTER); } } else if (method.equals("NOTIFY")) { output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/xml"); output.setHeader("NT", "upnp:event"); output.setHeader("NTS", "upnp:propchange"); output.setHeader("SID", PMS.get().usn()); output.setHeader("SEQ", "0"); response.append("<e:propertyset xmlns:e=\"urn:schemas-upnp-org:event-1-0\">"); response.append("<e:property>"); response.append("<TransferIDs></TransferIDs>"); response.append("</e:property>"); response.append("<e:property>"); response.append("<ContainerUpdateIDs></ContainerUpdateIDs>"); response.append("</e:property>"); response.append("<e:property>"); response.append("<SystemUpdateID>").append(DLNAResource.getSystemUpdateId()).append("</SystemUpdateID>"); response.append("</e:property>"); response.append("</e:propertyset>"); } output.setHeader("Server", PMS.get().getServerName()); if (response.length() > 0) { // A response message was constructed; convert it to data ready to be sent. byte responseData[] = response.toString().getBytes("UTF-8"); output.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "" + responseData.length); // HEAD requests only require headers to be set, no need to set contents. if (!method.equals("HEAD")) { // Not a HEAD request, so set the contents of the response. ChannelBuffer buf = ChannelBuffers.copiedBuffer(responseData); output.setContent(buf); } // Send the response to the client. future = e.getChannel().write(output); if (close) { // Close the channel after the response is sent. future.addListener(ChannelFutureListener.CLOSE); } } else if (inputStream != null) { // There is an input stream to send as a response. if (CLoverride > -2) { // Content-Length override has been set, send or omit as appropriate if (CLoverride > -1 && CLoverride != DLNAMediaInfo.TRANS_SIZE) { // Since PS3 firmware 2.50, it is wiser not to send an arbitrary Content-Length, // as the PS3 will display a network error and request the last seconds of the // transcoded video. Better to send no Content-Length at all. output.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "" + CLoverride); } } else { int cl = inputStream.available(); LOGGER.trace("Available Content-Length: " + cl); output.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "" + cl); } if (range.isStartOffsetAvailable() && dlna != null) { // Add timeseek information headers. String timeseekValue = DLNAMediaInfo.getDurationString(range.getStartOrZero()); String timetotalValue = dlna.getMedia().getDurationString(); String timeEndValue = range.isEndLimitAvailable() ? DLNAMediaInfo.getDurationString(range.getEnd()) : timetotalValue; output.setHeader("TimeSeekRange.dlna.org", "npt=" + timeseekValue + "-" + timeEndValue + "/" + timetotalValue); output.setHeader("X-Seek-Range", "npt=" + timeseekValue + "-" + timeEndValue + "/" + timetotalValue); } // Send the response headers to the client. future = e.getChannel().write(output); if (lowRange != DLNAMediaInfo.ENDFILE_POS && !method.equals("HEAD")) { // Send the response body to the client in chunks. ChannelFuture chunkWriteFuture = e.getChannel().write(new ChunkedStream(inputStream, BUFFER_SIZE)); // Add a listener to clean up after sending the entire response body. chunkWriteFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) { try { PMS.get().getRegistry().reenableGoToSleep(); inputStream.close(); } catch (IOException e) { LOGGER.debug("Caught exception", e); } // Always close the channel after the response is sent because of // a freeze at the end of video when the channel is not closed. future.getChannel().close(); startStopListenerDelegate.stop(); } }); } else { // HEAD method is being used, so simply clean up after the response was sent. try { PMS.get().getRegistry().reenableGoToSleep(); inputStream.close(); } catch (IOException ioe) { LOGGER.debug("Caught exception", ioe); } if (close) { // Close the channel after the response is sent future.addListener(ChannelFutureListener.CLOSE); } startStopListenerDelegate.stop(); } } else { // No response data and no input stream. Seems we are merely serving up headers. if (lowRange > 0 && highRange > 0) { // FIXME: There is no content, so why set a length? output.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "" + (highRange - lowRange + 1)); } else { output.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "0"); } // Send the response headers to the client. future = e.getChannel().write(output); if (close) { // Close the channel after the response is sent. future.addListener(ChannelFutureListener.CLOSE); } } // Log trace information Iterator<String> it = output.getHeaderNames().iterator(); while (it.hasNext()) { String headerName = it.next(); LOGGER.trace("Sent to socket: " + headerName + ": " + output.getHeader(headerName)); } return future; }
public ChannelFuture answer( HttpResponse output, MessageEvent e, final boolean close, final StartStopListenerDelegate startStopListenerDelegate ) throws IOException { ChannelFuture future = null; long CLoverride = -2; // 0 and above are valid Content-Length values, -1 means omit StringBuilder response = new StringBuilder(); DLNAResource dlna = null; boolean xbox = mediaRenderer.isXBOX(); // Samsung 2012 TVs have a problematic preceding slash that needs to be removed. if (argument.startsWith("/")) { LOGGER.trace("Stripping preceding slash from: " + argument); argument = argument.substring(1); } if ((method.equals("GET") || method.equals("HEAD")) && argument.startsWith("console/")) { // Request to output a page to the HTML console. output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/html"); response.append(HTMLConsole.servePage(argument.substring(8))); } else if ((method.equals("GET") || method.equals("HEAD")) && argument.startsWith("get/")) { // Request to retrieve a file /** * Skip the leading "get/" and extract the resource ID from the first path element * e.g. "get/0$1$5$3$4/Foo.mp4" -> "0$1$5$3$4" * * ExSport: I spotted on Android it is asking for "/get/0$2$4$2$1$3" which generates exception with response: * "Http: Response, HTTP/1.1, Status: Internal server error, URL: /get/0$2$4$2$1$3" * This should fix it */ String id = argument.substring(4); if (argument.substring(4).contains("/")) { id = argument.substring(4, argument.lastIndexOf("/")); } // Some clients escape the separators in their request: unescape them. id = id.replace("%24", "$"); // Retrieve the DLNAresource itself. List<DLNAResource> files = PMS.get().getRootFolder(mediaRenderer).getDLNAResources(id, false, 0, 0, mediaRenderer); if (transferMode != null) { output.setHeader("TransferMode.DLNA.ORG", transferMode); } if (files.size() == 1) { // DLNAresource was found. dlna = files.get(0); String fileName = argument.substring(argument.lastIndexOf("/") + 1); if (fileName.startsWith("thumbnail0000")) { // This is a request for a thumbnail file. output.setHeader(HttpHeaders.Names.CONTENT_TYPE, dlna.getThumbnailContentType()); output.setHeader(HttpHeaders.Names.ACCEPT_RANGES, "bytes"); output.setHeader(HttpHeaders.Names.EXPIRES, getFUTUREDATE() + " GMT"); output.setHeader(HttpHeaders.Names.CONNECTION, "keep-alive"); if (mediaRenderer.isMediaParserV2()) { dlna.checkThumbnail(); } inputStream = dlna.getThumbnailInputStream(); } else if (fileName.indexOf("subtitle0000") > -1) { // This is a request for a subtitle file output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/plain"); output.setHeader(HttpHeaders.Names.EXPIRES, getFUTUREDATE() + " GMT"); List<DLNAMediaSubtitle> subs = dlna.getMedia().getSubtitleTracksList(); if (subs != null && !subs.isEmpty()) { // TODO: maybe loop subs to get the requested subtitle type instead of using the first one DLNAMediaSubtitle sub = subs.get(0); try { // XXX external file is null if the first subtitle track is embedded: // http://www.ps3mediaserver.org/forum/viewtopic.php?f=3&t=15805&p=75534#p75534 if (sub.isExternal()) { inputStream = new java.io.FileInputStream(sub.getExternalFile()); } } catch (NullPointerException npe) { LOGGER.trace("Could not find external subtitles: " + sub); } } } else { // This is a request for a regular file. // If range has not been initialized yet and the DLNAResource has its // own start and end defined, initialize range with those values before // requesting the input stream. Range.Time splitRange = dlna.getSplitRange(); if (range.getStart() == null && splitRange.getStart() != null) { range.setStart(splitRange.getStart()); } if (range.getEnd() == null && splitRange.getEnd() != null) { range.setEnd(splitRange.getEnd()); } inputStream = dlna.getInputStream(Range.create(lowRange, highRange, range.getStart(), range.getEnd()), mediaRenderer); if (!configuration.isDisableSubtitles()) { // Some renderers (like Samsung devices) allow a custom header for a subtitle URL String subtitleHttpHeader = mediaRenderer.getSubtitleHttpHeader(); if (subtitleHttpHeader != null && !"".equals(subtitleHttpHeader)) { // Device allows a custom subtitle HTTP header; construct it List<DLNAMediaSubtitle> subs = dlna.getMedia().getSubtitleTracksList(); if (subs != null && !subs.isEmpty()) { DLNAMediaSubtitle sub = subs.get(0); String subtitleUrl; String subExtension = sub.getType().getExtension(); if (isNotBlank(subExtension)) { subtitleUrl = "http://" + PMS.get().getServer().getHost() + ':' + PMS.get().getServer().getPort() + "/get/" + id + "/subtitle0000." + subExtension; } else { subtitleUrl = "http://" + PMS.get().getServer().getHost() + ':' + PMS.get().getServer().getPort() + "/get/" + id + "/subtitle0000"; } output.setHeader(subtitleHttpHeader, subtitleUrl); } } } String name = dlna.getDisplayName(mediaRenderer); if (dlna.isNoName()) { name = dlna.getName() + " " + dlna.getDisplayName(mediaRenderer); } if (inputStream == null) { // No inputStream indicates that transcoding / remuxing probably crashed. LOGGER.error("There is no inputstream to return for " + name); } else { // Notify plugins that the DLNAresource is about to start playing startStopListenerDelegate.start(dlna); // Try to determine the content type of the file String rendererMimeType = getRendererMimeType(dlna.mimeType(), mediaRenderer); if (rendererMimeType != null && !"".equals(rendererMimeType)) { output.setHeader(HttpHeaders.Names.CONTENT_TYPE, rendererMimeType); } PMS.get().getFrame().setStatusLine("Serving " + name); // Response generation: // We use -1 for arithmetic convenience but don't send it as a value. // If Content-Length < 0 we omit it, for Content-Range we use '*' to signify unspecified. boolean chunked = mediaRenderer.isChunkedTransfer(); // Determine the total size. Note: when transcoding the length is // not known in advance, so DLNAMediaInfo.TRANS_SIZE will be returned instead. long totalsize = dlna.length(mediaRenderer); if (chunked && totalsize == DLNAMediaInfo.TRANS_SIZE) { // In chunked mode we try to avoid arbitrary values. totalsize = -1; } long remaining = totalsize - lowRange; long requested = highRange - lowRange; if (requested != 0) { // Determine the range (i.e. smaller of known or requested bytes) long bytes = remaining > -1 ? remaining : inputStream.available(); if (requested > 0 && bytes > requested) { bytes = requested + 1; } // Calculate the corresponding highRange (this is usually redundant). highRange = lowRange + bytes - (bytes > 0 ? 1 : 0); LOGGER.trace((chunked ? "Using chunked response. " : "") + "Sending " + bytes + " bytes."); output.setHeader(HttpHeaders.Names.CONTENT_RANGE, "bytes " + lowRange + "-" + (highRange > -1 ? highRange : "*") + "/" + (totalsize > -1 ? totalsize : "*")); // Content-Length refers to the current chunk size here, though in chunked // mode if the request is open-ended and totalsize is unknown we omit it. if (chunked && requested < 0 && totalsize < 0) { CLoverride = -1; } else { CLoverride = bytes; } } else { // Content-Length refers to the total remaining size of the stream here. CLoverride = remaining; } // Calculate the corresponding highRange (this is usually redundant). highRange = lowRange + CLoverride - (CLoverride > 0 ? 1 : 0); if (contentFeatures != null) { output.setHeader("ContentFeatures.DLNA.ORG", dlna.getDlnaContentFeatures()); } output.setHeader(HttpHeaders.Names.ACCEPT_RANGES, "bytes"); output.setHeader(HttpHeaders.Names.CONNECTION, "keep-alive"); } } } } else if ((method.equals("GET") || method.equals("HEAD")) && (argument.toLowerCase().endsWith(".png") || argument.toLowerCase().endsWith(".jpg") || argument.toLowerCase().endsWith(".jpeg"))) { if (argument.toLowerCase().endsWith(".png")) { output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "image/png"); } else { output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "image/jpeg"); } output.setHeader(HttpHeaders.Names.ACCEPT_RANGES, "bytes"); output.setHeader(HttpHeaders.Names.CONNECTION, "keep-alive"); output.setHeader(HttpHeaders.Names.EXPIRES, getFUTUREDATE() + " GMT"); inputStream = getResourceInputStream(argument); } else if ((method.equals("GET") || method.equals("HEAD")) && (argument.equals("description/fetch") || argument.endsWith("1.0.xml"))) { output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/xml; charset=\"utf-8\""); output.setHeader(HttpHeaders.Names.CACHE_CONTROL, "no-cache"); output.setHeader(HttpHeaders.Names.EXPIRES, "0"); output.setHeader(HttpHeaders.Names.ACCEPT_RANGES, "bytes"); output.setHeader(HttpHeaders.Names.CONNECTION, "keep-alive"); inputStream = getResourceInputStream((argument.equals("description/fetch") ? "PMS.xml" : argument)); if (argument.equals("description/fetch")) { byte b[] = new byte[inputStream.available()]; inputStream.read(b); String s = new String(b); s = s.replace("[uuid]", PMS.get().usn()); //.substring(0, PMS.get().usn().length()-2)); String profileName = configuration.getProfileName(); if (PMS.get().getServer().getHost() != null) { s = s.replace("[host]", PMS.get().getServer().getHost()); s = s.replace("[port]", "" + PMS.get().getServer().getPort()); } if (xbox) { LOGGER.debug("DLNA changes for Xbox 360"); s = s.replace("Universal Media Server", "Universal Media Server [" + profileName + "] : Windows Media Connect"); s = s.replace("<modelName>UMS</modelName>", "<modelName>Windows Media Connect</modelName>"); s = s.replace("<serviceList>", "<serviceList>" + CRLF + "<service>" + CRLF + "<serviceType>urn:microsoft.com:service:X_MS_MediaReceiverRegistrar:1</serviceType>" + CRLF + "<serviceId>urn:microsoft.com:serviceId:X_MS_MediaReceiverRegistrar</serviceId>" + CRLF + "<SCPDURL>/upnp/mrr/scpd</SCPDURL>" + CRLF + "<controlURL>/upnp/mrr/control</controlURL>" + CRLF + "</service>" + CRLF); } else { s = s.replace("Universal Media Server", "Universal Media Server [" + profileName + "]"); } response.append(s); inputStream = null; } } else if (method.equals("POST") && (argument.contains("MS_MediaReceiverRegistrar_control") || argument.contains("mrr/control"))) { output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/xml; charset=\"utf-8\""); response.append(HTTPXMLHelper.XML_HEADER); response.append(CRLF); response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER); response.append(CRLF); if (soapaction != null && soapaction.contains("IsAuthorized")) { response.append(HTTPXMLHelper.XBOX_2); response.append(CRLF); } else if (soapaction != null && soapaction.contains("IsValidated")) { response.append(HTTPXMLHelper.XBOX_1); response.append(CRLF); } response.append(HTTPXMLHelper.BROWSERESPONSE_FOOTER); response.append(CRLF); response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER); response.append(CRLF); } else if (method.equals("POST") && argument.endsWith("upnp/control/connection_manager")) { output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/xml; charset=\"utf-8\""); if (soapaction != null && soapaction.indexOf("ConnectionManager:1#GetProtocolInfo") > -1) { response.append(HTTPXMLHelper.XML_HEADER); response.append(CRLF); response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER); response.append(CRLF); response.append(HTTPXMLHelper.PROTOCOLINFO_RESPONSE); response.append(CRLF); response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER); response.append(CRLF); } } else if (method.equals("POST") && argument.endsWith("upnp/control/content_directory")) { output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/xml; charset=\"utf-8\""); if (soapaction != null && soapaction.indexOf("ContentDirectory:1#GetSystemUpdateID") > -1) { response.append(HTTPXMLHelper.XML_HEADER); response.append(CRLF); response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER); response.append(CRLF); response.append(HTTPXMLHelper.GETSYSTEMUPDATEID_HEADER); response.append(CRLF); response.append("<Id>").append(DLNAResource.getSystemUpdateId()).append("</Id>"); response.append(CRLF); response.append(HTTPXMLHelper.GETSYSTEMUPDATEID_FOOTER); response.append(CRLF); response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER); response.append(CRLF); } else if (soapaction != null && soapaction.indexOf("ContentDirectory:1#X_GetFeatureList") > -1) { // Added for Samsung 2012 TVs response.append(HTTPXMLHelper.XML_HEADER); response.append(CRLF); response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER); response.append(CRLF); response.append(HTTPXMLHelper.SAMSUNG_ERROR_RESPONSE); response.append(CRLF); response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER); response.append(CRLF); } else if (soapaction != null && soapaction.indexOf("ContentDirectory:1#GetSortCapabilities") > -1) { response.append(HTTPXMLHelper.XML_HEADER); response.append(CRLF); response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER); response.append(CRLF); response.append(HTTPXMLHelper.SORTCAPS_RESPONSE); response.append(CRLF); response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER); response.append(CRLF); } else if (soapaction != null && soapaction.indexOf("ContentDirectory:1#GetSearchCapabilities") > -1) { response.append(HTTPXMLHelper.XML_HEADER); response.append(CRLF); response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER); response.append(CRLF); response.append(HTTPXMLHelper.SEARCHCAPS_RESPONSE); response.append(CRLF); response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER); response.append(CRLF); } else if (soapaction != null && (soapaction.contains("ContentDirectory:1#Browse") || soapaction.contains("ContentDirectory:1#Search"))) { objectID = getEnclosingValue(content, "<ObjectID>", "</ObjectID>"); String containerID = null; if ((objectID == null || objectID.length() == 0)) { containerID = getEnclosingValue(content, "<ContainerID>", "</ContainerID>"); if (containerID == null || !containerID.contains("$")) { objectID = "0"; } else { objectID = containerID; containerID = null; } } Object sI = getEnclosingValue(content, "<StartingIndex>", "</StartingIndex>"); Object rC = getEnclosingValue(content, "<RequestedCount>", "</RequestedCount>"); browseFlag = getEnclosingValue(content, "<BrowseFlag>", "</BrowseFlag>"); if (sI != null) { startingIndex = Integer.parseInt(sI.toString()); } if (rC != null) { requestCount = Integer.parseInt(rC.toString()); } response.append(HTTPXMLHelper.XML_HEADER); response.append(CRLF); response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER); response.append(CRLF); if (soapaction != null && soapaction.contains("ContentDirectory:1#Search")) { response.append(HTTPXMLHelper.SEARCHRESPONSE_HEADER); } else { response.append(HTTPXMLHelper.BROWSERESPONSE_HEADER); } response.append(CRLF); response.append(HTTPXMLHelper.RESULT_HEADER); response.append(HTTPXMLHelper.DIDL_HEADER); if (soapaction != null && soapaction.contains("ContentDirectory:1#Search")) { browseFlag = "BrowseDirectChildren"; } // Xbox virtual containers ... d'oh! String searchCriteria = null; if (xbox && configuration.getUseCache() && PMS.get().getLibrary() != null && containerID != null) { if (containerID.equals("7") && PMS.get().getLibrary().getAlbumFolder() != null) { objectID = PMS.get().getLibrary().getAlbumFolder().getResourceId(); } else if (containerID.equals("6") && PMS.get().getLibrary().getArtistFolder() != null) { objectID = PMS.get().getLibrary().getArtistFolder().getResourceId(); } else if (containerID.equals("5") && PMS.get().getLibrary().getGenreFolder() != null) { objectID = PMS.get().getLibrary().getGenreFolder().getResourceId(); } else if (containerID.equals("F") && PMS.get().getLibrary().getPlaylistFolder() != null) { objectID = PMS.get().getLibrary().getPlaylistFolder().getResourceId(); } else if (containerID.equals("4") && PMS.get().getLibrary().getAllFolder() != null) { objectID = PMS.get().getLibrary().getAllFolder().getResourceId(); } else if (containerID.equals("1")) { String artist = getEnclosingValue(content, "upnp:artist = &quot;", "&quot;)"); if (artist != null) { objectID = PMS.get().getLibrary().getArtistFolder().getResourceId(); searchCriteria = artist; } } } else if (soapaction.contains("ContentDirectory:1#Search")) { searchCriteria = getEnclosingValue(content, "<SearchCriteria>", "</SearchCriteria>"); } List<DLNAResource> files = PMS.get().getRootFolder(mediaRenderer).getDLNAResources( objectID, browseFlag != null && browseFlag.equals("BrowseDirectChildren"), startingIndex, requestCount, mediaRenderer, searchCriteria ); if (searchCriteria != null && files != null) { searchCriteria = searchCriteria.toLowerCase(); for (int i = files.size() - 1; i >= 0; i--) { DLNAResource res = files.get(i); if (res.isSearched()) { continue; } boolean keep = res.getName().toLowerCase().indexOf(searchCriteria) != -1; final DLNAMediaInfo media = res.getMedia(); if (media!=null) { for (int j = 0;j < media.getAudioTracksList().size(); j++) { DLNAMediaAudio audio = media.getAudioTracksList().get(j); keep |= audio.getAlbum().toLowerCase().indexOf(searchCriteria) != -1; keep |= audio.getArtist().toLowerCase().indexOf(searchCriteria) != -1; keep |= audio.getSongname().toLowerCase().indexOf(searchCriteria) != -1; } } if (!keep) { // dump it files.remove(i); } } if (xbox) { if (files.size() > 0) { files = files.get(0).getChildren(); } } } int minus = 0; if (files != null) { for (DLNAResource uf : files) { if (xbox && containerID != null) { uf.setFakeParentId(containerID); } if (uf.isCompatible(mediaRenderer) && (uf.getPlayer() == null || uf.getPlayer().isPlayerCompatible(mediaRenderer))) { response.append(uf.getDidlString(mediaRenderer)); } else { minus++; } } } response.append(HTTPXMLHelper.DIDL_FOOTER); response.append(HTTPXMLHelper.RESULT_FOOTER); response.append(CRLF); int filessize = 0; if (files != null) { filessize = files.size(); } response.append("<NumberReturned>").append(filessize - minus).append("</NumberReturned>"); response.append(CRLF); DLNAResource parentFolder = null; if (files != null && filessize > 0) { parentFolder = files.get(0).getParent(); } if (browseFlag != null && browseFlag.equals("BrowseDirectChildren") && mediaRenderer.isMediaParserV2() && mediaRenderer.isDLNATreeHack()) { // with the new parser, files are parsed and analyzed *before* // creating the DLNA tree, every 10 items (the ps3 asks 10 by 10), // so we do not know exactly the total number of items in the DLNA folder to send // (regular files, plus the #transcode folder, maybe the #imdb one, also files can be // invalidated and hidden if format is broken or encrypted, etc.). // let's send a fake total size to force the renderer to ask following items int totalCount = startingIndex + requestCount + 1; // returns 11 when 10 asked // If no more elements, send the startingIndex if (filessize - minus <= 0) { totalCount = startingIndex; } response.append("<TotalMatches>").append(totalCount).append("</TotalMatches>"); } else if (browseFlag != null && browseFlag.equals("BrowseDirectChildren")) { response.append("<TotalMatches>").append(((parentFolder != null) ? parentFolder.childrenNumber() : filessize) - minus).append("</TotalMatches>"); } else { // From upnp spec: If BrowseMetadata is specified in the BrowseFlags then TotalMatches = 1 response.append("<TotalMatches>1</TotalMatches>"); } response.append(CRLF); response.append("<UpdateID>"); if (parentFolder != null) { response.append(parentFolder.getUpdateId()); } else { response.append("1"); } response.append("</UpdateID>"); response.append(CRLF); if (soapaction != null && soapaction.contains("ContentDirectory:1#Search")) { response.append(HTTPXMLHelper.SEARCHRESPONSE_FOOTER); } else { response.append(HTTPXMLHelper.BROWSERESPONSE_FOOTER); } response.append(CRLF); response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER); response.append(CRLF); LOGGER.trace(response.toString()); } } else if (method.equals("SUBSCRIBE")) { output.setHeader("SID", PMS.get().usn()); output.setHeader("TIMEOUT", "Second-1800"); if (soapaction != null) { String cb = soapaction.replace("<", "").replace(">", ""); try { URL soapActionUrl = new URL(cb); String addr = soapActionUrl.getHost(); int port = soapActionUrl.getPort(); Socket sock = new Socket(addr,port); try (OutputStream out = sock.getOutputStream()) { out.write(("NOTIFY /" + argument + " HTTP/1.1").getBytes()); out.write(CRLF.getBytes()); out.write(("SID: " + PMS.get().usn()).getBytes()); out.write(CRLF.getBytes()); out.write(("SEQ: " + 0).getBytes()); out.write(CRLF.getBytes()); out.write(("NT: upnp:event").getBytes()); out.write(CRLF.getBytes()); out.write(("NTS: upnp:propchange").getBytes()); out.write(CRLF.getBytes()); out.write(("HOST: " + addr + ":" + port).getBytes()); out.write(CRLF.getBytes()); out.flush(); sock.close(); } } catch (MalformedURLException ex) { LOGGER.debug("Cannot parse address and port from soap action \"" + soapaction + "\"", ex); } } else { LOGGER.debug("Expected soap action in request"); } if (argument.contains("connection_manager")) { response.append(HTTPXMLHelper.eventHeader("urn:schemas-upnp-org:service:ConnectionManager:1")); response.append(HTTPXMLHelper.eventProp("SinkProtocolInfo")); response.append(HTTPXMLHelper.eventProp("SourceProtocolInfo")); response.append(HTTPXMLHelper.eventProp("CurrentConnectionIDs")); response.append(HTTPXMLHelper.EVENT_FOOTER); } else if (argument.contains("content_directory")) { response.append(HTTPXMLHelper.eventHeader("urn:schemas-upnp-org:service:ContentDirectory:1")); response.append(HTTPXMLHelper.eventProp("TransferIDs")); response.append(HTTPXMLHelper.eventProp("ContainerUpdateIDs")); response.append(HTTPXMLHelper.eventProp("SystemUpdateID", "" + DLNAResource.getSystemUpdateId())); response.append(HTTPXMLHelper.EVENT_FOOTER); } } else if (method.equals("NOTIFY")) { output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/xml"); output.setHeader("NT", "upnp:event"); output.setHeader("NTS", "upnp:propchange"); output.setHeader("SID", PMS.get().usn()); output.setHeader("SEQ", "0"); response.append("<e:propertyset xmlns:e=\"urn:schemas-upnp-org:event-1-0\">"); response.append("<e:property>"); response.append("<TransferIDs></TransferIDs>"); response.append("</e:property>"); response.append("<e:property>"); response.append("<ContainerUpdateIDs></ContainerUpdateIDs>"); response.append("</e:property>"); response.append("<e:property>"); response.append("<SystemUpdateID>").append(DLNAResource.getSystemUpdateId()).append("</SystemUpdateID>"); response.append("</e:property>"); response.append("</e:propertyset>"); } output.setHeader("Server", PMS.get().getServerName()); if (response.length() > 0) { // A response message was constructed; convert it to data ready to be sent. byte responseData[] = response.toString().getBytes("UTF-8"); output.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "" + responseData.length); // HEAD requests only require headers to be set, no need to set contents. if (!method.equals("HEAD")) { // Not a HEAD request, so set the contents of the response. ChannelBuffer buf = ChannelBuffers.copiedBuffer(responseData); output.setContent(buf); } // Send the response to the client. future = e.getChannel().write(output); if (close) { // Close the channel after the response is sent. future.addListener(ChannelFutureListener.CLOSE); } } else if (inputStream != null) { // There is an input stream to send as a response. if (CLoverride > -2) { // Content-Length override has been set, send or omit as appropriate if (CLoverride > -1 && CLoverride != DLNAMediaInfo.TRANS_SIZE) { // Since PS3 firmware 2.50, it is wiser not to send an arbitrary Content-Length, // as the PS3 will display a network error and request the last seconds of the // transcoded video. Better to send no Content-Length at all. output.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "" + CLoverride); } } else { int cl = inputStream.available(); LOGGER.trace("Available Content-Length: " + cl); output.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "" + cl); } if (range.isStartOffsetAvailable() && dlna != null) { // Add timeseek information headers. String timeseekValue = StringUtil.convertTimeToString(range.getStartOrZero(), StringUtil.DURATION_TIME_FORMAT); String timetotalValue = dlna.getMedia().getDurationString(); String timeEndValue = range.isEndLimitAvailable() ? StringUtil.convertTimeToString(range.getEnd(), StringUtil.DURATION_TIME_FORMAT) : timetotalValue; output.setHeader("TimeSeekRange.dlna.org", "npt=" + timeseekValue + "-" + timeEndValue + "/" + timetotalValue); output.setHeader("X-Seek-Range", "npt=" + timeseekValue + "-" + timeEndValue + "/" + timetotalValue); } // Send the response headers to the client. future = e.getChannel().write(output); if (lowRange != DLNAMediaInfo.ENDFILE_POS && !method.equals("HEAD")) { // Send the response body to the client in chunks. ChannelFuture chunkWriteFuture = e.getChannel().write(new ChunkedStream(inputStream, BUFFER_SIZE)); // Add a listener to clean up after sending the entire response body. chunkWriteFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) { try { PMS.get().getRegistry().reenableGoToSleep(); inputStream.close(); } catch (IOException e) { LOGGER.debug("Caught exception", e); } // Always close the channel after the response is sent because of // a freeze at the end of video when the channel is not closed. future.getChannel().close(); startStopListenerDelegate.stop(); } }); } else { // HEAD method is being used, so simply clean up after the response was sent. try { PMS.get().getRegistry().reenableGoToSleep(); inputStream.close(); } catch (IOException ioe) { LOGGER.debug("Caught exception", ioe); } if (close) { // Close the channel after the response is sent future.addListener(ChannelFutureListener.CLOSE); } startStopListenerDelegate.stop(); } } else { // No response data and no input stream. Seems we are merely serving up headers. if (lowRange > 0 && highRange > 0) { // FIXME: There is no content, so why set a length? output.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "" + (highRange - lowRange + 1)); } else { output.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "0"); } // Send the response headers to the client. future = e.getChannel().write(output); if (close) { // Close the channel after the response is sent. future.addListener(ChannelFutureListener.CLOSE); } } // Log trace information Iterator<String> it = output.getHeaderNames().iterator(); while (it.hasNext()) { String headerName = it.next(); LOGGER.trace("Sent to socket: " + headerName + ": " + output.getHeader(headerName)); } return future; }
diff --git a/src/org/daxplore/presenter/server/servlets/AdminPanelServlet.java b/src/org/daxplore/presenter/server/servlets/AdminPanelServlet.java index 8ff895d..8dac209 100644 --- a/src/org/daxplore/presenter/server/servlets/AdminPanelServlet.java +++ b/src/org/daxplore/presenter/server/servlets/AdminPanelServlet.java @@ -1,77 +1,76 @@ /* * This file is part of Daxplore Presenter. * * Daxplore Presenter is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2.1 of the License, or * (at your option) any later version. * * Daxplore Presenter is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Daxplore Presenter. If not, see <http://www.gnu.org/licenses/>. */ package org.daxplore.presenter.server.servlets; import java.io.IOException; import java.io.Writer; import java.text.MessageFormat; import java.util.Locale; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; import org.daxplore.presenter.server.throwable.InternalServerException; @SuppressWarnings("serial") public class AdminPanelServlet extends HttpServlet { protected static Logger logger = Logger.getLogger(AdminPanelServlet.class.getName()); protected static String adminHtmlTemplate = null; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) { try { Locale locale = new Locale("en"); String pageTitle = "Daxplore Admin"; if (adminHtmlTemplate == null) { try { adminHtmlTemplate = IOUtils.toString(getServletContext().getResourceAsStream("/templates/admin.html")); } catch (IOException e) { throw new InternalServerException("Failed to load the html admin template", e); } } String baseurl = request.getRequestURL().toString(); - baseurl = baseurl.substring(0, baseurl.lastIndexOf("/")); baseurl = baseurl.substring(0, baseurl.lastIndexOf("/")+1); String[] arguments = { locale.toLanguageTag(), // {0} pageTitle, // {1} baseurl // {2} }; try { Writer writer = response.getWriter(); writer.write(MessageFormat.format(adminHtmlTemplate, (Object[])arguments)); writer.close(); } catch (IOException e) { throw new InternalServerException(e); } } catch (InternalServerException e) { logger.log(Level.SEVERE, e.getMessage(), e); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } catch (Exception e) { logger.log(Level.SEVERE, "Unexpected exception: " + e.getMessage(), e); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } }
true
true
protected void doGet(HttpServletRequest request, HttpServletResponse response) { try { Locale locale = new Locale("en"); String pageTitle = "Daxplore Admin"; if (adminHtmlTemplate == null) { try { adminHtmlTemplate = IOUtils.toString(getServletContext().getResourceAsStream("/templates/admin.html")); } catch (IOException e) { throw new InternalServerException("Failed to load the html admin template", e); } } String baseurl = request.getRequestURL().toString(); baseurl = baseurl.substring(0, baseurl.lastIndexOf("/")); baseurl = baseurl.substring(0, baseurl.lastIndexOf("/")+1); String[] arguments = { locale.toLanguageTag(), // {0} pageTitle, // {1} baseurl // {2} }; try { Writer writer = response.getWriter(); writer.write(MessageFormat.format(adminHtmlTemplate, (Object[])arguments)); writer.close(); } catch (IOException e) { throw new InternalServerException(e); } } catch (InternalServerException e) { logger.log(Level.SEVERE, e.getMessage(), e); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } catch (Exception e) { logger.log(Level.SEVERE, "Unexpected exception: " + e.getMessage(), e); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } }
protected void doGet(HttpServletRequest request, HttpServletResponse response) { try { Locale locale = new Locale("en"); String pageTitle = "Daxplore Admin"; if (adminHtmlTemplate == null) { try { adminHtmlTemplate = IOUtils.toString(getServletContext().getResourceAsStream("/templates/admin.html")); } catch (IOException e) { throw new InternalServerException("Failed to load the html admin template", e); } } String baseurl = request.getRequestURL().toString(); baseurl = baseurl.substring(0, baseurl.lastIndexOf("/")+1); String[] arguments = { locale.toLanguageTag(), // {0} pageTitle, // {1} baseurl // {2} }; try { Writer writer = response.getWriter(); writer.write(MessageFormat.format(adminHtmlTemplate, (Object[])arguments)); writer.close(); } catch (IOException e) { throw new InternalServerException(e); } } catch (InternalServerException e) { logger.log(Level.SEVERE, e.getMessage(), e); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } catch (Exception e) { logger.log(Level.SEVERE, "Unexpected exception: " + e.getMessage(), e); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } }
diff --git a/ToureNPlaner/src/de/uni/stuttgart/informatik/ToureNPlaner/UI/Adapters/ResultNodeAdapter.java b/ToureNPlaner/src/de/uni/stuttgart/informatik/ToureNPlaner/UI/Adapters/ResultNodeAdapter.java index 112d7f3..cb53744 100644 --- a/ToureNPlaner/src/de/uni/stuttgart/informatik/ToureNPlaner/UI/Adapters/ResultNodeAdapter.java +++ b/ToureNPlaner/src/de/uni/stuttgart/informatik/ToureNPlaner/UI/Adapters/ResultNodeAdapter.java @@ -1,39 +1,39 @@ package de.uni.stuttgart.informatik.ToureNPlaner.UI.Adapters; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import de.uni.stuttgart.informatik.ToureNPlaner.Data.ResultNode; import de.uni.stuttgart.informatik.ToureNPlaner.R; import java.util.List; import java.util.Map; public class ResultNodeAdapter extends ArrayAdapter<ResultNode> { public ResultNodeAdapter(Context context, List<ResultNode> objects) { super(context, R.layout.list_item, objects); } @Override public View getView(int position, View convertView, ViewGroup parent) { TextView item = convertView == null ? (TextView) LayoutInflater.from(getContext()).inflate(R.layout.list_item, null) : (TextView) convertView; ResultNode node = getItem(position); String txt = ""; for (Map.Entry<String, String> e : node.getMisc().entrySet()) { txt += e.getKey() + ": " + e.getValue() + "\n"; } // cut of last \n - if (!txt.isEmpty()) + if (txt.length() > 0) txt = txt.substring(0, txt.length() - 1); item.setText(txt); return item; } }
true
true
public View getView(int position, View convertView, ViewGroup parent) { TextView item = convertView == null ? (TextView) LayoutInflater.from(getContext()).inflate(R.layout.list_item, null) : (TextView) convertView; ResultNode node = getItem(position); String txt = ""; for (Map.Entry<String, String> e : node.getMisc().entrySet()) { txt += e.getKey() + ": " + e.getValue() + "\n"; } // cut of last \n if (!txt.isEmpty()) txt = txt.substring(0, txt.length() - 1); item.setText(txt); return item; }
public View getView(int position, View convertView, ViewGroup parent) { TextView item = convertView == null ? (TextView) LayoutInflater.from(getContext()).inflate(R.layout.list_item, null) : (TextView) convertView; ResultNode node = getItem(position); String txt = ""; for (Map.Entry<String, String> e : node.getMisc().entrySet()) { txt += e.getKey() + ": " + e.getValue() + "\n"; } // cut of last \n if (txt.length() > 0) txt = txt.substring(0, txt.length() - 1); item.setText(txt); return item; }
diff --git a/src/main/java/ca/mcpnet/RailDriver/RailDriverTask.java b/src/main/java/ca/mcpnet/RailDriver/RailDriverTask.java index 3da80f3..cf27f1a 100644 --- a/src/main/java/ca/mcpnet/RailDriver/RailDriverTask.java +++ b/src/main/java/ca/mcpnet/RailDriver/RailDriverTask.java @@ -1,529 +1,533 @@ package ca.mcpnet.RailDriver; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.bukkit.Effect; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.block.Chest; import org.bukkit.block.Furnace; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.material.Lever; import org.bukkit.material.MaterialData; import org.bukkit.material.Torch; import ca.mcpnet.RailDriver.RailDriver.Facing; public class RailDriverTask implements Runnable { private RailDriver plugin; private int x,y,z; private BlockFace direction; private World world; private int taskid; int iteration; boolean nexttorch; ArrayList<ItemStack> collecteditems; Iterator<ItemStack> itemitr; boolean whichdispenser; int smokedir; RailDriverTask(RailDriver instance, Block block) { plugin = instance; x = block.getX(); y = block.getY(); z = block.getZ(); Lever lever = new Lever(block.getType(),block.getData()); direction = lever.getAttachedFace(); world = block.getWorld(); taskid = -1; iteration = 0; nexttorch = false; collecteditems = new ArrayList<ItemStack>(); whichdispenser = false; if (direction == BlockFace.EAST) { smokedir = 7; } else if (direction == BlockFace.WEST) { smokedir = 1; } else if (direction == BlockFace.SOUTH) { smokedir = 3; } else if (direction == BlockFace.NORTH) { smokedir = 5; } else { smokedir = 4; } } Block getRelativeBlock(int i, int j, int k) { if (direction == BlockFace.NORTH) { return world.getBlockAt(x-i,y-1+k,z+1-j); } else if (direction == BlockFace.EAST) { return world.getBlockAt(x-1+j,y-1+k,z-i); } else if (direction == BlockFace.WEST) { return world.getBlockAt(x+1-j,y-1+k,z+i); } else if (direction == BlockFace.SOUTH) { return world.getBlockAt(x+i,y-1+k,z-1+j); } else { return null; } } void smokePuff() { world.playEffect(getRelativeBlock(1,0,1).getLocation(), Effect.SMOKE, smokedir); world.playEffect(getRelativeBlock(1,2,1).getLocation(), Effect.SMOKE, smokedir); } void setDrillSwitch(boolean on) { Block block = getRelativeBlock(2,1,2); Lever leverblock = new Lever(block.getType(),block.getData()); leverblock.setPowered(on); block.setData(leverblock.getData()); } void setMainSwitch(boolean on) { Block block = getRelativeBlock(0,1,1); Lever leverblock = new Lever(block.getType(),block.getData()); leverblock.setPowered(on); block.setData(leverblock.getData()); } public void run() { if (taskid == -1) { setMainSwitch(false); setDrillSwitch(false); world.playEffect(new Location(world,x,y,z), Effect.EXTINGUISH,0); smokePuff(); plugin.taskset.remove(this); } iteration++; if (iteration == 1) { setDrillSwitch(false); if (plugin.getConfig().getBoolean("requires_fuel")) { if (!burnCoal()) { localbroadcast("Raildriver has insufficient fuel!"); plugin.taskset.remove(taskid); deactivate(); } } } if (iteration == 6) { Block leverblock = world.getBlockAt(x, y, z); if (!plugin.isRailDriver(leverblock)) { localbroadcast("Raildriver malfunction during drill phase!"); plugin.taskset.remove(taskid); deactivate(); return; } // Remove materials in front of bit if (!excavate()) { localbroadcast("Raildriver encountered obstruction!"); deactivate(); return; } setDrillSwitch(true); smokePuff(); } if (iteration == 8) { ejectItems(); } if (iteration == 12) { setDrillSwitch(false); } if (iteration == 18) { setDrillSwitch(true); smokePuff(); } if (iteration == 20) { ejectItems(); } if (iteration == 24) { setDrillSwitch(false); } if (iteration == 30) { setDrillSwitch(true); smokePuff(); } if (iteration == 32) { ejectItems(); } if (iteration == 36) { setDrillSwitch(false); } if (iteration == 40) { world.playEffect(getRelativeBlock(0,1,-1).getLocation(), Effect.STEP_SOUND, Material.LAVA.getId()); // Do track laying stuff } if (iteration == 42) { world.playEffect(getRelativeBlock(0,0,-1).getLocation(), Effect.STEP_SOUND, Material.LAVA.getId()); world.playEffect(getRelativeBlock(0,2,-1).getLocation(), Effect.STEP_SOUND, Material.LAVA.getId()); // Do track laying stuff } if (iteration == 44) { world.playEffect(getRelativeBlock(0,-1,1).getLocation(), Effect.STEP_SOUND, Material.LAVA.getId()); world.playEffect(getRelativeBlock(0,3,1).getLocation(), Effect.STEP_SOUND, Material.LAVA.getId()); // Do track laying stuff } if (iteration == 46) { world.playEffect(getRelativeBlock(1,-1,2).getLocation(), Effect.STEP_SOUND, Material.LAVA.getId()); world.playEffect(getRelativeBlock(1,3,2).getLocation(), Effect.STEP_SOUND, Material.LAVA.getId()); // Do track laying stuff } if (iteration == 48) { // Check that it's still a raildriver Block leverblock = world.getBlockAt(x, y, z); if (!plugin.isRailDriver(leverblock)) { localbroadcast("Raildriver malfunction during advance phase!"); plugin.taskset.remove(taskid); deactivate(); return; } if (!advance()) { deactivate(); return; } // RailDriver.log.info("RailDriver "+taskid+" in chunk "+world.getChunkAt(getRelativeBlock(0,1,1))); world.createExplosion(getRelativeBlock(2,1,1).getLocation(), 0); iteration = 0; } // world.playEffect(block.getLocation(), Effect.STEP_SOUND, block.getTypeId()); /* Block block = this.getRelativeBlock(1, 0, i); i = (i + 1) % 3; RailDriver.log.info(block.getType().name()); */ // world.createExplosion(x, y, z, 0); // Light the fires } private void localbroadcast(String msg) { Block block = getRelativeBlock(0,0,0); Location location = block.getLocation(); List<Player> players = block.getWorld().getPlayers(); Iterator<Player> pitr = players.iterator(); while (pitr.hasNext()) { Player player = pitr.next(); if (location.distanceSquared(player.getLocation()) < 36) { player.sendMessage(msg); } } } private boolean burnCoal() { Block leftblock = getRelativeBlock(1,0,0); Furnace leftfurnace = (Furnace) leftblock.getState(); Inventory leftinventory = leftfurnace.getInventory(); Block rightblock = getRelativeBlock(1,2,0); Furnace rightfurnace = (Furnace) rightblock.getState(); Inventory rightinventory = rightfurnace.getInventory(); if (!leftinventory.contains(Material.COAL) || (!rightinventory.contains(Material.COAL))) { return false; } leftinventory.removeItem(new ItemStack(Material.COAL.getId(),1,(short)0,(byte)1),new ItemStack(Material.COAL,1)); rightinventory.removeItem(new ItemStack(Material.COAL.getId(),1,(short)0,(byte)1),new ItemStack(Material.COAL,1)); leftfurnace.update(); rightfurnace.update(); return true; } private boolean advance() { // Check to make sure ground under is solid for (int lx = 0; lx < 3; lx++) { for (int lz = 0; lz < RailDriver.raildriverblocklist[lx][0].length; lz++) { Block block = getRelativeBlock(lz,lx,-1); if (block.isEmpty() || block.isLiquid()) { localbroadcast("Raildriver encountered broken ground!"); return false; } } } // Check to make sure behind has no liquid for (int lx = 0; lx < 3; lx++) { Block block = getRelativeBlock(0,lx,0); if (block.isLiquid()) { localbroadcast("Raildriver encountered unstable environment!"); return false; } } // Check to make sure raildriver has enough materials int period = 8; int distance; if (direction == BlockFace.NORTH || direction == BlockFace.SOUTH) { distance = x; } else { distance = z; } if (plugin.getConfig().getBoolean("requires_fuel")) { Chest chest = (Chest) getRelativeBlock(1,1,2).getState(); Inventory inventory = chest.getInventory(); boolean torchcolumns = distance % period == 0; if (torchcolumns) { if (!inventory.contains(Material.POWERED_RAIL,1)) { // If we don't have powered rails, we try and convert other materials if (!inventory.contains(Material.GOLD_INGOT,4) || !inventory.contains(Material.STICK,1) || !inventory.contains(Material.REDSTONE,1)) { localbroadcast("Raildriver has insufficient building materials for power rails!"); return false; } inventory.removeItem( new ItemStack(Material.GOLD_INGOT,4), new ItemStack(Material.STICK,1), new ItemStack(Material.REDSTONE,1)); inventory.addItem(new ItemStack(Material.POWERED_RAIL,14)); } if (!inventory.contains(Material.POWERED_RAIL, 1) || !inventory.contains(Material.COBBLESTONE, 9) || !inventory.contains(Material.STICK, 2) || !inventory.contains(Material.REDSTONE, 1) || !inventory.contains(Material.COAL,1)) { localbroadcast("Raildriver has insufficient building materials for power columns!"); return false; } inventory.removeItem( new ItemStack(Material.POWERED_RAIL,1), new ItemStack(Material.COBBLESTONE,9), new ItemStack(Material.STICK,2), new ItemStack(Material.REDSTONE,1), new ItemStack(Material.COAL,1)); } else { if (!inventory.contains(Material.RAILS, 1)) { // If we don't have rails, we try and convert other materials if (!inventory.contains(Material.IRON_INGOT,4) || !inventory.contains(Material.STICK,1)) { localbroadcast("Raildriver has insufficient building materials for rails!"); return false; } inventory.removeItem( new ItemStack(Material.IRON_INGOT,4), new ItemStack(Material.STICK,1)); inventory.addItem(new ItemStack(Material.RAILS,14)); } // Now try to lay the track if (!inventory.contains(Material.RAILS, 1) || !inventory.contains(Material.COBBLESTONE, 3)) { localbroadcast("Raildriver has insufficient building materials for rails!"); return false; } inventory.removeItem( new ItemStack(Material.RAILS,1), new ItemStack(Material.COBBLESTONE,3)); } } for (int lx = 0; lx < 3; lx++) { for (int ly = 0; ly < 3; ly++) { for (int lz = RailDriver.raildriverblocklist[lx][ly].length; lz > 0; lz--) { Block target = getRelativeBlock(lz,lx,ly); Block source = getRelativeBlock(lz-1,lx,ly); // RailDriver.log.info(source.getType().name()); if (source.getType() == Material.CHEST) { // Get the old chest info Chest sourcechest = (Chest) source.getState(); Inventory sourceinventory = sourcechest.getInventory(); ItemStack[] sourceitems = sourceinventory.getContents(); sourceinventory.clear(); MaterialData sourcedata = sourcechest.getData(); // Blow the old chest away source.setType(Material.AIR); target.setType(Material.CHEST); Chest targetchest = (Chest) target.getState(); targetchest.setData(sourcedata); Inventory targetinventory = targetchest.getInventory(); targetinventory.setContents(sourceitems); targetchest.update(); } else if (source.getType() == Material.BURNING_FURNACE) { Furnace sourcefurnace = (Furnace) source.getState(); Inventory sourceinventory = sourcefurnace.getInventory(); ItemStack[] sourceitems = sourceinventory.getContents(); sourceinventory.clear(); MaterialData sourcedata = sourcefurnace.getData(); // Blow the old chest away source.setType(Material.AIR); target.setType(Material.BURNING_FURNACE); Furnace targetfurnace = (Furnace) target.getState(); targetfurnace.setData(sourcedata); Inventory targetinventory = targetfurnace.getInventory(); targetinventory.setContents(sourceitems); targetfurnace.update(); } else if (source.getType() == Material.DISPENSER || source.getType() == Material.FURNACE || source.getType() == Material.LEVER) { byte sourcedata = source.getData(); Material sourcematerial = source.getType(); source.setType(Material.AIR); target.setType(sourcematerial); target.setData(sourcedata); } else if (source.getType() == Material.TORCH || source.getType() == Material.REDSTONE_TORCH_ON || source.getType() == Material.REDSTONE_TORCH_OFF) { // Prevent free torch dropping side effect target.setType(Material.AIR); } else { target.setType(source.getType()); target.setData(source.getData()); } } } } // Set the floor made of stone for (int lx = 0; lx < 3; lx++) getRelativeBlock(1,lx,-1).setTypeId(98); for (int lx = 0; lx < 3; lx++) { for (int ly = 0; ly < 3; ly++) { if (!(lx == 1 && ly == 1)) { getRelativeBlock(1,lx,ly).setType(Material.AIR); } } } if (distance % period == 0) { for (int ly = 0; ly < 3; ly++) { getRelativeBlock(1,-1,ly-1).setTypeId(98); getRelativeBlock(1,3,ly-1).setTypeId(98); } - Block left = getRelativeBlock(1,0,1); + Block left; if (nexttorch) { + left = getRelativeBlock(1,0,0); left.setType(Material.REDSTONE_TORCH_ON); } else { + left = getRelativeBlock(1,0,1); left.setType(Material.TORCH); } Torch lefttorch = new Torch(left.getType(),left.getData()); lefttorch.setFacingDirection(Facing.RIGHT.translate(direction)); left.setData(lefttorch.getData()); getRelativeBlock(1,1,0).setType(Material.POWERED_RAIL); - Block right = getRelativeBlock(1,2,1); + Block right; if (nexttorch) { + right = getRelativeBlock(1,2,1); right.setType(Material.TORCH); } else { + right = getRelativeBlock(1,2,0); right.setType(Material.REDSTONE_TORCH_ON); } Torch righttorch = new Torch(right.getType(),right.getData()); righttorch.setFacingDirection(Facing.LEFT.translate(direction)); right.setData(righttorch.getData()); nexttorch = !nexttorch; } else { // Regular rail getRelativeBlock(1,1,0).setType(Material.RAILS); } // plugin.getServer().getScheduler().cancelTask(taskid); // plugin.taskset.remove(this); Location newloc = getRelativeBlock(1,1,1).getLocation(); x = newloc.getBlockX(); y = newloc.getBlockY(); z = newloc.getBlockZ(); return true; } private void ejectItems() { if (!collecteditems.isEmpty()) { world.createExplosion(getRelativeBlock(6,1,1).getLocation(), 0); for (int i = 0;i < 3 && itemitr.hasNext(); i++) { ItemStack curstack = itemitr.next(); itemitr.remove(); Location loc; if (whichdispenser) { loc = getRelativeBlock(0,0,1).getLocation(); whichdispenser = false; } else { loc = getRelativeBlock(0,2,1).getLocation(); whichdispenser = true; } world.dropItem(loc, curstack); world.playEffect(loc, Effect.STEP_SOUND, curstack.getTypeId()); } } } private boolean excavate() { for (int lx = 0; lx < 3; lx++) { for (int ly = 0; ly < 3; ly++) { Block block = getRelativeBlock((RailDriver.raildriverblocklist[lx][ly]).length, lx, ly); if (block.isLiquid()) { return false; } if (!block.isEmpty()) { collecteditems.add(new ItemStack(block.getType(),1)); block.setType(Material.AIR); } } } itemitr = collecteditems.iterator(); return true; } public boolean matchBlock(Block block) { if (block.getLocation().getBlockX() == x && block.getLocation().getBlockY() == y && block.getLocation().getBlockZ() == z) { return true; } return false; } public void setBlockTypeSaveData(Block block, Material type) { byte data = block.getData(); block.setType(type); block.setData(data); } public void setFurnaceBurning(Block block, boolean on) { if (block.getType() != Material.BURNING_FURNACE && block.getType() != Material.FURNACE) { return; } Furnace furnace = (Furnace) block.getState(); Inventory inventory = furnace.getInventory(); ItemStack[] contents = inventory.getContents(); inventory.clear(); MaterialData data = furnace.getData(); if (on) { block.setType(Material.BURNING_FURNACE); } else { block.setType(Material.FURNACE); } furnace = (Furnace) block.getState(); furnace.setData(data); inventory = furnace.getInventory(); inventory.setContents(contents); furnace.update(); } public void activate() { if (taskid != -1) { RailDriver.log("Activation requested on already active raildriver "+taskid); return; } taskid = plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, this, 10L, 2L); RailDriver.log("Activated "+direction.name()+ "BOUND raildriver "+taskid); // Light the fires setFurnaceBurning(getRelativeBlock(1,0,0),true); setFurnaceBurning(getRelativeBlock(1,2,0),true); } public void deactivate() { if (taskid == -1) { RailDriver.log("Deactivation requested for already inactive raildriver!"); return; } plugin.getServer().getScheduler().cancelTask(taskid); RailDriver.log("Deactivated raildriver "+taskid); // Shut off furnaces setFurnaceBurning(getRelativeBlock(1,0,0),false); setFurnaceBurning(getRelativeBlock(1,2,0),false); // Shutdown hiss world.playEffect(new Location(world,x,y,z), Effect.EXTINGUISH,0); taskid = -1; plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, this, 10L); } }
false
true
private boolean advance() { // Check to make sure ground under is solid for (int lx = 0; lx < 3; lx++) { for (int lz = 0; lz < RailDriver.raildriverblocklist[lx][0].length; lz++) { Block block = getRelativeBlock(lz,lx,-1); if (block.isEmpty() || block.isLiquid()) { localbroadcast("Raildriver encountered broken ground!"); return false; } } } // Check to make sure behind has no liquid for (int lx = 0; lx < 3; lx++) { Block block = getRelativeBlock(0,lx,0); if (block.isLiquid()) { localbroadcast("Raildriver encountered unstable environment!"); return false; } } // Check to make sure raildriver has enough materials int period = 8; int distance; if (direction == BlockFace.NORTH || direction == BlockFace.SOUTH) { distance = x; } else { distance = z; } if (plugin.getConfig().getBoolean("requires_fuel")) { Chest chest = (Chest) getRelativeBlock(1,1,2).getState(); Inventory inventory = chest.getInventory(); boolean torchcolumns = distance % period == 0; if (torchcolumns) { if (!inventory.contains(Material.POWERED_RAIL,1)) { // If we don't have powered rails, we try and convert other materials if (!inventory.contains(Material.GOLD_INGOT,4) || !inventory.contains(Material.STICK,1) || !inventory.contains(Material.REDSTONE,1)) { localbroadcast("Raildriver has insufficient building materials for power rails!"); return false; } inventory.removeItem( new ItemStack(Material.GOLD_INGOT,4), new ItemStack(Material.STICK,1), new ItemStack(Material.REDSTONE,1)); inventory.addItem(new ItemStack(Material.POWERED_RAIL,14)); } if (!inventory.contains(Material.POWERED_RAIL, 1) || !inventory.contains(Material.COBBLESTONE, 9) || !inventory.contains(Material.STICK, 2) || !inventory.contains(Material.REDSTONE, 1) || !inventory.contains(Material.COAL,1)) { localbroadcast("Raildriver has insufficient building materials for power columns!"); return false; } inventory.removeItem( new ItemStack(Material.POWERED_RAIL,1), new ItemStack(Material.COBBLESTONE,9), new ItemStack(Material.STICK,2), new ItemStack(Material.REDSTONE,1), new ItemStack(Material.COAL,1)); } else { if (!inventory.contains(Material.RAILS, 1)) { // If we don't have rails, we try and convert other materials if (!inventory.contains(Material.IRON_INGOT,4) || !inventory.contains(Material.STICK,1)) { localbroadcast("Raildriver has insufficient building materials for rails!"); return false; } inventory.removeItem( new ItemStack(Material.IRON_INGOT,4), new ItemStack(Material.STICK,1)); inventory.addItem(new ItemStack(Material.RAILS,14)); } // Now try to lay the track if (!inventory.contains(Material.RAILS, 1) || !inventory.contains(Material.COBBLESTONE, 3)) { localbroadcast("Raildriver has insufficient building materials for rails!"); return false; } inventory.removeItem( new ItemStack(Material.RAILS,1), new ItemStack(Material.COBBLESTONE,3)); } } for (int lx = 0; lx < 3; lx++) { for (int ly = 0; ly < 3; ly++) { for (int lz = RailDriver.raildriverblocklist[lx][ly].length; lz > 0; lz--) { Block target = getRelativeBlock(lz,lx,ly); Block source = getRelativeBlock(lz-1,lx,ly); // RailDriver.log.info(source.getType().name()); if (source.getType() == Material.CHEST) { // Get the old chest info Chest sourcechest = (Chest) source.getState(); Inventory sourceinventory = sourcechest.getInventory(); ItemStack[] sourceitems = sourceinventory.getContents(); sourceinventory.clear(); MaterialData sourcedata = sourcechest.getData(); // Blow the old chest away source.setType(Material.AIR); target.setType(Material.CHEST); Chest targetchest = (Chest) target.getState(); targetchest.setData(sourcedata); Inventory targetinventory = targetchest.getInventory(); targetinventory.setContents(sourceitems); targetchest.update(); } else if (source.getType() == Material.BURNING_FURNACE) { Furnace sourcefurnace = (Furnace) source.getState(); Inventory sourceinventory = sourcefurnace.getInventory(); ItemStack[] sourceitems = sourceinventory.getContents(); sourceinventory.clear(); MaterialData sourcedata = sourcefurnace.getData(); // Blow the old chest away source.setType(Material.AIR); target.setType(Material.BURNING_FURNACE); Furnace targetfurnace = (Furnace) target.getState(); targetfurnace.setData(sourcedata); Inventory targetinventory = targetfurnace.getInventory(); targetinventory.setContents(sourceitems); targetfurnace.update(); } else if (source.getType() == Material.DISPENSER || source.getType() == Material.FURNACE || source.getType() == Material.LEVER) { byte sourcedata = source.getData(); Material sourcematerial = source.getType(); source.setType(Material.AIR); target.setType(sourcematerial); target.setData(sourcedata); } else if (source.getType() == Material.TORCH || source.getType() == Material.REDSTONE_TORCH_ON || source.getType() == Material.REDSTONE_TORCH_OFF) { // Prevent free torch dropping side effect target.setType(Material.AIR); } else { target.setType(source.getType()); target.setData(source.getData()); } } } } // Set the floor made of stone for (int lx = 0; lx < 3; lx++) getRelativeBlock(1,lx,-1).setTypeId(98); for (int lx = 0; lx < 3; lx++) { for (int ly = 0; ly < 3; ly++) { if (!(lx == 1 && ly == 1)) { getRelativeBlock(1,lx,ly).setType(Material.AIR); } } } if (distance % period == 0) { for (int ly = 0; ly < 3; ly++) { getRelativeBlock(1,-1,ly-1).setTypeId(98); getRelativeBlock(1,3,ly-1).setTypeId(98); } Block left = getRelativeBlock(1,0,1); if (nexttorch) { left.setType(Material.REDSTONE_TORCH_ON); } else { left.setType(Material.TORCH); } Torch lefttorch = new Torch(left.getType(),left.getData()); lefttorch.setFacingDirection(Facing.RIGHT.translate(direction)); left.setData(lefttorch.getData()); getRelativeBlock(1,1,0).setType(Material.POWERED_RAIL); Block right = getRelativeBlock(1,2,1); if (nexttorch) { right.setType(Material.TORCH); } else { right.setType(Material.REDSTONE_TORCH_ON); } Torch righttorch = new Torch(right.getType(),right.getData()); righttorch.setFacingDirection(Facing.LEFT.translate(direction)); right.setData(righttorch.getData()); nexttorch = !nexttorch; } else { // Regular rail getRelativeBlock(1,1,0).setType(Material.RAILS); } // plugin.getServer().getScheduler().cancelTask(taskid); // plugin.taskset.remove(this); Location newloc = getRelativeBlock(1,1,1).getLocation(); x = newloc.getBlockX(); y = newloc.getBlockY(); z = newloc.getBlockZ(); return true; }
private boolean advance() { // Check to make sure ground under is solid for (int lx = 0; lx < 3; lx++) { for (int lz = 0; lz < RailDriver.raildriverblocklist[lx][0].length; lz++) { Block block = getRelativeBlock(lz,lx,-1); if (block.isEmpty() || block.isLiquid()) { localbroadcast("Raildriver encountered broken ground!"); return false; } } } // Check to make sure behind has no liquid for (int lx = 0; lx < 3; lx++) { Block block = getRelativeBlock(0,lx,0); if (block.isLiquid()) { localbroadcast("Raildriver encountered unstable environment!"); return false; } } // Check to make sure raildriver has enough materials int period = 8; int distance; if (direction == BlockFace.NORTH || direction == BlockFace.SOUTH) { distance = x; } else { distance = z; } if (plugin.getConfig().getBoolean("requires_fuel")) { Chest chest = (Chest) getRelativeBlock(1,1,2).getState(); Inventory inventory = chest.getInventory(); boolean torchcolumns = distance % period == 0; if (torchcolumns) { if (!inventory.contains(Material.POWERED_RAIL,1)) { // If we don't have powered rails, we try and convert other materials if (!inventory.contains(Material.GOLD_INGOT,4) || !inventory.contains(Material.STICK,1) || !inventory.contains(Material.REDSTONE,1)) { localbroadcast("Raildriver has insufficient building materials for power rails!"); return false; } inventory.removeItem( new ItemStack(Material.GOLD_INGOT,4), new ItemStack(Material.STICK,1), new ItemStack(Material.REDSTONE,1)); inventory.addItem(new ItemStack(Material.POWERED_RAIL,14)); } if (!inventory.contains(Material.POWERED_RAIL, 1) || !inventory.contains(Material.COBBLESTONE, 9) || !inventory.contains(Material.STICK, 2) || !inventory.contains(Material.REDSTONE, 1) || !inventory.contains(Material.COAL,1)) { localbroadcast("Raildriver has insufficient building materials for power columns!"); return false; } inventory.removeItem( new ItemStack(Material.POWERED_RAIL,1), new ItemStack(Material.COBBLESTONE,9), new ItemStack(Material.STICK,2), new ItemStack(Material.REDSTONE,1), new ItemStack(Material.COAL,1)); } else { if (!inventory.contains(Material.RAILS, 1)) { // If we don't have rails, we try and convert other materials if (!inventory.contains(Material.IRON_INGOT,4) || !inventory.contains(Material.STICK,1)) { localbroadcast("Raildriver has insufficient building materials for rails!"); return false; } inventory.removeItem( new ItemStack(Material.IRON_INGOT,4), new ItemStack(Material.STICK,1)); inventory.addItem(new ItemStack(Material.RAILS,14)); } // Now try to lay the track if (!inventory.contains(Material.RAILS, 1) || !inventory.contains(Material.COBBLESTONE, 3)) { localbroadcast("Raildriver has insufficient building materials for rails!"); return false; } inventory.removeItem( new ItemStack(Material.RAILS,1), new ItemStack(Material.COBBLESTONE,3)); } } for (int lx = 0; lx < 3; lx++) { for (int ly = 0; ly < 3; ly++) { for (int lz = RailDriver.raildriverblocklist[lx][ly].length; lz > 0; lz--) { Block target = getRelativeBlock(lz,lx,ly); Block source = getRelativeBlock(lz-1,lx,ly); // RailDriver.log.info(source.getType().name()); if (source.getType() == Material.CHEST) { // Get the old chest info Chest sourcechest = (Chest) source.getState(); Inventory sourceinventory = sourcechest.getInventory(); ItemStack[] sourceitems = sourceinventory.getContents(); sourceinventory.clear(); MaterialData sourcedata = sourcechest.getData(); // Blow the old chest away source.setType(Material.AIR); target.setType(Material.CHEST); Chest targetchest = (Chest) target.getState(); targetchest.setData(sourcedata); Inventory targetinventory = targetchest.getInventory(); targetinventory.setContents(sourceitems); targetchest.update(); } else if (source.getType() == Material.BURNING_FURNACE) { Furnace sourcefurnace = (Furnace) source.getState(); Inventory sourceinventory = sourcefurnace.getInventory(); ItemStack[] sourceitems = sourceinventory.getContents(); sourceinventory.clear(); MaterialData sourcedata = sourcefurnace.getData(); // Blow the old chest away source.setType(Material.AIR); target.setType(Material.BURNING_FURNACE); Furnace targetfurnace = (Furnace) target.getState(); targetfurnace.setData(sourcedata); Inventory targetinventory = targetfurnace.getInventory(); targetinventory.setContents(sourceitems); targetfurnace.update(); } else if (source.getType() == Material.DISPENSER || source.getType() == Material.FURNACE || source.getType() == Material.LEVER) { byte sourcedata = source.getData(); Material sourcematerial = source.getType(); source.setType(Material.AIR); target.setType(sourcematerial); target.setData(sourcedata); } else if (source.getType() == Material.TORCH || source.getType() == Material.REDSTONE_TORCH_ON || source.getType() == Material.REDSTONE_TORCH_OFF) { // Prevent free torch dropping side effect target.setType(Material.AIR); } else { target.setType(source.getType()); target.setData(source.getData()); } } } } // Set the floor made of stone for (int lx = 0; lx < 3; lx++) getRelativeBlock(1,lx,-1).setTypeId(98); for (int lx = 0; lx < 3; lx++) { for (int ly = 0; ly < 3; ly++) { if (!(lx == 1 && ly == 1)) { getRelativeBlock(1,lx,ly).setType(Material.AIR); } } } if (distance % period == 0) { for (int ly = 0; ly < 3; ly++) { getRelativeBlock(1,-1,ly-1).setTypeId(98); getRelativeBlock(1,3,ly-1).setTypeId(98); } Block left; if (nexttorch) { left = getRelativeBlock(1,0,0); left.setType(Material.REDSTONE_TORCH_ON); } else { left = getRelativeBlock(1,0,1); left.setType(Material.TORCH); } Torch lefttorch = new Torch(left.getType(),left.getData()); lefttorch.setFacingDirection(Facing.RIGHT.translate(direction)); left.setData(lefttorch.getData()); getRelativeBlock(1,1,0).setType(Material.POWERED_RAIL); Block right; if (nexttorch) { right = getRelativeBlock(1,2,1); right.setType(Material.TORCH); } else { right = getRelativeBlock(1,2,0); right.setType(Material.REDSTONE_TORCH_ON); } Torch righttorch = new Torch(right.getType(),right.getData()); righttorch.setFacingDirection(Facing.LEFT.translate(direction)); right.setData(righttorch.getData()); nexttorch = !nexttorch; } else { // Regular rail getRelativeBlock(1,1,0).setType(Material.RAILS); } // plugin.getServer().getScheduler().cancelTask(taskid); // plugin.taskset.remove(this); Location newloc = getRelativeBlock(1,1,1).getLocation(); x = newloc.getBlockX(); y = newloc.getBlockY(); z = newloc.getBlockZ(); return true; }
diff --git a/LaTeXDraw/src/net/sf/latexdraw/mapping/ShapeList2ViewListMapping.java b/LaTeXDraw/src/net/sf/latexdraw/mapping/ShapeList2ViewListMapping.java index 07ee8b98..ddcdd4e9 100644 --- a/LaTeXDraw/src/net/sf/latexdraw/mapping/ShapeList2ViewListMapping.java +++ b/LaTeXDraw/src/net/sf/latexdraw/mapping/ShapeList2ViewListMapping.java @@ -1,89 +1,89 @@ package net.sf.latexdraw.mapping; import java.util.List; import net.sf.latexdraw.glib.models.interfaces.IShape; import net.sf.latexdraw.glib.models.interfaces.IText; import net.sf.latexdraw.glib.views.Java2D.interfaces.IViewShape; import net.sf.latexdraw.glib.views.Java2D.interfaces.IViewText; import net.sf.latexdraw.glib.views.Java2D.interfaces.View2DTK; import net.sf.latexdraw.glib.views.latex.LaTeXGenerator; import org.malai.mapping.MappingRegistry; import org.malai.mapping.SymmetricList2ListMapping; /** * Defines a mapping that link a list of IShape to a list of IShapeView.<br> *<br> * This file is part of LaTeXDraw<br> * Copyright (c) 2005-2012 Arnaud BLOUIN<br> *<br> * LaTeXDraw is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version.<br> *<br> * LaTeXDraw is distributed without any warranty; without even the * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details.<br> *<br> * 05/15/10<br> * @author Arnaud BLOUIN * @since 3.0 * @version 3.0 */ public class ShapeList2ViewListMapping extends SymmetricList2ListMapping<IShape, IViewShape> { /** * {@link SymmetricList2ListMapping#SymmetricList2ListMapping(List, List)} */ public ShapeList2ViewListMapping(final List<IShape> source, final List<IViewShape> target) { super(source, target); } @Override protected IViewShape createTargetObject(final Object sourceObject) { return sourceObject instanceof IShape ? View2DTK.getFactory().createView((IShape)sourceObject) : null; } @Override public void onObjectAdded(final Object list, final Object object, final int index) { super.onObjectAdded(list, object, index); if(object instanceof IShape) { - MappingRegistry.REGISTRY.addMapping(new Shape2ViewMapping((IShape)object, index==-1 ? target.get(target.size()-1) : target.get(index))); + final IViewShape view = index==-1 ? target.get(target.size()-1) : target.get(index); + MappingRegistry.REGISTRY.addMapping(new Shape2ViewMapping((IShape)object, view)); // If the shape is a text, a special mapping must be added. - if(object instanceof IText) - MappingRegistry.REGISTRY.addMapping(new Package2TextViewMapping( - LaTeXGenerator.getPackagesUnary(), (IViewText)(index==-1 ? target.get(target.size()-1) : target.get(index)))); + if(view instanceof IViewText) + MappingRegistry.REGISTRY.addMapping(new Package2TextViewMapping(LaTeXGenerator.getPackagesUnary(), (IViewText)view)); } } @Override public void onObjectRemoved(final Object list, final Object object, final int index) { IViewShape view = index==-1 ? target.get(target.size()-1) : target.get(index); view.flush(); super.onObjectRemoved(list, object, index); MappingRegistry.REGISTRY.removeMappingsUsingSource(object, Shape2ViewMapping.class); // If the shape is a text, the special mapping previously added must be removed. if(object instanceof IText) MappingRegistry.REGISTRY.removeMappingsUsingTarget(view, Package2TextViewMapping.class); } @Override public void onListCleaned(final Object list) { super.onListCleaned(list); for(IShape shape : source) MappingRegistry.REGISTRY.removeMappingsUsingSource(shape, Shape2ViewMapping.class); } }
false
true
public void onObjectAdded(final Object list, final Object object, final int index) { super.onObjectAdded(list, object, index); if(object instanceof IShape) { MappingRegistry.REGISTRY.addMapping(new Shape2ViewMapping((IShape)object, index==-1 ? target.get(target.size()-1) : target.get(index))); // If the shape is a text, a special mapping must be added. if(object instanceof IText) MappingRegistry.REGISTRY.addMapping(new Package2TextViewMapping( LaTeXGenerator.getPackagesUnary(), (IViewText)(index==-1 ? target.get(target.size()-1) : target.get(index)))); } }
public void onObjectAdded(final Object list, final Object object, final int index) { super.onObjectAdded(list, object, index); if(object instanceof IShape) { final IViewShape view = index==-1 ? target.get(target.size()-1) : target.get(index); MappingRegistry.REGISTRY.addMapping(new Shape2ViewMapping((IShape)object, view)); // If the shape is a text, a special mapping must be added. if(view instanceof IViewText) MappingRegistry.REGISTRY.addMapping(new Package2TextViewMapping(LaTeXGenerator.getPackagesUnary(), (IViewText)view)); } }
diff --git a/BitCrusher/src/com/noisepages/nettoyeur/bitcrusher/MainActivity.java b/BitCrusher/src/com/noisepages/nettoyeur/bitcrusher/MainActivity.java index 6d7215c..606755d 100644 --- a/BitCrusher/src/com/noisepages/nettoyeur/bitcrusher/MainActivity.java +++ b/BitCrusher/src/com/noisepages/nettoyeur/bitcrusher/MainActivity.java @@ -1,112 +1,109 @@ package com.noisepages.nettoyeur.bitcrusher; import java.io.IOException; import android.annotation.TargetApi; import android.app.Activity; import android.content.Context; import android.media.AudioManager; import android.os.Build; import android.os.Bundle; import android.view.Menu; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.Switch; public class MainActivity extends Activity implements OnCheckedChangeListener, OnSeekBarChangeListener { private OpenSlBitCrusher bitCrusher; private SeekBar crushBar; private Switch playSwitch; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); crushBar = (SeekBar) findViewById(R.id.crushBar); crushBar.setOnSeekBarChangeListener(this); playSwitch = (Switch) findViewById(R.id.playSwitch); playSwitch.setOnCheckedChangeListener(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override protected void onStart() { super.onStart(); try { - if (Build.VERSION.SDK_INT >= 17) { - createBitCrusher(); - } else { - createBitCrusherDefault(); - } + bitCrusher = (Build.VERSION.SDK_INT >= 17) ? + createBitCrusher() : createBitCrusherDefault(); setCrush(crushBar.getProgress()); if (playSwitch.isChecked()) { bitCrusher.start(); } } catch (IOException e) { throw new RuntimeException(e); } } // This method will choose the recommended configuration for OpenSL on JB MR1 and later. @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) private OpenSlBitCrusher createBitCrusher() throws IOException { // Detect native sample rate and buffer size. If at all possible, OpenSL should use // these values. AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE); int sr = Integer.parseInt(am.getProperty(AudioManager.PROPERTY_OUTPUT_SAMPLE_RATE)); int bs = Integer.parseInt(am.getProperty(AudioManager.PROPERTY_OUTPUT_FRAMES_PER_BUFFER)); return new OpenSlBitCrusher(sr, bs); } // This method will choose a reasonable default on older devices, i.e., CD sample rate and // 64 frames per buffer. private OpenSlBitCrusher createBitCrusherDefault() throws IOException { return new OpenSlBitCrusher(44100, 64); } @Override protected void onStop() { super.onStop(); bitCrusher.close(); } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { try { bitCrusher.start(); } catch (IOException e) { throw new RuntimeException(e); } } else { bitCrusher.stop(); } } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { setCrush(progress); } private void setCrush(int depth) { bitCrusher.crush(depth * 16 / 101); } @Override public void onStartTrackingTouch(SeekBar seekBar) { // Do nothing. } @Override public void onStopTrackingTouch(SeekBar seekBar) { // Do nothing. } }
true
true
protected void onStart() { super.onStart(); try { if (Build.VERSION.SDK_INT >= 17) { createBitCrusher(); } else { createBitCrusherDefault(); } setCrush(crushBar.getProgress()); if (playSwitch.isChecked()) { bitCrusher.start(); } } catch (IOException e) { throw new RuntimeException(e); } }
protected void onStart() { super.onStart(); try { bitCrusher = (Build.VERSION.SDK_INT >= 17) ? createBitCrusher() : createBitCrusherDefault(); setCrush(crushBar.getProgress()); if (playSwitch.isChecked()) { bitCrusher.start(); } } catch (IOException e) { throw new RuntimeException(e); } }
diff --git a/apps/routerconsole/java/src/net/i2p/router/web/PluginStarter.java b/apps/routerconsole/java/src/net/i2p/router/web/PluginStarter.java index f6aa9adb4..7c7c11b47 100644 --- a/apps/routerconsole/java/src/net/i2p/router/web/PluginStarter.java +++ b/apps/routerconsole/java/src/net/i2p/router/web/PluginStarter.java @@ -1,454 +1,454 @@ package net.i2p.router.web; import java.io.File; import java.io.IOException; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.StringTokenizer; import net.i2p.I2PAppContext; import net.i2p.data.DataHelper; import net.i2p.router.RouterContext; import net.i2p.router.startup.ClientAppConfig; import net.i2p.router.startup.LoadClientAppsJob; import net.i2p.util.FileUtil; import net.i2p.util.Log; import net.i2p.util.Translate; import org.mortbay.jetty.Server; /** * Start/stop/delete plugins that are already installed * Get properties of installed plugins * Get or change settings in plugins.config * * @since 0.7.12 * @author zzz */ public class PluginStarter implements Runnable { protected RouterContext _context; static final String PREFIX = "plugin."; static final String ENABLED = ".startOnLoad"; private static final String[] STANDARD_WEBAPPS = { "i2psnark", "i2ptunnel", "susidns", "susimail", "addressbook", "routerconsole" }; private static final String[] STANDARD_THEMES = { "images", "light", "dark", "classic", "midnight" }; public PluginStarter(RouterContext ctx) { _context = ctx; } static boolean pluginsEnabled(I2PAppContext ctx) { return Boolean.valueOf(ctx.getProperty("router.enablePlugins", "true")).booleanValue(); } public void run() { startPlugins(_context); } /** this shouldn't throw anything */ static void startPlugins(RouterContext ctx) { Log log = ctx.logManager().getLog(PluginStarter.class); Properties props = pluginProperties(); for (Iterator iter = props.keySet().iterator(); iter.hasNext(); ) { String name = (String)iter.next(); if (name.startsWith(PREFIX) && name.endsWith(ENABLED)) { if (Boolean.valueOf(props.getProperty(name)).booleanValue()) { String app = name.substring(PREFIX.length(), name.lastIndexOf(ENABLED)); try { if (!startPlugin(ctx, app)) log.error("Failed to start plugin: " + app); } catch (Throwable e) { log.error("Failed to start plugin: " + app, e); } } } } } /** * @return true on success * @throws just about anything, caller would be wise to catch Throwable */ static boolean startPlugin(RouterContext ctx, String appName) throws Exception { Log log = ctx.logManager().getLog(PluginStarter.class); File pluginDir = new File(ctx.getAppDir(), PluginUpdateHandler.PLUGIN_DIR + '/' + appName); if ((!pluginDir.exists()) || (!pluginDir.isDirectory())) { log.error("Cannot start nonexistent plugin: " + appName); return false; } //log.error("Starting plugin: " + appName); // register themes File dir = new File(pluginDir, "console/themes"); File[] tfiles = dir.listFiles(); if (tfiles != null) { for (int i = 0; i < tfiles.length; i++) { String name = tfiles[i].getName(); if (tfiles[i].isDirectory() && (!Arrays.asList(STANDARD_THEMES).contains(tfiles[i]))) ctx.router().setConfigSetting(ConfigUIHelper.PROP_THEME_PFX + name, tfiles[i].getAbsolutePath()); // we don't need to save } } // load and start things in clients.config File clientConfig = new File(pluginDir, "clients.config"); if (clientConfig.exists()) { Properties props = new Properties(); DataHelper.loadProps(props, clientConfig); List<ClientAppConfig> clients = ClientAppConfig.getClientApps(clientConfig); runClientApps(ctx, pluginDir, clients, "start"); } // start console webapps in console/webapps Server server = WebAppStarter.getConsoleServer(); if (server != null) { File consoleDir = new File(pluginDir, "console"); Properties props = RouterConsoleRunner.webAppProperties(consoleDir.getAbsolutePath()); File webappDir = new File(consoleDir, "webapps"); String fileNames[] = webappDir.list(RouterConsoleRunner.WarFilenameFilter.instance()); if (fileNames != null) { for (int i = 0; i < fileNames.length; i++) { try { String warName = fileNames[i].substring(0, fileNames[i].lastIndexOf(".war")); //log.error("Found webapp: " + warName); // check for duplicates in $I2P if (Arrays.asList(STANDARD_WEBAPPS).contains(warName)) { log.error("Skipping duplicate webapp " + warName + " in plugin " + appName); continue; } - String enabled = props.getProperty(PREFIX + warName + ENABLED); + String enabled = props.getProperty(RouterConsoleRunner.PREFIX + warName + ENABLED); if (! "false".equals(enabled)) { //log.error("Starting webapp: " + warName); String path = new File(webappDir, fileNames[i]).getCanonicalPath(); WebAppStarter.startWebApp(ctx, server, warName, path); } } catch (IOException ioe) { log.error("Error resolving '" + fileNames[i] + "' in '" + webappDir, ioe); } } } } // add translation jars in console/locale // These will not override existing resource bundles since we are adding them // later in the classpath. File localeDir = new File(pluginDir, "console/locale"); if (localeDir.exists() && localeDir.isDirectory()) { File[] files = localeDir.listFiles(); if (files != null) { boolean added = false; for (int i = 0; i < files.length; i++) { File f = files[i]; if (f.getName().endsWith(".jar")) { try { addPath(f.toURI().toURL()); log.error("INFO: Adding translation plugin to classpath: " + f); added = true; } catch (Exception e) { log.error("Plugin " + appName + " bad classpath element: " + f, e); } } } if (added) Translate.clearCache(); } } // add summary bar link Properties props = pluginProperties(ctx, appName); String name = ConfigClientsHelper.stripHTML(props, "consoleLinkName_" + Messages.getLanguage(ctx)); if (name == null) name = ConfigClientsHelper.stripHTML(props, "consoleLinkName"); String url = ConfigClientsHelper.stripHTML(props, "consoleLinkURL"); if (name != null && url != null && name.length() > 0 && url.length() > 0) { String tip = ConfigClientsHelper.stripHTML(props, "consoleLinkTooltip_" + Messages.getLanguage(ctx)); if (tip == null) tip = ConfigClientsHelper.stripHTML(props, "consoleLinkTooltip"); if (tip != null) NavHelper.registerApp(name, url, tip); else NavHelper.registerApp(name, url); } return true; } /** * @return true on success * @throws just about anything, caller would be wise to catch Throwable */ static boolean stopPlugin(RouterContext ctx, String appName) throws Exception { Log log = ctx.logManager().getLog(PluginStarter.class); File pluginDir = new File(ctx.getAppDir(), PluginUpdateHandler.PLUGIN_DIR + '/' + appName); if ((!pluginDir.exists()) || (!pluginDir.isDirectory())) { log.error("Cannot stop nonexistent plugin: " + appName); return false; } // stop things in clients.config File clientConfig = new File(pluginDir, "clients.config"); if (clientConfig.exists()) { Properties props = new Properties(); DataHelper.loadProps(props, clientConfig); List<ClientAppConfig> clients = ClientAppConfig.getClientApps(clientConfig); runClientApps(ctx, pluginDir, clients, "stop"); } // stop console webapps in console/webapps Server server = WebAppStarter.getConsoleServer(); if (server != null) { File consoleDir = new File(pluginDir, "console"); Properties props = RouterConsoleRunner.webAppProperties(consoleDir.getAbsolutePath()); File webappDir = new File(consoleDir, "webapps"); String fileNames[] = webappDir.list(RouterConsoleRunner.WarFilenameFilter.instance()); if (fileNames != null) { for (int i = 0; i < fileNames.length; i++) { String warName = fileNames[i].substring(0, fileNames[i].lastIndexOf(".war")); if (Arrays.asList(STANDARD_WEBAPPS).contains(warName)) { continue; } WebAppStarter.stopWebApp(server, warName); } } } // remove summary bar link Properties props = pluginProperties(ctx, appName); String name = ConfigClientsHelper.stripHTML(props, "consoleLinkName_" + Messages.getLanguage(ctx)); if (name == null) name = ConfigClientsHelper.stripHTML(props, "consoleLinkName"); if (name != null && name.length() > 0) NavHelper.unregisterApp(name); if (log.shouldLog(Log.WARN)) log.warn("Stopping plugin: " + appName); return true; } /** @return true on success - caller should call stopPlugin() first */ static boolean deletePlugin(RouterContext ctx, String appName) throws Exception { Log log = ctx.logManager().getLog(PluginStarter.class); File pluginDir = new File(ctx.getAppDir(), PluginUpdateHandler.PLUGIN_DIR + '/' + appName); if ((!pluginDir.exists()) || (!pluginDir.isDirectory())) { log.error("Cannot delete nonexistent plugin: " + appName); return false; } // uninstall things in clients.config File clientConfig = new File(pluginDir, "clients.config"); if (clientConfig.exists()) { Properties props = new Properties(); DataHelper.loadProps(props, clientConfig); List<ClientAppConfig> clients = ClientAppConfig.getClientApps(clientConfig); runClientApps(ctx, pluginDir, clients, "uninstall"); } // unregister themes, and switch to default if we are unregistering the current theme File dir = new File(pluginDir, "console/themes"); File[] tfiles = dir.listFiles(); if (tfiles != null) { String current = ctx.getProperty(CSSHelper.PROP_THEME_NAME); for (int i = 0; i < tfiles.length; i++) { String name = tfiles[i].getName(); if (tfiles[i].isDirectory() && (!Arrays.asList(STANDARD_THEMES).contains(tfiles[i]))) { ctx.router().removeConfigSetting(ConfigUIHelper.PROP_THEME_PFX + name); if (name.equals(current)) ctx.router().setConfigSetting(CSSHelper.PROP_THEME_NAME, CSSHelper.DEFAULT_THEME); } } ctx.router().saveConfig(); } FileUtil.rmdir(pluginDir, false); Properties props = pluginProperties(); for (Iterator iter = props.keySet().iterator(); iter.hasNext(); ) { String name = (String)iter.next(); if (name.startsWith(PREFIX + appName)) iter.remove(); } storePluginProperties(props); return true; } /** plugin.config */ public static Properties pluginProperties(I2PAppContext ctx, String appName) { File cfgFile = new File(ctx.getAppDir(), PluginUpdateHandler.PLUGIN_DIR + '/' + appName + '/' + "plugin.config"); Properties rv = new Properties(); try { DataHelper.loadProps(rv, cfgFile); } catch (IOException ioe) {} return rv; } /** * plugins.config * this auto-adds a propery for every dir in the plugin directory */ public static Properties pluginProperties() { File dir = I2PAppContext.getGlobalContext().getConfigDir(); Properties rv = new Properties(); File cfgFile = new File(dir, "plugins.config"); try { DataHelper.loadProps(rv, cfgFile); } catch (IOException ioe) {} List<String> names = getPlugins(); for (String name : names) { String prop = PREFIX + name + ENABLED; if (rv.getProperty(prop) == null) rv.setProperty(prop, "true"); } return rv; } /** * all installed plugins whether enabled or not */ public static List<String> getPlugins() { List<String> rv = new ArrayList(); File pluginDir = new File(I2PAppContext.getGlobalContext().getAppDir(), PluginUpdateHandler.PLUGIN_DIR); File[] files = pluginDir.listFiles(); if (files == null) return rv; for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) rv.add(files[i].getName()); } return rv; } /** * The signing keys from all the plugins * @return Map of key to keyname * Last one wins if a dup (installer should prevent dups) */ public static Map<String, String> getPluginKeys(I2PAppContext ctx) { Map<String, String> rv = new HashMap(); List<String> names = getPlugins(); for (String name : names) { Properties props = pluginProperties(ctx, name); String pubkey = props.getProperty("key"); String signer = props.getProperty("signer"); if (pubkey != null && signer != null && pubkey.length() == 172 && signer.length() > 0) rv.put(pubkey, signer); } return rv; } /** * plugins.config */ public static void storePluginProperties(Properties props) { File cfgFile = new File(I2PAppContext.getGlobalContext().getConfigDir(), "plugins.config"); try { DataHelper.storeProps(props, cfgFile); } catch (IOException ioe) {} } /** * @param action "start" or "stop" or "uninstall" * @throws just about anything if an app has a delay less than zero, caller would be wise to catch Throwable * If no apps have a delay less than zero, it shouldn't throw anything */ private static void runClientApps(RouterContext ctx, File pluginDir, List<ClientAppConfig> apps, String action) throws Exception { Log log = ctx.logManager().getLog(PluginStarter.class); for(ClientAppConfig app : apps) { if (action.equals("start") && app.disabled) continue; String argVal[]; if (action.equals("start")) { // start argVal = LoadClientAppsJob.parseArgs(app.args); } else { String args; if (action.equals("stop")) args = app.stopargs; else if (action.equals("uninstall")) args = app.uninstallargs; else throw new IllegalArgumentException("bad action"); // args must be present if (args == null || args.length() <= 0) continue; argVal = LoadClientAppsJob.parseArgs(args); } // do this after parsing so we don't need to worry about quoting for (int i = 0; i < argVal.length; i++) { if (argVal[i].indexOf("$") >= 0) { argVal[i] = argVal[i].replace("$I2P", ctx.getBaseDir().getAbsolutePath()); argVal[i] = argVal[i].replace("$CONFIG", ctx.getConfigDir().getAbsolutePath()); argVal[i] = argVal[i].replace("$PLUGIN", pluginDir.getAbsolutePath()); } } if (app.classpath != null) { String cp = new String(app.classpath); if (cp.indexOf("$") >= 0) { cp = cp.replace("$I2P", ctx.getBaseDir().getAbsolutePath()); cp = cp.replace("$CONFIG", ctx.getConfigDir().getAbsolutePath()); cp = cp.replace("$PLUGIN", pluginDir.getAbsolutePath()); } addToClasspath(cp, app.clientName, log); } if (app.delay < 0 && action.equals("start")) { // this will throw exceptions LoadClientAppsJob.runClientInline(app.className, app.clientName, argVal, log); } else if (app.delay == 0 || !action.equals("start")) { // quick check, will throw ClassNotFoundException on error LoadClientAppsJob.testClient(app.className); // run this guy now LoadClientAppsJob.runClient(app.className, app.clientName, argVal, log); } else { // quick check, will throw ClassNotFoundException on error LoadClientAppsJob.testClient(app.className); // wait before firing it up ctx.jobQueue().addJob(new LoadClientAppsJob.DelayedRunClient(ctx, app.className, app.clientName, argVal, app.delay)); } } } /** * Perhaps there's an easy way to use Thread.setContextClassLoader() * but I don't see how to make it magically get used for everything. * So add this to the whole JVM's classpath. */ private static void addToClasspath(String classpath, String clientName, Log log) { StringTokenizer tok = new StringTokenizer(classpath, ","); while (tok.hasMoreTokens()) { String elem = tok.nextToken().trim(); File f = new File(elem); if (!f.isAbsolute()) { log.error("Plugin client " + clientName + " classpath element is not absolute: " + f); continue; } try { addPath(f.toURI().toURL()); if (log.shouldLog(Log.WARN)) log.warn("INFO: Adding plugin to classpath: " + f); } catch (Exception e) { log.error("Plugin client " + clientName + " bad classpath element: " + f, e); } } } /** * http://jimlife.wordpress.com/2007/12/19/java-adding-new-classpath-at-runtime/ */ public static void addPath(URL u) throws Exception { URLClassLoader urlClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader(); Class urlClass = URLClassLoader.class; Method method = urlClass.getDeclaredMethod("addURL", new Class[]{URL.class}); method.setAccessible(true); method.invoke(urlClassLoader, new Object[]{u}); } }
true
true
static boolean startPlugin(RouterContext ctx, String appName) throws Exception { Log log = ctx.logManager().getLog(PluginStarter.class); File pluginDir = new File(ctx.getAppDir(), PluginUpdateHandler.PLUGIN_DIR + '/' + appName); if ((!pluginDir.exists()) || (!pluginDir.isDirectory())) { log.error("Cannot start nonexistent plugin: " + appName); return false; } //log.error("Starting plugin: " + appName); // register themes File dir = new File(pluginDir, "console/themes"); File[] tfiles = dir.listFiles(); if (tfiles != null) { for (int i = 0; i < tfiles.length; i++) { String name = tfiles[i].getName(); if (tfiles[i].isDirectory() && (!Arrays.asList(STANDARD_THEMES).contains(tfiles[i]))) ctx.router().setConfigSetting(ConfigUIHelper.PROP_THEME_PFX + name, tfiles[i].getAbsolutePath()); // we don't need to save } } // load and start things in clients.config File clientConfig = new File(pluginDir, "clients.config"); if (clientConfig.exists()) { Properties props = new Properties(); DataHelper.loadProps(props, clientConfig); List<ClientAppConfig> clients = ClientAppConfig.getClientApps(clientConfig); runClientApps(ctx, pluginDir, clients, "start"); } // start console webapps in console/webapps Server server = WebAppStarter.getConsoleServer(); if (server != null) { File consoleDir = new File(pluginDir, "console"); Properties props = RouterConsoleRunner.webAppProperties(consoleDir.getAbsolutePath()); File webappDir = new File(consoleDir, "webapps"); String fileNames[] = webappDir.list(RouterConsoleRunner.WarFilenameFilter.instance()); if (fileNames != null) { for (int i = 0; i < fileNames.length; i++) { try { String warName = fileNames[i].substring(0, fileNames[i].lastIndexOf(".war")); //log.error("Found webapp: " + warName); // check for duplicates in $I2P if (Arrays.asList(STANDARD_WEBAPPS).contains(warName)) { log.error("Skipping duplicate webapp " + warName + " in plugin " + appName); continue; } String enabled = props.getProperty(PREFIX + warName + ENABLED); if (! "false".equals(enabled)) { //log.error("Starting webapp: " + warName); String path = new File(webappDir, fileNames[i]).getCanonicalPath(); WebAppStarter.startWebApp(ctx, server, warName, path); } } catch (IOException ioe) { log.error("Error resolving '" + fileNames[i] + "' in '" + webappDir, ioe); } } } } // add translation jars in console/locale // These will not override existing resource bundles since we are adding them // later in the classpath. File localeDir = new File(pluginDir, "console/locale"); if (localeDir.exists() && localeDir.isDirectory()) { File[] files = localeDir.listFiles(); if (files != null) { boolean added = false; for (int i = 0; i < files.length; i++) { File f = files[i]; if (f.getName().endsWith(".jar")) { try { addPath(f.toURI().toURL()); log.error("INFO: Adding translation plugin to classpath: " + f); added = true; } catch (Exception e) { log.error("Plugin " + appName + " bad classpath element: " + f, e); } } } if (added) Translate.clearCache(); } } // add summary bar link Properties props = pluginProperties(ctx, appName); String name = ConfigClientsHelper.stripHTML(props, "consoleLinkName_" + Messages.getLanguage(ctx)); if (name == null) name = ConfigClientsHelper.stripHTML(props, "consoleLinkName"); String url = ConfigClientsHelper.stripHTML(props, "consoleLinkURL"); if (name != null && url != null && name.length() > 0 && url.length() > 0) { String tip = ConfigClientsHelper.stripHTML(props, "consoleLinkTooltip_" + Messages.getLanguage(ctx)); if (tip == null) tip = ConfigClientsHelper.stripHTML(props, "consoleLinkTooltip"); if (tip != null) NavHelper.registerApp(name, url, tip); else NavHelper.registerApp(name, url); } return true; }
static boolean startPlugin(RouterContext ctx, String appName) throws Exception { Log log = ctx.logManager().getLog(PluginStarter.class); File pluginDir = new File(ctx.getAppDir(), PluginUpdateHandler.PLUGIN_DIR + '/' + appName); if ((!pluginDir.exists()) || (!pluginDir.isDirectory())) { log.error("Cannot start nonexistent plugin: " + appName); return false; } //log.error("Starting plugin: " + appName); // register themes File dir = new File(pluginDir, "console/themes"); File[] tfiles = dir.listFiles(); if (tfiles != null) { for (int i = 0; i < tfiles.length; i++) { String name = tfiles[i].getName(); if (tfiles[i].isDirectory() && (!Arrays.asList(STANDARD_THEMES).contains(tfiles[i]))) ctx.router().setConfigSetting(ConfigUIHelper.PROP_THEME_PFX + name, tfiles[i].getAbsolutePath()); // we don't need to save } } // load and start things in clients.config File clientConfig = new File(pluginDir, "clients.config"); if (clientConfig.exists()) { Properties props = new Properties(); DataHelper.loadProps(props, clientConfig); List<ClientAppConfig> clients = ClientAppConfig.getClientApps(clientConfig); runClientApps(ctx, pluginDir, clients, "start"); } // start console webapps in console/webapps Server server = WebAppStarter.getConsoleServer(); if (server != null) { File consoleDir = new File(pluginDir, "console"); Properties props = RouterConsoleRunner.webAppProperties(consoleDir.getAbsolutePath()); File webappDir = new File(consoleDir, "webapps"); String fileNames[] = webappDir.list(RouterConsoleRunner.WarFilenameFilter.instance()); if (fileNames != null) { for (int i = 0; i < fileNames.length; i++) { try { String warName = fileNames[i].substring(0, fileNames[i].lastIndexOf(".war")); //log.error("Found webapp: " + warName); // check for duplicates in $I2P if (Arrays.asList(STANDARD_WEBAPPS).contains(warName)) { log.error("Skipping duplicate webapp " + warName + " in plugin " + appName); continue; } String enabled = props.getProperty(RouterConsoleRunner.PREFIX + warName + ENABLED); if (! "false".equals(enabled)) { //log.error("Starting webapp: " + warName); String path = new File(webappDir, fileNames[i]).getCanonicalPath(); WebAppStarter.startWebApp(ctx, server, warName, path); } } catch (IOException ioe) { log.error("Error resolving '" + fileNames[i] + "' in '" + webappDir, ioe); } } } } // add translation jars in console/locale // These will not override existing resource bundles since we are adding them // later in the classpath. File localeDir = new File(pluginDir, "console/locale"); if (localeDir.exists() && localeDir.isDirectory()) { File[] files = localeDir.listFiles(); if (files != null) { boolean added = false; for (int i = 0; i < files.length; i++) { File f = files[i]; if (f.getName().endsWith(".jar")) { try { addPath(f.toURI().toURL()); log.error("INFO: Adding translation plugin to classpath: " + f); added = true; } catch (Exception e) { log.error("Plugin " + appName + " bad classpath element: " + f, e); } } } if (added) Translate.clearCache(); } } // add summary bar link Properties props = pluginProperties(ctx, appName); String name = ConfigClientsHelper.stripHTML(props, "consoleLinkName_" + Messages.getLanguage(ctx)); if (name == null) name = ConfigClientsHelper.stripHTML(props, "consoleLinkName"); String url = ConfigClientsHelper.stripHTML(props, "consoleLinkURL"); if (name != null && url != null && name.length() > 0 && url.length() > 0) { String tip = ConfigClientsHelper.stripHTML(props, "consoleLinkTooltip_" + Messages.getLanguage(ctx)); if (tip == null) tip = ConfigClientsHelper.stripHTML(props, "consoleLinkTooltip"); if (tip != null) NavHelper.registerApp(name, url, tip); else NavHelper.registerApp(name, url); } return true; }
diff --git a/jkit/java/stages/InnerClassRewrite.java b/jkit/java/stages/InnerClassRewrite.java index f1080c6..acc8fce 100755 --- a/jkit/java/stages/InnerClassRewrite.java +++ b/jkit/java/stages/InnerClassRewrite.java @@ -1,953 +1,954 @@ package jkit.java.stages; import static jkit.compiler.SyntaxError.syntax_error; import java.util.*; import jkit.compiler.ClassLoader; import jkit.compiler.Clazz; import jkit.compiler.FieldNotFoundException; import jkit.java.io.JavaFile; import jkit.java.tree.*; import jkit.java.tree.Decl.*; import jkit.java.tree.Stmt.Case; import static jkit.java.tree.Type.fromJilType; import static jkit.jil.util.Types.parentType; import jkit.jil.tree.*; import jkit.jil.tree.Type; import jkit.jil.util.*; import jkit.util.Pair; import jkit.util.Triple; /** * <p> * The purpose of this stage is to perform several rewrites related to inner * classes: * <ol> * <li>Non-static inner classes require parent pointer fields</li> * <li>Parent pointer fields must be initialised in all constructors</li> * <li>Access methods must be added when an inner class attempts to access a * private field of an enclosing class.</li> * </ol> * For example, consider the following: * </p> * * <pre> * class Parent { * private String outer; * * public static class Inner { * public void f() { * outer = &quot;Hello World&quot;; * } * } * } * </pre> * * <p> * Now, compiling these classes without adding an accessor would cause a * problem, since the JVM does not permit private fields to be accessed from * other classes. That is, it would not permit field <code>Parent.outer</code> * to be accessed from the separate class <code>Parent$Inner</code>. * </p> * <p> * To workaround this problem, the Java compiler inserts <code>access</code> * methods. We can think of this as applying a simple transformation of the * original program before compilation. So, for example, the above program is * transformed into the following before being compiled: * </p> * * <pre> * class Parent { * private String outer; * * String access$001(String tmp) { * out = tmp; * } * * public static class Inner { * public void f() { * access$001(&quot;Hello World&quot;); * } * } * } * </pre> * * <p> * Here, we see that the access method has two interesting properties: firstly, * it has a name which cannot be expressed in Java source code; secondly, it has * <code>package</code> visibility (since no <code>public</code>/<code>protected</code>/<code>private</code> * modifier is given). * </p> * The naming scheme for access methods is as follows: * <ol> * <li><b>access$xy0</b> - indicates a read access of some field.</li> * <li><b>access$xy2</b> - indicates a write access of some field.</li> * <li><b>access$0yz</b> - indicates some kind of access to the first such * access encountered in the source file. Then, 1xy would indicate the next, and * so on.</li> * </ol> * <p> * Thefore, this stage traverses the source file looking for such inner class * accesses, and inserting <code>access</code> methods where appropriate. * </p> * * @author djp * */ public class InnerClassRewrite { private ClassLoader loader; private TypeSystem types; private final Stack<Type.Clazz> enclosingClasses = new Stack<Type.Clazz>(); private final HashMap<Type.Clazz, HashMap<String, JilMethod>> readAccessors = new HashMap(); private final HashMap<Type.Clazz, HashMap<String, JilMethod>> writeAccessors = new HashMap(); public InnerClassRewrite(ClassLoader loader, TypeSystem types) { this.loader = loader; this.types = types; } public void apply(JavaFile file) { readAccessors.clear(); writeAccessors.clear(); // Traverse the declarations for(Decl d : file.declarations()) { doDeclaration(d); } } protected void doDeclaration(Decl d) { if(d instanceof JavaInterface) { doInterface((JavaInterface)d); } else if(d instanceof JavaClass) { doClass((JavaClass)d); } else if(d instanceof JavaMethod) { doMethod((JavaMethod)d); } else if(d instanceof JavaField) { doField((JavaField)d); } else if (d instanceof Decl.InitialiserBlock) { doInitialiserBlock((Decl.InitialiserBlock) d); } else if (d instanceof Decl.StaticInitialiserBlock) { doStaticInitialiserBlock((Decl.StaticInitialiserBlock) d); } else { syntax_error("internal failure (unknown declaration \"" + d + "\" encountered)",d); } } protected void doInterface(JavaInterface d) { doClass(d); } protected void doClass(JavaClass c) { Type.Clazz type = (Type.Clazz) c.attribute(Type.class); enclosingClasses.add(type); for(Decl d : c.declarations()) { doDeclaration(d); } if (type.components().size() > 1 && !c.isStatic() && !(c instanceof JavaInterface)) { // Ok, we've found a non-static inner class here. Therefore, we need // to rewrite all constructors to accept a parent pointer. try { addParentPtr(c,type,Types.parentType(type)); } catch(ClassNotFoundException cne) { syntax_error(cne.getMessage(),c,cne); } } enclosingClasses.pop(); } protected void doMethod(JavaMethod d) { doStatement(d.body()); } protected void doField(JavaField d) { d.setInitialiser(doExpression(d.initialiser())); } protected void doInitialiserBlock(Decl.InitialiserBlock d) { List<Stmt> statements = d.statements(); for(int i=0;i!=statements.size();++i) { statements.set(i, doStatement(statements.get(i))); } } protected void doStaticInitialiserBlock(Decl.StaticInitialiserBlock d) { List<Stmt> statements = d.statements(); for(int i=0;i!=statements.size();++i) { statements.set(i, doStatement(statements.get(i))); } } protected Stmt doStatement(Stmt e) { if(e instanceof Stmt.SynchronisedBlock) { doSynchronisedBlock((Stmt.SynchronisedBlock)e); } else if(e instanceof Stmt.TryCatchBlock) { doTryCatchBlock((Stmt.TryCatchBlock)e); } else if(e instanceof Stmt.Block) { doBlock((Stmt.Block)e); } else if(e instanceof Stmt.VarDef) { doVarDef((Stmt.VarDef) e); } else if(e instanceof Stmt.Assignment) { return (Stmt) doAssignment((Stmt.Assignment) e); } else if(e instanceof Stmt.Return) { doReturn((Stmt.Return) e); } else if(e instanceof Stmt.Throw) { doThrow((Stmt.Throw) e); } else if(e instanceof Stmt.Assert) { doAssert((Stmt.Assert) e); } else if(e instanceof Stmt.Break) { doBreak((Stmt.Break) e); } else if(e instanceof Stmt.Continue) { doContinue((Stmt.Continue) e); } else if(e instanceof Stmt.Label) { doLabel((Stmt.Label) e); } else if(e instanceof Stmt.If) { doIf((Stmt.If) e); } else if(e instanceof Stmt.For) { doFor((Stmt.For) e); } else if(e instanceof Stmt.ForEach) { doForEach((Stmt.ForEach) e); } else if(e instanceof Stmt.While) { doWhile((Stmt.While) e); } else if(e instanceof Stmt.DoWhile) { doDoWhile((Stmt.DoWhile) e); } else if(e instanceof Stmt.Switch) { doSwitch((Stmt.Switch) e); } else if(e instanceof Expr.Invoke) { doInvoke((Expr.Invoke) e); } else if(e instanceof Expr.New) { doNew((Expr.New) e); } else if(e instanceof Decl.JavaClass) { doClass((Decl.JavaClass)e); } else if(e instanceof Stmt.PrePostIncDec) { doExpression((Stmt.PrePostIncDec)e); } else if(e != null) { syntax_error("Invalid statement encountered: " + e.getClass(),e); } return e; } protected void doBlock(Stmt.Block block) { if(block != null) { List<Stmt> statements = block.statements(); for(int i=0;i!=statements.size();++i) { statements.set(i, doStatement(statements.get(i))); } } } protected void doCatchBlock(Stmt.CatchBlock block) { if(block != null) { List<Stmt> statements = block.statements(); for(int i=0;i!=statements.size();++i) { statements.set(i, doStatement(statements.get(i))); } } } protected void doSynchronisedBlock(Stmt.SynchronisedBlock block) { doBlock(block); doExpression(block.expr()); } protected void doTryCatchBlock(Stmt.TryCatchBlock block) { doBlock(block); doBlock(block.finaly()); for(Stmt.CatchBlock cb : block.handlers()) { doCatchBlock(cb); } } protected void doVarDef(Stmt.VarDef def) { List<Triple<String, Integer, Expr>> defs = def.definitions(); Type t = (Type) def.type().attribute(Type.class); for(int i=0;i!=defs.size();++i) { Triple<String, Integer, Expr> d = defs.get(i); Type nt = t; for(int j=0;j!=d.second();++j) { nt = new Type.Array(nt); } Expr e = doExpression(d.third()); defs.set(i, new Triple(d.first(),d.second(),e)); } } protected Expr doAssignment(Stmt.Assignment def) { // first, do the right-hand side def.setRhs(doExpression(def.rhs())); // second, so the left-hand side. if(def.lhs() instanceof Expr.Deref) { Expr.Deref e = (Expr.Deref) def.lhs(); Type tmp = (Type) e.target().attribute(Type.class); if(!(tmp instanceof Type.Reference) || tmp instanceof Type.Array) { // don't need to do anything in this case } else { Type.Clazz target = (Type.Clazz) tmp; if(e.name().equals("this")) { // This is a special case, where we're trying to look up a field // called "this". No such field can exist! What this means is that // we're inside an inner class, and we're trying to access the this // pointer of an enclosing class. This is easy to deal with here, // since the type returned by this expression will be the target // type of the dereference. // don't need to do anything here. } else { // now, perform field lookup! try { Triple<Clazz, Clazz.Field, Type> r = types .resolveField(target, e.name(), loader); Clazz.Field f = r.second(); Clazz c = r.first(); if (f.isPrivate() && isStrictInnerClass(enclosingClasses.peek(), c.type())) { // Ok, we have found a dereference of a field. This // means we need to add an accessor method, unless there // already is one. if(!(c instanceof jkit.jil.tree.JilClass)) { // it should be impossible to get here. syntax_error( "internal failure --- jil class required, found " + c.getClass().getName(), e); } ArrayList<jkit.jil.tree.Attribute> attributes = new ArrayList(e.attributes()); Clazz.Method accessor = createWriteAccessor(f, (jkit.jil.tree.JilClass) c); attributes.add(new JilBuilder.MethodInfo(accessor.exceptions(),accessor.type())); ArrayList<Expr> params = new ArrayList<Expr>(); + params.add(e.target()); params.add(def.rhs()); return new Expr.Invoke(new Expr.ClassVariable(c .type().toString(), c.type()), accessor .name(), params, new ArrayList(), attributes); } } catch(ClassNotFoundException cne) { syntax_error("class not found: " + target,e,cne); } catch(FieldNotFoundException fne) { syntax_error("field not found: " + target + "." + e.name(),e,fne); } } } } else { Expr lhs = doExpression(def.lhs()); def.setLhs(lhs); } return def; } protected void doReturn(Stmt.Return ret) { ret.setExpr(doExpression(ret.expr())); } protected void doThrow(Stmt.Throw ret) { ret.setExpr(doExpression(ret.expr())); } protected void doAssert(Stmt.Assert ret) { ret.setExpr(doExpression(ret.expr())); } protected void doBreak(Stmt.Break brk) { // nothing } protected void doContinue(Stmt.Continue brk) { // nothing } protected void doLabel(Stmt.Label lab) { lab.setStatement(doStatement(lab.statement())); } protected void doIf(Stmt.If stmt) { stmt.setCondition(doExpression(stmt.condition())); stmt.setTrueStatement(doStatement(stmt.trueStatement())); stmt.setFalseStatement(doStatement(stmt.falseStatement())); } protected void doWhile(Stmt.While stmt) { stmt.setCondition(doExpression(stmt.condition())); stmt.setBody(doStatement(stmt.body())); } protected void doDoWhile(Stmt.DoWhile stmt) { stmt.setCondition(doExpression(stmt.condition())); stmt.setBody(doStatement(stmt.body())); } protected void doFor(Stmt.For stmt) { stmt.setInitialiser(doStatement(stmt.initialiser())); stmt.setCondition(doExpression(stmt.condition())); stmt.setIncrement(doStatement(stmt.increment())); stmt.setBody(doStatement(stmt.body())); } protected void doForEach(Stmt.ForEach stmt) { stmt.setSource(doExpression(stmt.source())); stmt.setBody(doStatement(stmt.body())); } protected void doSwitch(Stmt.Switch sw) { sw.setCondition(doExpression(sw.condition())); for(Case c : sw.cases()) { c.setCondition(doExpression(c.condition())); List<Stmt> statements = c.statements(); for(int i=0;i!=statements.size();++i) { statements.set(i, doStatement(statements.get(i))); } } // should check that case conditions are final constants here. } protected Expr doExpression(Expr e) { if(e instanceof Value.Bool) { return doBoolVal((Value.Bool)e); } if(e instanceof Value.Byte) { return doByteVal((Value.Byte)e); } else if(e instanceof Value.Char) { return doCharVal((Value.Char)e); } else if(e instanceof Value.Short) { return doShortVal((Value.Short)e); } else if(e instanceof Value.Int) { return doIntVal((Value.Int)e); } else if(e instanceof Value.Long) { return doLongVal((Value.Long)e); } else if(e instanceof Value.Float) { return doFloatVal((Value.Float)e); } else if(e instanceof Value.Double) { return doDoubleVal((Value.Double)e); } else if(e instanceof Value.String) { return doStringVal((Value.String)e); } else if(e instanceof Value.Null) { return doNullVal((Value.Null)e); } else if(e instanceof Value.TypedArray) { return doTypedArrayVal((Value.TypedArray)e); } else if(e instanceof Value.Array) { return doArrayVal((Value.Array)e); } else if(e instanceof Value.Class) { return doClassVal((Value.Class) e); } else if(e instanceof Expr.LocalVariable) { return doLocalVariable((Expr.LocalVariable)e); } else if(e instanceof Expr.NonLocalVariable) { return doNonLocalVariable((Expr.NonLocalVariable)e); } else if(e instanceof Expr.ClassVariable) { return doClassVariable((Expr.ClassVariable)e); } else if(e instanceof Expr.UnOp) { return doUnOp((Expr.UnOp)e); } else if(e instanceof Expr.BinOp) { return doBinOp((Expr.BinOp)e); } else if(e instanceof Expr.TernOp) { return doTernOp((Expr.TernOp)e); } else if(e instanceof Expr.Cast) { return doCast((Expr.Cast)e); } else if(e instanceof Expr.Convert) { return doConvert((Expr.Convert)e); } else if(e instanceof Expr.InstanceOf) { return doInstanceOf((Expr.InstanceOf)e); } else if(e instanceof Expr.Invoke) { return doInvoke((Expr.Invoke) e); } else if(e instanceof Expr.New) { return doNew((Expr.New) e); } else if(e instanceof Expr.ArrayIndex) { return doArrayIndex((Expr.ArrayIndex) e); } else if(e instanceof Expr.Deref) { return doDeref((Expr.Deref) e); } else if(e instanceof Stmt.Assignment) { // force brackets return doAssignment((Stmt.Assignment) e); } else if(e != null) { syntax_error("Invalid expression encountered: " + e.getClass(),e); } return null; } protected Expr doDeref(Expr.Deref e) { e.setTarget(doExpression(e.target())); Type tmp = (Type) e.target().attribute(Type.class); if(!(tmp instanceof Type.Reference) || tmp instanceof Type.Array) { // don't need to do anything in this case } else { Type.Clazz target = (Type.Clazz) tmp; if(e.name().equals("this")) { // This is a special case, where we're trying to look up a field // called "this". No such field can exist! What this means is that // we're inside an inner class, and we're trying to access the this // pointer of an enclosing class. This is easy to deal with here, // since the type returned by this expression will be the target // type of the dereference. // don't need to do anything here. } else { // now, perform field lookup! try { Triple<Clazz, Clazz.Field, Type> r = types .resolveField(target, e.name(), loader); Clazz.Field f = r.second(); Clazz c = r.first(); if (f.isPrivate() && isStrictInnerClass(enclosingClasses.peek(), c.type())) { // Ok, we have found a dereference of a field. This // means we need to add an accessor method, unless there // already is one. if(!(c instanceof jkit.jil.tree.JilClass)) { // it should be impossible to get here. syntax_error( "internal failure --- jil class required, found " + c.getClass().getName(), e); } ArrayList<jkit.jil.tree.Attribute> attributes = new ArrayList(e.attributes()); Clazz.Method accessor = createReadAccessor(f, (jkit.jil.tree.JilClass) c); attributes.add(new JilBuilder.MethodInfo(accessor.exceptions(),accessor.type())); ArrayList<Expr> params = new ArrayList<Expr>(); params.add(e.target()); return new Expr.Invoke(new Expr.ClassVariable(c.type() .toString(), c.type()), accessor.name(), params, new ArrayList(), attributes); } } catch(ClassNotFoundException cne) { syntax_error("class not found: " + target,e,cne); } catch(FieldNotFoundException fne) { syntax_error("field not found: " + target + "." + e.name(),e,fne); } } } return e; } protected Expr doArrayIndex(Expr.ArrayIndex e) { e.setTarget(doExpression(e.target())); e.setIndex(doExpression(e.index())); return e; } protected Expr doNew(Expr.New e) { // Second, recurse through any parameters supplied ... Type type = (Type) e.type().attribute(Type.class); List<Expr> parameters = e.parameters(); for(int i=0;i!=parameters.size();++i) { Expr p = parameters.get(i); parameters.set(i,doExpression(p)); } if(e.declarations().size() > 0) { Type.Clazz clazz = (Type.Clazz) e.type().attribute(Type.Clazz.class); enclosingClasses.add(clazz); for(Decl d : e.declarations()) { doDeclaration(d); } enclosingClasses.pop(); } // Now, check whether we're constructing a non-static inner class. If // so, then we need supply the parent pointer. if(type instanceof Type.Clazz) { Type.Clazz tc = (Type.Clazz) type; if(tc.components().size() > 1) { // Ok, this is an inner class construction. So, we need to check // whether it's static or not. try { Clazz clazz = loader.loadClass(tc); if(!clazz.isStatic()) { // First, update the arguments to the new call Type.Clazz parentType = parentType(tc); if(e.context() == null) { Expr.LocalVariable thiz = new Expr.LocalVariable( "this", parentType); e.parameters().add(0,thiz); } // Second, update the function type. JilBuilder.MethodInfo mi = (JilBuilder.MethodInfo) e .attribute(JilBuilder.MethodInfo.class); Type.Function mt = mi.type; ArrayList<Type> nparamtypes = new ArrayList<Type>(mt.parameterTypes()); nparamtypes.add(0,parentType); mi.type = new Type.Function(mt.returnType(), nparamtypes, mt.typeArguments()); } } catch(ClassNotFoundException cne) { syntax_error(cne.getMessage(),e,cne); } } } return e; } protected Expr doInvoke(Expr.Invoke e) { e.setTarget(doExpression(e.target())); List<Expr> parameters = e.parameters(); for(int i=0;i!=parameters.size();++i) { Expr p = parameters.get(i); parameters.set(i, doExpression(p)); } return e; } protected Expr doInstanceOf(Expr.InstanceOf e) { e.setLhs(doExpression(e.lhs())); return e; } protected Expr doCast(Expr.Cast e) { e.setExpr(doExpression(e.expr())); return e; } protected Expr doConvert(Expr.Convert e) { e.setExpr(doExpression(e.expr())); return e; } protected Expr doLocalVariable(Expr.LocalVariable e) { return e; } protected Expr doNonLocalVariable(Expr.NonLocalVariable e) { return e; } protected Expr doClassVariable(Expr.ClassVariable e) { return e; } protected Expr doBoolVal(Value.Bool e) { return e; } protected Expr doByteVal(Value.Byte e) { return e; } protected Expr doCharVal(Value.Char e) { return e; } protected Expr doShortVal(Value.Short e) { return e; } protected Expr doIntVal(Value.Int e) { return e; } protected Expr doLongVal(Value.Long e) { return e; } protected Expr doFloatVal(Value.Float e) { return e; } protected Expr doDoubleVal(Value.Double e) { return e; } protected Expr doStringVal(Value.String e) { return e; } protected Expr doNullVal(Value.Null e) { return e; } protected Expr doTypedArrayVal(Value.TypedArray e) { for(int i=0;i!=e.values().size();++i) { Expr v = e.values().get(i); e.values().set(i,doExpression(v)); } return e; } protected Expr doArrayVal(Value.Array e) { for(int i=0;i!=e.values().size();++i) { Expr v = e.values().get(i); e.values().set(i,doExpression(v)); } return e; } protected Expr doClassVal(Value.Class e) { return e; } protected Expr doUnOp(Expr.UnOp e) { e.setExpr(doExpression(e.expr())); return e; } protected Expr doBinOp(Expr.BinOp e) { e.setLhs(doExpression(e.lhs())); e.setRhs(doExpression(e.rhs())); return e; } protected Expr doTernOp(Expr.TernOp e) { e.setCondition(doExpression(e.condition())); e.setTrueBranch(doExpression(e.trueBranch())); e.setFalseBranch(doExpression(e.falseBranch())); return e; } /** * Test whether inner is a strict inner class of parent. * * @param inner * @param Parent */ protected boolean isStrictInnerClass(Type.Clazz inner, Type.Clazz parent) { if(!inner.pkg().equals(parent.pkg())) { return false; } if(inner.components().size() <= parent.components().size()) { return false; } for(int i=0;i!=parent.components().size();++i) { String parentName = parent.components().get(i).first(); String innerName = inner.components().get(i).first(); if(!parentName.equals(innerName)) { return false; } } return true; } /** * The purpose of this method is to add a parent pointer to the class in * question. This involves several things: firstly, we add the field with * the special name "this$0"; second, we modify every constructor to accept * it as the first parameter and then assign directly to the field; finally, * we update all skeletons accordingly. * * @param type * @param owner */ protected void addParentPtr(JavaClass owner, Type.Clazz ownerType, Type.Clazz parentType) throws ClassNotFoundException { SourceLocation loc = (SourceLocation) owner.attribute(SourceLocation.class); // First, update the source code for constructors String constructorName = owner.name(); for(Decl o : owner.declarations()) { if(o instanceof JavaMethod) { JavaMethod m = (JavaMethod) o; if(m.name().equals(constructorName)) { rewriteConstructor(m, ownerType, parentType, loc); } } } // Second, update the skeleton types. I know it's a JilClass here, since // it must be the skeleton for the enclosing class which I'm compiling! JilClass oc = (JilClass) loader.loadClass(ownerType); for(JilMethod m : oc.methods(owner.name())) { ArrayList<Type> nparams = new ArrayList<Type>(m.type().parameterTypes()); nparams.add(0,parentType); Type.Function ntype = new Type.Function(m.type().returnType(),nparams); m.setType(ntype); ArrayList<Modifier> mods = new ArrayList<Modifier>(); mods.add(new Modifier.Base(java.lang.reflect.Modifier.FINAL)); m.parameters().add(0, new Pair("this$0",mods)); } // Finally, add a field with the appropriate name. ArrayList<Modifier> modifiers = new ArrayList<Modifier>(); modifiers.add(new Modifier.Base(java.lang.reflect.Modifier.FINAL)); modifiers.add(new Modifier.Base(java.lang.reflect.Modifier.PRIVATE)); JilField field = new JilField("this$0", parentType, modifiers, loc); oc.fields().add(field); } protected void rewriteConstructor(JavaMethod constructor, Type.Clazz ownerType, Type.Clazz parentType, SourceLocation loc) { ArrayList<Modifier> mods = new ArrayList<Modifier>(); mods.add(new Modifier.Base(java.lang.reflect.Modifier.FINAL)); constructor.parameters().add(0, new Triple("this$0", mods, parentType)); Expr.LocalVariable param = new Expr.LocalVariable("this$0", parentType, loc); Expr.LocalVariable thiz = new Expr.LocalVariable("this", ownerType, loc); Expr.Deref lhs = new Expr.Deref(thiz, "this$0", parentType, loc); Stmt.Assignment assign = new Stmt.Assignment(lhs, param); constructor.body().statements().add(0, assign); // Now, update the inferred jil type for this method. Type.Function type = (Type.Function) constructor .attribute(Type.Function.class); ArrayList<Type> nparams = new ArrayList<Type>(type.parameterTypes()); nparams.add(0,parentType); constructor.attributes().remove(type); constructor.attributes().add(new Type.Function(type.returnType(),nparams)); } protected Clazz.Method createReadAccessor(Clazz.Field field, jkit.jil.tree.JilClass clazz) { // The first thing we need to do is check whether or not we've actually // created an accessor already. HashMap<String,JilMethod> accessors = readAccessors.get(clazz.type()); JilMethod accessor = null; if(accessors == null) { accessors = new HashMap<String,JilMethod>(); readAccessors.put(clazz.type(),accessors); } else { accessor = accessors.get(field.name()); } if(accessor == null) { // no, we haven't so construct one. List<Modifier> modifiers = new ArrayList<Modifier>(); JilExpr thisVar = null; ArrayList<Modifier> mods = new ArrayList<Modifier>(); mods.add(new Modifier.Base(java.lang.reflect.Modifier.FINAL)); ArrayList<Pair<String,List<Modifier>>> params = new ArrayList(); Type.Function ft; modifiers.add(new Modifier.Base(java.lang.reflect.Modifier.STATIC)); if(field.isStatic()) { thisVar = new JilExpr.ClassVariable(clazz.type()); ft = new Type.Function(field.type()); } else { thisVar = new JilExpr.Variable("thisp",clazz.type()); params.add(new Pair("thisp",mods)); ft = new Type.Function(field.type(),clazz.type()); } accessor = new JilMethod("access$" + accessors.size() + "00", ft, params, modifiers, new ArrayList<Type.Clazz>()); JilExpr expr = new JilExpr.Deref(thisVar, field.name(), field .isStatic(), field.type()); JilStmt stmt = new JilStmt.Return(expr,field.type()); accessor.body().add(stmt); accessors.put(field.name(),accessor); clazz.methods().add(accessor); } return accessor; } protected Clazz.Method createWriteAccessor(Clazz.Field field, jkit.jil.tree.JilClass clazz) { // The first thing we need to do is check whether or not we've actually // created an accessor already. HashMap<String,JilMethod> accessors = writeAccessors.get(clazz.type()); JilMethod accessor = null; if(accessors == null) { accessors = new HashMap<String,JilMethod>(); writeAccessors.put(clazz.type(),accessors); } else { accessor = accessors.get(field.name()); } if(accessor == null) { // no, we haven't so construct one. List<Modifier> modifiers = new ArrayList<Modifier>(); JilExpr thisVar = null; ArrayList<Modifier> mods = new ArrayList<Modifier>(); mods.add(new Modifier.Base(java.lang.reflect.Modifier.FINAL)); ArrayList<Pair<String,List<Modifier>>> params = new ArrayList(); Type.Function ft; modifiers.add(new Modifier.Base(java.lang.reflect.Modifier.STATIC)); if(field.isStatic()) { thisVar = new JilExpr.ClassVariable(clazz.type()); ft = new Type.Function(field.type(),field.type()); } else { thisVar = new JilExpr.Variable("thisp",clazz.type()); params.add(new Pair("thisp",mods)); ft = new Type.Function(field.type(),clazz.type(),field.type()); } params.add(new Pair("tmp",mods)); accessor = new JilMethod("access$" + accessors.size() + "02", ft, params, modifiers, new ArrayList<Type.Clazz>()); JilExpr tmpVar = new JilExpr.Variable("old", field.type()); JilStmt copy = new JilStmt.Assign(tmpVar, new JilExpr.Deref( thisVar, field.name(), field.isStatic(), field.type())); JilExpr lhs = new JilExpr.Deref(thisVar, field.name(), field .isStatic(), field.type()); JilStmt assign = new JilStmt.Assign(lhs, new JilExpr.Variable( "tmp", field.type())); JilStmt ret = new JilStmt.Return(tmpVar,field.type()); accessor.body().add(copy); accessor.body().add(assign); accessor.body().add(ret); accessors.put(field.name(),accessor); clazz.methods().add(accessor); } return accessor; } }
true
true
protected Expr doAssignment(Stmt.Assignment def) { // first, do the right-hand side def.setRhs(doExpression(def.rhs())); // second, so the left-hand side. if(def.lhs() instanceof Expr.Deref) { Expr.Deref e = (Expr.Deref) def.lhs(); Type tmp = (Type) e.target().attribute(Type.class); if(!(tmp instanceof Type.Reference) || tmp instanceof Type.Array) { // don't need to do anything in this case } else { Type.Clazz target = (Type.Clazz) tmp; if(e.name().equals("this")) { // This is a special case, where we're trying to look up a field // called "this". No such field can exist! What this means is that // we're inside an inner class, and we're trying to access the this // pointer of an enclosing class. This is easy to deal with here, // since the type returned by this expression will be the target // type of the dereference. // don't need to do anything here. } else { // now, perform field lookup! try { Triple<Clazz, Clazz.Field, Type> r = types .resolveField(target, e.name(), loader); Clazz.Field f = r.second(); Clazz c = r.first(); if (f.isPrivate() && isStrictInnerClass(enclosingClasses.peek(), c.type())) { // Ok, we have found a dereference of a field. This // means we need to add an accessor method, unless there // already is one. if(!(c instanceof jkit.jil.tree.JilClass)) { // it should be impossible to get here. syntax_error( "internal failure --- jil class required, found " + c.getClass().getName(), e); } ArrayList<jkit.jil.tree.Attribute> attributes = new ArrayList(e.attributes()); Clazz.Method accessor = createWriteAccessor(f, (jkit.jil.tree.JilClass) c); attributes.add(new JilBuilder.MethodInfo(accessor.exceptions(),accessor.type())); ArrayList<Expr> params = new ArrayList<Expr>(); params.add(def.rhs()); return new Expr.Invoke(new Expr.ClassVariable(c .type().toString(), c.type()), accessor .name(), params, new ArrayList(), attributes); } } catch(ClassNotFoundException cne) { syntax_error("class not found: " + target,e,cne); } catch(FieldNotFoundException fne) { syntax_error("field not found: " + target + "." + e.name(),e,fne); } } } } else { Expr lhs = doExpression(def.lhs()); def.setLhs(lhs); } return def; }
protected Expr doAssignment(Stmt.Assignment def) { // first, do the right-hand side def.setRhs(doExpression(def.rhs())); // second, so the left-hand side. if(def.lhs() instanceof Expr.Deref) { Expr.Deref e = (Expr.Deref) def.lhs(); Type tmp = (Type) e.target().attribute(Type.class); if(!(tmp instanceof Type.Reference) || tmp instanceof Type.Array) { // don't need to do anything in this case } else { Type.Clazz target = (Type.Clazz) tmp; if(e.name().equals("this")) { // This is a special case, where we're trying to look up a field // called "this". No such field can exist! What this means is that // we're inside an inner class, and we're trying to access the this // pointer of an enclosing class. This is easy to deal with here, // since the type returned by this expression will be the target // type of the dereference. // don't need to do anything here. } else { // now, perform field lookup! try { Triple<Clazz, Clazz.Field, Type> r = types .resolveField(target, e.name(), loader); Clazz.Field f = r.second(); Clazz c = r.first(); if (f.isPrivate() && isStrictInnerClass(enclosingClasses.peek(), c.type())) { // Ok, we have found a dereference of a field. This // means we need to add an accessor method, unless there // already is one. if(!(c instanceof jkit.jil.tree.JilClass)) { // it should be impossible to get here. syntax_error( "internal failure --- jil class required, found " + c.getClass().getName(), e); } ArrayList<jkit.jil.tree.Attribute> attributes = new ArrayList(e.attributes()); Clazz.Method accessor = createWriteAccessor(f, (jkit.jil.tree.JilClass) c); attributes.add(new JilBuilder.MethodInfo(accessor.exceptions(),accessor.type())); ArrayList<Expr> params = new ArrayList<Expr>(); params.add(e.target()); params.add(def.rhs()); return new Expr.Invoke(new Expr.ClassVariable(c .type().toString(), c.type()), accessor .name(), params, new ArrayList(), attributes); } } catch(ClassNotFoundException cne) { syntax_error("class not found: " + target,e,cne); } catch(FieldNotFoundException fne) { syntax_error("field not found: " + target + "." + e.name(),e,fne); } } } } else { Expr lhs = doExpression(def.lhs()); def.setLhs(lhs); } return def; }
diff --git a/src/com/dmdirc/ui/textpane/TextPaneCanvas.java b/src/com/dmdirc/ui/textpane/TextPaneCanvas.java index cb013637b..adee23dc9 100644 --- a/src/com/dmdirc/ui/textpane/TextPaneCanvas.java +++ b/src/com/dmdirc/ui/textpane/TextPaneCanvas.java @@ -1,498 +1,496 @@ /* * Copyright (c) 2006-2007 Chris Smith, Shane Mc Cormack, Gregory Holmes * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.dmdirc.ui.textpane; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Rectangle; import java.awt.Shape; import java.awt.event.MouseEvent; import java.awt.font.LineBreakMeasurer; import java.awt.font.TextLayout; import java.text.AttributedCharacterIterator; import java.text.AttributedCharacterIterator.Attribute; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import javax.swing.JPanel; import javax.swing.UIManager; import javax.swing.event.MouseInputListener; import com.dmdirc.ui.messages.Styliser; import java.util.regex.Pattern; /** Canvas object to draw text. */ class TextPaneCanvas extends JPanel implements MouseInputListener { /** * A version number for this class. It should be changed whenever the * class structure is changed (or anything else that would prevent * serialized objects being unserialized with the new class). */ private static final long serialVersionUID = 4; /** IRCDocument. */ private final IRCDocument document; /** parent textpane. */ private final TextPane textPane; /** Position -> TextLayout. */ private final Map<Rectangle, TextLayout> positions; /** TextLayout -> Line numbers. */ private final Map<TextLayout, LineInfo> textLayouts; /** Line number -> rectangle for lines containing hyperlinks. */ private final Map<TextLayout, Rectangle> hyperlinks; /** position of the scrollbar. */ private int scrollBarPosition; /** Start line of the selection. */ private int selStartLine; /** Start character of the selection. */ private int selStartChar; /** End line of the selection. */ private int selEndLine; /** End character of the selection. */ private int selEndChar; /** * Creates a new text pane canvas. * * @param parent parent text pane for the canvas * @param document IRCDocument to be displayed */ public TextPaneCanvas(final TextPane parent, final IRCDocument document) { super(); this.document = document; scrollBarPosition = 0; textPane = parent; this.setDoubleBuffered(true); this.setOpaque(true); textLayouts = new HashMap<TextLayout, LineInfo>(); positions = new HashMap<Rectangle, TextLayout>(); hyperlinks = new HashMap<TextLayout, Rectangle>(); this.addMouseListener(this); this.addMouseMotionListener(this); } /** * Paints the text onto the canvas. * @param g graphics object to draw onto */ public void paintComponent(final Graphics g) { final Graphics2D graphics2D = (Graphics2D) g; final float formatWidth = getWidth(); final float formatHeight = getHeight(); g.setColor(textPane.getBackground()); g.fillRect(0, 0, (int) formatWidth, (int) formatHeight); int paragraphStart; int paragraphEnd; LineBreakMeasurer lineMeasurer; boolean isHyperlink = false; textLayouts.clear(); positions.clear(); hyperlinks.clear(); float drawPosY = formatHeight; int startLine = scrollBarPosition; // Check the start line is in range if (startLine >= document.getNumLines()) { startLine = document.getNumLines() - 1; } if (startLine <= 0) { startLine = 0; } // We use these for drawing rather than the actual // sel{Start,End}{Line,Char} vars defined in the highlightEvent // This alllows for highlight in both directions. int useStartLine; int useStartChar; int useEndLine; int useEndChar; if (selStartLine > selEndLine) { // Swap both useStartLine = selEndLine; useStartChar = selEndChar; useEndLine = selStartLine; useEndChar = selStartChar; } else if (selStartLine == selEndLine && selStartChar > selEndChar) { // Just swap the chars useStartLine = selStartLine; useStartChar = selEndChar; useEndLine = selEndLine; useEndChar = selStartChar; } else { // Swap nothing useStartLine = selStartLine; useStartChar = selStartChar; useEndLine = selEndLine; useEndChar = selEndChar; } // Iterate through the lines if (document.getNumLines() > 0) { for (int i = startLine; i >= 0; i--) { final AttributedCharacterIterator iterator = document.getLine(i).getIterator(); paragraphStart = iterator.getBeginIndex(); paragraphEnd = iterator.getEndIndex(); lineMeasurer = new LineBreakMeasurer(iterator, ((Graphics2D) g).getFontRenderContext()); lineMeasurer.setPosition(paragraphStart); int wrappedLine = 0; int height = 0; int firstLineHeight = 0; // Work out the number of lines this will take while (lineMeasurer.getPosition() < paragraphEnd) { final TextLayout layout = lineMeasurer.nextLayout(formatWidth); if (wrappedLine == 0) { firstLineHeight = (int) (layout.getDescent() + layout.getLeading() + layout.getAscent()); } - height += layout.getDescent() + layout.getLeading() + layout.getAscent(); + height += firstLineHeight; wrappedLine++; } // Get back to the start lineMeasurer.setPosition(paragraphStart); paragraphStart = iterator.getBeginIndex(); paragraphEnd = iterator.getEndIndex(); if (wrappedLine > 1) { drawPosY -= height; } //Check if this line contains a hyperlink for (Attribute attr : iterator.getAllAttributeKeys()) { if (attr instanceof IRCTextAttribute) { isHyperlink = true; } } int j = 0; int chars = 0; // Loop through each wrapped line while (lineMeasurer.getPosition() < paragraphEnd) { final TextLayout layout = lineMeasurer.nextLayout(formatWidth); // Calculate the Y offset if (wrappedLine == 1) { - drawPosY -= layout.getDescent() + layout.getLeading() + layout.getAscent(); + drawPosY -= firstLineHeight; } else if (j != 0) { - drawPosY += layout.getDescent() + layout.getLeading() + layout.getAscent(); + drawPosY += firstLineHeight; } float drawPosX; // Calculate the initial X position if (layout.isLeftToRight()) { drawPosX = 0; } else { drawPosX = formatWidth - layout.getAdvance(); } // Check if the target is in range - if (drawPosY + layout.getAscent() >= 0 - || (drawPosY + layout.getDescent() + layout.getLeading()) <= formatHeight) { + if (drawPosY + layout.getAscent() + layout.getLeading() >= 0 + || (drawPosY + layout.getDescent()) <= formatHeight) { // If the selection includes this line if (useStartLine <= i && useEndLine >= i) { int firstChar; int lastChar; // Determine the first char we care about if (useStartLine < i || useStartChar < chars) { firstChar = chars; } else { firstChar = useStartChar; } // ... And the last if (useEndLine > i || useEndChar > chars + layout.getCharacterCount()) { lastChar = chars + layout.getCharacterCount(); } else { lastChar = useEndChar; } // If the selection includes the chars we're showing if (lastChar > chars && firstChar < chars + layout.getCharacterCount()) { final int trans = (int) (layout.getLeading() + layout.getAscent() + drawPosY); final Shape shape = layout.getLogicalHighlightShape(firstChar - chars, lastChar - chars); - graphics2D.setColor(UIManager.getColor("TextPane.selectionForeground")); - graphics2D.setBackground(UIManager.getColor("TextPane.selectionBackground")); + graphics2D.setColor(UIManager.getColor("TextPane.selectionBackground")); + graphics2D.setBackground(UIManager.getColor("TextPane.selectionForeground")); graphics2D.translate(0, trans); graphics2D.fill(shape); graphics2D.translate(0, -1 * trans); } } graphics2D.setColor(Color.BLACK); layout.draw(graphics2D, drawPosX, drawPosY + layout.getAscent()); textLayouts.put(layout, new LineInfo(i, j)); positions.put(new Rectangle( - (int) drawPosX, (int) drawPosY, (int) formatHeight, - (int) (layout.getDescent() + layout.getLeading() + layout.getAscent()) - ), layout); + (int) drawPosX, (int) drawPosY, + (int) formatHeight, firstLineHeight), layout); if (isHyperlink) { - hyperlinks.put(layout, new Rectangle((int) drawPosX, (int) drawPosY, - (int) formatWidth, - (int) (layout.getDescent() + layout.getLeading() + layout.getAscent()))); + hyperlinks.put(layout, new Rectangle((int) drawPosX, + (int) drawPosY, (int) formatWidth, firstLineHeight)); } } j++; chars += layout.getCharacterCount(); } if (j > 1) { drawPosY -= height - firstLineHeight; } if (drawPosY <= 0) { break; } } } } /** * sets the position of the scroll bar, and repaints if required. * @param position scroll bar position */ protected void setScrollBarPosition(final int position) { if (scrollBarPosition != position) { scrollBarPosition = position; if (textPane.isVisible()) { repaint(); } } } /** {@inheritDoc}. */ public void mouseClicked(final MouseEvent e) { String clickedText = ""; int start = -1; int end = -1; final int[] info = getClickPosition(this.getMousePosition()); clickedText = textPane.getTextFromLine(info[0]); start = info[2]; end = info[2]; if (start != -1 || end != -1) { // Traverse backwards while (start > 0 && start < clickedText.length() && clickedText.charAt(start) != ' ') { start--; } if (start + 1 < clickedText.length() && clickedText.charAt(start) == ' ') { start++; } // And forwards while (end < clickedText.length() && end > 0 && clickedText.charAt(end) != ' ') { end++; } checkClickedText(clickedText.substring(start, end)); } e.setSource(textPane); textPane.dispatchEvent(e); } /** {@inheritDoc}. */ public void mousePressed(final MouseEvent e) { if (e.getButton() == e.BUTTON1) { highlightEvent(true, e); } e.setSource(textPane); textPane.dispatchEvent(e); } /** {@inheritDoc}. */ public void mouseReleased(final MouseEvent e) { if (e.getButton() == e.BUTTON1) { highlightEvent(false, e); } e.setSource(textPane); textPane.dispatchEvent(e); } /** {@inheritDoc}. */ public void mouseEntered(final MouseEvent e) { //Ignore } /** {@inheritDoc}. */ public void mouseExited(final MouseEvent e) { //Ignore } /** {@inheritDoc}. */ public void mouseDragged(final MouseEvent e) { highlightEvent(false, e); e.setSource(textPane); textPane.dispatchEvent(e); } /** {@inheritDoc}. */ public void mouseMoved(final MouseEvent e) { //Ignore } /** * Sets the selection for the given event. * * @param start true = start * @param e responsible mouse event */ private void highlightEvent(final boolean start, final MouseEvent e) { final Point point = this.getMousePosition(); if (point == null) { if (getLocationOnScreen().getY() > e.getYOnScreen()) { textPane.setScrollBarPosition(scrollBarPosition - 1); } else { textPane.setScrollBarPosition(scrollBarPosition + 1); } } else { final int[] info = getClickPosition(point); if (info[0] != -1 && info[1] != -1) { if (start) { selStartLine = info[0]; selStartChar = info[2]; } selEndLine = info[0]; selEndChar = info[2]; this.repaint(); } } } /** * Checks the clicked text and fires the appropriate events. * * @param clickedText Text clicked */ public void checkClickedText(final String clickedText) { final Matcher matcher = Pattern.compile(Styliser.URL_REGEXP).matcher(clickedText); if (matcher.find()) { fireHyperlinkClicked(matcher.group()); } else if (textPane.isValidChannel(clickedText)) { fireChannelClicked(clickedText); } } /** * * Returns the line information from a mouse click inside the textpane. * * @param point mouse position * * @return line number, line part, position in whole line */ public int[] getClickPosition(final Point point) { int lineNumber = -1; int linePart = -1; int pos = 0; if (point != null) { for (Map.Entry<Rectangle, TextLayout> entry : positions.entrySet()) { if (entry.getKey().contains(point)) { lineNumber = textLayouts.get(entry.getValue()).getLine(); linePart = textLayouts.get(entry.getValue()).getPart(); } } for (Map.Entry<Rectangle, TextLayout> entry : positions.entrySet()) { if (textLayouts.get(entry.getValue()).getLine() == lineNumber) { if (textLayouts.get(entry.getValue()).getPart() < linePart) { pos += entry.getValue().getCharacterCount(); } else if (textLayouts.get(entry.getValue()).getPart() == linePart) { pos += entry.getValue().hitTestChar((int) point.getX(), (int) point.getY()).getInsertionIndex(); } } } } return new int[]{lineNumber, linePart, pos}; } /** * Informs listeners when a word has been clicked on. * @param text word clicked on */ private void fireHyperlinkClicked(final String text) { textPane.fireChannelClicked(text); } /** * Informs listeners when a word has been clicked on. * @param text word clicked on */ private void fireChannelClicked(final String text) { textPane.fireChannelClicked(text); } /** * Returns the selected range info. * <ul> * <li>0 = start line</li> * <li>1 = start char</li> * <li>2 = end line</li> * <li>3 = end char</li> * </ul> * * @return Selected range info */ protected int[] getSelectedRange() { if (selStartLine > selEndLine) { // Swap both return new int[]{selEndLine, selEndChar, selStartLine, selStartChar, }; } else if (selStartLine == selEndLine && selStartChar > selEndChar) { // Just swap the chars return new int[]{selStartLine, selEndChar, selEndLine, selStartChar, }; } else { // Swap nothing return new int[]{selStartLine, selStartChar, selEndLine, selEndChar, }; } } /** Clears the selection. */ protected void clearSelection() { selEndLine = selStartLine; selEndChar = selStartChar; } }
false
true
public void paintComponent(final Graphics g) { final Graphics2D graphics2D = (Graphics2D) g; final float formatWidth = getWidth(); final float formatHeight = getHeight(); g.setColor(textPane.getBackground()); g.fillRect(0, 0, (int) formatWidth, (int) formatHeight); int paragraphStart; int paragraphEnd; LineBreakMeasurer lineMeasurer; boolean isHyperlink = false; textLayouts.clear(); positions.clear(); hyperlinks.clear(); float drawPosY = formatHeight; int startLine = scrollBarPosition; // Check the start line is in range if (startLine >= document.getNumLines()) { startLine = document.getNumLines() - 1; } if (startLine <= 0) { startLine = 0; } // We use these for drawing rather than the actual // sel{Start,End}{Line,Char} vars defined in the highlightEvent // This alllows for highlight in both directions. int useStartLine; int useStartChar; int useEndLine; int useEndChar; if (selStartLine > selEndLine) { // Swap both useStartLine = selEndLine; useStartChar = selEndChar; useEndLine = selStartLine; useEndChar = selStartChar; } else if (selStartLine == selEndLine && selStartChar > selEndChar) { // Just swap the chars useStartLine = selStartLine; useStartChar = selEndChar; useEndLine = selEndLine; useEndChar = selStartChar; } else { // Swap nothing useStartLine = selStartLine; useStartChar = selStartChar; useEndLine = selEndLine; useEndChar = selEndChar; } // Iterate through the lines if (document.getNumLines() > 0) { for (int i = startLine; i >= 0; i--) { final AttributedCharacterIterator iterator = document.getLine(i).getIterator(); paragraphStart = iterator.getBeginIndex(); paragraphEnd = iterator.getEndIndex(); lineMeasurer = new LineBreakMeasurer(iterator, ((Graphics2D) g).getFontRenderContext()); lineMeasurer.setPosition(paragraphStart); int wrappedLine = 0; int height = 0; int firstLineHeight = 0; // Work out the number of lines this will take while (lineMeasurer.getPosition() < paragraphEnd) { final TextLayout layout = lineMeasurer.nextLayout(formatWidth); if (wrappedLine == 0) { firstLineHeight = (int) (layout.getDescent() + layout.getLeading() + layout.getAscent()); } height += layout.getDescent() + layout.getLeading() + layout.getAscent(); wrappedLine++; } // Get back to the start lineMeasurer.setPosition(paragraphStart); paragraphStart = iterator.getBeginIndex(); paragraphEnd = iterator.getEndIndex(); if (wrappedLine > 1) { drawPosY -= height; } //Check if this line contains a hyperlink for (Attribute attr : iterator.getAllAttributeKeys()) { if (attr instanceof IRCTextAttribute) { isHyperlink = true; } } int j = 0; int chars = 0; // Loop through each wrapped line while (lineMeasurer.getPosition() < paragraphEnd) { final TextLayout layout = lineMeasurer.nextLayout(formatWidth); // Calculate the Y offset if (wrappedLine == 1) { drawPosY -= layout.getDescent() + layout.getLeading() + layout.getAscent(); } else if (j != 0) { drawPosY += layout.getDescent() + layout.getLeading() + layout.getAscent(); } float drawPosX; // Calculate the initial X position if (layout.isLeftToRight()) { drawPosX = 0; } else { drawPosX = formatWidth - layout.getAdvance(); } // Check if the target is in range if (drawPosY + layout.getAscent() >= 0 || (drawPosY + layout.getDescent() + layout.getLeading()) <= formatHeight) { // If the selection includes this line if (useStartLine <= i && useEndLine >= i) { int firstChar; int lastChar; // Determine the first char we care about if (useStartLine < i || useStartChar < chars) { firstChar = chars; } else { firstChar = useStartChar; } // ... And the last if (useEndLine > i || useEndChar > chars + layout.getCharacterCount()) { lastChar = chars + layout.getCharacterCount(); } else { lastChar = useEndChar; } // If the selection includes the chars we're showing if (lastChar > chars && firstChar < chars + layout.getCharacterCount()) { final int trans = (int) (layout.getLeading() + layout.getAscent() + drawPosY); final Shape shape = layout.getLogicalHighlightShape(firstChar - chars, lastChar - chars); graphics2D.setColor(UIManager.getColor("TextPane.selectionForeground")); graphics2D.setBackground(UIManager.getColor("TextPane.selectionBackground")); graphics2D.translate(0, trans); graphics2D.fill(shape); graphics2D.translate(0, -1 * trans); } } graphics2D.setColor(Color.BLACK); layout.draw(graphics2D, drawPosX, drawPosY + layout.getAscent()); textLayouts.put(layout, new LineInfo(i, j)); positions.put(new Rectangle( (int) drawPosX, (int) drawPosY, (int) formatHeight, (int) (layout.getDescent() + layout.getLeading() + layout.getAscent()) ), layout); if (isHyperlink) { hyperlinks.put(layout, new Rectangle((int) drawPosX, (int) drawPosY, (int) formatWidth, (int) (layout.getDescent() + layout.getLeading() + layout.getAscent()))); } } j++; chars += layout.getCharacterCount(); } if (j > 1) { drawPosY -= height - firstLineHeight; } if (drawPosY <= 0) { break; } } } }
public void paintComponent(final Graphics g) { final Graphics2D graphics2D = (Graphics2D) g; final float formatWidth = getWidth(); final float formatHeight = getHeight(); g.setColor(textPane.getBackground()); g.fillRect(0, 0, (int) formatWidth, (int) formatHeight); int paragraphStart; int paragraphEnd; LineBreakMeasurer lineMeasurer; boolean isHyperlink = false; textLayouts.clear(); positions.clear(); hyperlinks.clear(); float drawPosY = formatHeight; int startLine = scrollBarPosition; // Check the start line is in range if (startLine >= document.getNumLines()) { startLine = document.getNumLines() - 1; } if (startLine <= 0) { startLine = 0; } // We use these for drawing rather than the actual // sel{Start,End}{Line,Char} vars defined in the highlightEvent // This alllows for highlight in both directions. int useStartLine; int useStartChar; int useEndLine; int useEndChar; if (selStartLine > selEndLine) { // Swap both useStartLine = selEndLine; useStartChar = selEndChar; useEndLine = selStartLine; useEndChar = selStartChar; } else if (selStartLine == selEndLine && selStartChar > selEndChar) { // Just swap the chars useStartLine = selStartLine; useStartChar = selEndChar; useEndLine = selEndLine; useEndChar = selStartChar; } else { // Swap nothing useStartLine = selStartLine; useStartChar = selStartChar; useEndLine = selEndLine; useEndChar = selEndChar; } // Iterate through the lines if (document.getNumLines() > 0) { for (int i = startLine; i >= 0; i--) { final AttributedCharacterIterator iterator = document.getLine(i).getIterator(); paragraphStart = iterator.getBeginIndex(); paragraphEnd = iterator.getEndIndex(); lineMeasurer = new LineBreakMeasurer(iterator, ((Graphics2D) g).getFontRenderContext()); lineMeasurer.setPosition(paragraphStart); int wrappedLine = 0; int height = 0; int firstLineHeight = 0; // Work out the number of lines this will take while (lineMeasurer.getPosition() < paragraphEnd) { final TextLayout layout = lineMeasurer.nextLayout(formatWidth); if (wrappedLine == 0) { firstLineHeight = (int) (layout.getDescent() + layout.getLeading() + layout.getAscent()); } height += firstLineHeight; wrappedLine++; } // Get back to the start lineMeasurer.setPosition(paragraphStart); paragraphStart = iterator.getBeginIndex(); paragraphEnd = iterator.getEndIndex(); if (wrappedLine > 1) { drawPosY -= height; } //Check if this line contains a hyperlink for (Attribute attr : iterator.getAllAttributeKeys()) { if (attr instanceof IRCTextAttribute) { isHyperlink = true; } } int j = 0; int chars = 0; // Loop through each wrapped line while (lineMeasurer.getPosition() < paragraphEnd) { final TextLayout layout = lineMeasurer.nextLayout(formatWidth); // Calculate the Y offset if (wrappedLine == 1) { drawPosY -= firstLineHeight; } else if (j != 0) { drawPosY += firstLineHeight; } float drawPosX; // Calculate the initial X position if (layout.isLeftToRight()) { drawPosX = 0; } else { drawPosX = formatWidth - layout.getAdvance(); } // Check if the target is in range if (drawPosY + layout.getAscent() + layout.getLeading() >= 0 || (drawPosY + layout.getDescent()) <= formatHeight) { // If the selection includes this line if (useStartLine <= i && useEndLine >= i) { int firstChar; int lastChar; // Determine the first char we care about if (useStartLine < i || useStartChar < chars) { firstChar = chars; } else { firstChar = useStartChar; } // ... And the last if (useEndLine > i || useEndChar > chars + layout.getCharacterCount()) { lastChar = chars + layout.getCharacterCount(); } else { lastChar = useEndChar; } // If the selection includes the chars we're showing if (lastChar > chars && firstChar < chars + layout.getCharacterCount()) { final int trans = (int) (layout.getLeading() + layout.getAscent() + drawPosY); final Shape shape = layout.getLogicalHighlightShape(firstChar - chars, lastChar - chars); graphics2D.setColor(UIManager.getColor("TextPane.selectionBackground")); graphics2D.setBackground(UIManager.getColor("TextPane.selectionForeground")); graphics2D.translate(0, trans); graphics2D.fill(shape); graphics2D.translate(0, -1 * trans); } } graphics2D.setColor(Color.BLACK); layout.draw(graphics2D, drawPosX, drawPosY + layout.getAscent()); textLayouts.put(layout, new LineInfo(i, j)); positions.put(new Rectangle( (int) drawPosX, (int) drawPosY, (int) formatHeight, firstLineHeight), layout); if (isHyperlink) { hyperlinks.put(layout, new Rectangle((int) drawPosX, (int) drawPosY, (int) formatWidth, firstLineHeight)); } } j++; chars += layout.getCharacterCount(); } if (j > 1) { drawPosY -= height - firstLineHeight; } if (drawPosY <= 0) { break; } } } }
diff --git a/studio-connection-core/src/main/java/org/apache/directory/studio/connection/core/io/ConnectionIO.java b/studio-connection-core/src/main/java/org/apache/directory/studio/connection/core/io/ConnectionIO.java index d65b37318..ed573edad 100644 --- a/studio-connection-core/src/main/java/org/apache/directory/studio/connection/core/io/ConnectionIO.java +++ b/studio-connection-core/src/main/java/org/apache/directory/studio/connection/core/io/ConnectionIO.java @@ -1,362 +1,362 @@ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.directory.studio.connection.core.io; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamSource; import org.apache.directory.studio.connection.core.ConnectionCorePlugin; import org.apache.directory.studio.connection.core.ConnectionParameter; import org.apache.directory.studio.connection.core.ConnectionParameter.AuthenticationMethod; import org.apache.directory.studio.connection.core.ConnectionParameter.EncryptionMethod; import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.DocumentResult; import org.dom4j.io.DocumentSource; import org.dom4j.io.SAXReader; /** * This class is used to read/write the 'connections.xml' file. * * @author <a href="mailto:[email protected]">Apache Directory Project</a> * @version $Rev$, $Date$ */ public class ConnectionIO { // XML tags private static final String CONNECTIONS_TAG = "connections"; private static final String CONNECTION_TAG = "connection"; private static final String ID_TAG = "id"; private static final String NAME_TAG = "name"; private static final String HOST_TAG = "host"; private static final String PORT_TAG = "port"; private static final String ENCRYPTION_METHOD_TAG = "encryptionMethod"; private static final String AUTH_METHOD_TAG = "authMethod"; private static final String BIND_PRINCIPAL_TAG = "bindPrincipal"; private static final String BIND_PASSWORD_TAG = "bindPassword"; private static final String EXTENDED_PROPERTIES_TAG = "extendedProperties"; private static final String EXTENDED_PROPERTY_TAG = "extendedProperty"; private static final String KEY_TAG = "key"; private static final String VALUE_TAG = "value"; /** * Loads the connections using the reader * * @param reader * the reader * @return * the connections * @throws ConnectionIOException * if an error occurs when converting the document */ public static List<ConnectionParameter> load( FileReader reader ) throws ConnectionIOException { List<ConnectionParameter> connections = new ArrayList<ConnectionParameter>(); SAXReader saxReader = new SAXReader(); Document document = null; try { document = saxReader.read( reader ); } catch ( DocumentException e ) { throw new ConnectionIOException( e.getMessage() ); } Element rootElement = document.getRootElement(); if ( !rootElement.getName().equals( CONNECTIONS_TAG ) ) { throw new ConnectionIOException( "The file does not seem to be a valid Connections file." ); } for ( Iterator<?> i = rootElement.elementIterator( CONNECTION_TAG ); i.hasNext(); ) { Element connectionElement = ( Element ) i.next(); connections.add( readConnection( connectionElement ) ); } return connections; } /** * Reads a connection from the given Element. * * @param element * the element * @return * the corresponding connection * @throws ConnectionIOException * if an error occurs when converting values */ private static ConnectionParameter readConnection( Element element ) throws ConnectionIOException { ConnectionParameter connection = new ConnectionParameter(); // ID Attribute idAttribute = element.attribute( ID_TAG ); if ( idAttribute != null ) { connection.setId( idAttribute.getValue() ); } // Name Attribute nameAttribute = element.attribute( NAME_TAG ); if ( nameAttribute != null ) { connection.setName( nameAttribute.getValue() ); } // Host Attribute hostAttribute = element.attribute( HOST_TAG ); if ( hostAttribute != null ) { connection.setHost( hostAttribute.getValue() ); } // Port Attribute portAttribute = element.attribute( PORT_TAG ); if ( portAttribute != null ) { try { connection.setPort( Integer.parseInt( portAttribute.getValue() ) ); } catch ( NumberFormatException e ) { throw new ConnectionIOException( "Unable to parse 'Port' of connection '" + connection.getName() + "' as int value. Port value :" + portAttribute.getValue() ); } } // Encryption Method Attribute encryptionMethodAttribute = element.attribute( ENCRYPTION_METHOD_TAG ); if ( encryptionMethodAttribute != null ) { try { connection.setEncryptionMethod( EncryptionMethod.valueOf( encryptionMethodAttribute.getValue() ) ); } catch ( IllegalArgumentException e ) { throw new ConnectionIOException( "Unable to parse 'Encryption Method' of connection '" + connection.getName() + "' as int value. Encryption Method value :" + encryptionMethodAttribute.getValue() ); } } // Auth Method Attribute authMethodAttribute = element.attribute( AUTH_METHOD_TAG ); if ( authMethodAttribute != null ) { try { connection.setAuthMethod( AuthenticationMethod.valueOf( authMethodAttribute.getValue() ) ); } catch ( IllegalArgumentException e ) { throw new ConnectionIOException( "Unable to parse 'Authentication Method' of connection '" + connection.getName() + "' as int value. Authentication Method value :" + authMethodAttribute.getValue() ); } } // Bind Principal Attribute bindPrincipalAttribute = element.attribute( BIND_PRINCIPAL_TAG ); if ( bindPrincipalAttribute != null ) { connection.setBindPrincipal( bindPrincipalAttribute.getValue() ); } // Bind Password Attribute bindPasswordAttribute = element.attribute( BIND_PASSWORD_TAG ); if ( bindPasswordAttribute != null ) { connection.setBindPassword( bindPasswordAttribute.getValue() ); } // Extended Properties Element extendedPropertiesElement = element.element( EXTENDED_PROPERTIES_TAG ); if ( extendedPropertiesElement != null ) { for ( Iterator<?> i = extendedPropertiesElement.elementIterator( EXTENDED_PROPERTY_TAG ); i.hasNext(); ) { Element extendedPropertyElement = ( Element ) i.next(); Attribute keyAttribute = extendedPropertyElement.attribute( KEY_TAG ); Attribute valueAttribute = extendedPropertyElement.attribute( VALUE_TAG ); - if ( keyAttribute != null ) + if ( keyAttribute != null && valueAttribute != null ) { connection.setExtendedProperty( keyAttribute.getValue(), valueAttribute.getValue() ); } } } return connection; } /** * Saves the connections using the writer. * * @param connections * the connections * @param writer * the writer * @throws IOException * if an I/O error occurs */ public static void save( List<ConnectionParameter> connections, FileWriter writer ) throws IOException { // Creating the Document Document document = DocumentHelper.createDocument(); // Creating the root element Element root = document.addElement( CONNECTIONS_TAG ); if ( connections != null ) { for ( ConnectionParameter connection : connections ) { addConnection( root, connection ); } } // Writing the file to disk BufferedWriter buffWriter = new BufferedWriter( writer ); buffWriter.write( styleDocument( document ).asXML() ); buffWriter.close(); } /** * Adds the given connection to the given parent Element. * * @param parent * the parent Element * @param connection * the connection */ private static void addConnection( Element parent, ConnectionParameter connection ) { Element connectionElement = parent.addElement( CONNECTION_TAG ); // ID connectionElement.addAttribute( ID_TAG, connection.getId() ); // Name connectionElement.addAttribute( NAME_TAG, connection.getName() ); // Host connectionElement.addAttribute( HOST_TAG, connection.getHost() ); // Port connectionElement.addAttribute( PORT_TAG, "" + connection.getPort() ); // Encryption Method connectionElement.addAttribute( ENCRYPTION_METHOD_TAG, connection.getEncryptionMethod().toString() ); // Auth Method connectionElement.addAttribute( AUTH_METHOD_TAG, connection.getAuthMethod().toString() ); // Bind Principal connectionElement.addAttribute( BIND_PRINCIPAL_TAG, connection.getBindPrincipal() ); // Bind Password connectionElement.addAttribute( BIND_PASSWORD_TAG, connection.getBindPassword() ); // Extended Properties Element extendedPropertiesElement = connectionElement.addElement( EXTENDED_PROPERTIES_TAG ); Map<String, String> extendedProperties = connection.getExtendedProperties(); if ( extendedProperties != null ) { for ( Iterator<Entry<String, String>> iter = extendedProperties.entrySet().iterator(); iter.hasNext(); ) { Map.Entry<String, String> element = ( Map.Entry<String, String> ) iter.next(); Element extendedPropertyElement = extendedPropertiesElement.addElement( EXTENDED_PROPERTY_TAG ); extendedPropertyElement.addAttribute( KEY_TAG, element.getKey() ); extendedPropertyElement.addAttribute( VALUE_TAG, element.getValue() ); } } } /** * XML Pretty Printer XSLT Transformation * * @param document * the Dom4j Document * @return */ private static Document styleDocument( Document document ) { // load the transformer using JAXP TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = null; try { transformer = factory.newTransformer( new StreamSource( ConnectionCorePlugin.class .getResourceAsStream( "XmlFileFormat.xslt" ) ) ); } catch ( TransformerConfigurationException e1 ) { // Will never occur } // now lets style the given document DocumentSource source = new DocumentSource( document ); DocumentResult result = new DocumentResult(); try { transformer.transform( source, result ); } catch ( TransformerException e ) { // Will never occur } // return the transformed document Document transformedDoc = result.getDocument(); return transformedDoc; } }
true
true
private static ConnectionParameter readConnection( Element element ) throws ConnectionIOException { ConnectionParameter connection = new ConnectionParameter(); // ID Attribute idAttribute = element.attribute( ID_TAG ); if ( idAttribute != null ) { connection.setId( idAttribute.getValue() ); } // Name Attribute nameAttribute = element.attribute( NAME_TAG ); if ( nameAttribute != null ) { connection.setName( nameAttribute.getValue() ); } // Host Attribute hostAttribute = element.attribute( HOST_TAG ); if ( hostAttribute != null ) { connection.setHost( hostAttribute.getValue() ); } // Port Attribute portAttribute = element.attribute( PORT_TAG ); if ( portAttribute != null ) { try { connection.setPort( Integer.parseInt( portAttribute.getValue() ) ); } catch ( NumberFormatException e ) { throw new ConnectionIOException( "Unable to parse 'Port' of connection '" + connection.getName() + "' as int value. Port value :" + portAttribute.getValue() ); } } // Encryption Method Attribute encryptionMethodAttribute = element.attribute( ENCRYPTION_METHOD_TAG ); if ( encryptionMethodAttribute != null ) { try { connection.setEncryptionMethod( EncryptionMethod.valueOf( encryptionMethodAttribute.getValue() ) ); } catch ( IllegalArgumentException e ) { throw new ConnectionIOException( "Unable to parse 'Encryption Method' of connection '" + connection.getName() + "' as int value. Encryption Method value :" + encryptionMethodAttribute.getValue() ); } } // Auth Method Attribute authMethodAttribute = element.attribute( AUTH_METHOD_TAG ); if ( authMethodAttribute != null ) { try { connection.setAuthMethod( AuthenticationMethod.valueOf( authMethodAttribute.getValue() ) ); } catch ( IllegalArgumentException e ) { throw new ConnectionIOException( "Unable to parse 'Authentication Method' of connection '" + connection.getName() + "' as int value. Authentication Method value :" + authMethodAttribute.getValue() ); } } // Bind Principal Attribute bindPrincipalAttribute = element.attribute( BIND_PRINCIPAL_TAG ); if ( bindPrincipalAttribute != null ) { connection.setBindPrincipal( bindPrincipalAttribute.getValue() ); } // Bind Password Attribute bindPasswordAttribute = element.attribute( BIND_PASSWORD_TAG ); if ( bindPasswordAttribute != null ) { connection.setBindPassword( bindPasswordAttribute.getValue() ); } // Extended Properties Element extendedPropertiesElement = element.element( EXTENDED_PROPERTIES_TAG ); if ( extendedPropertiesElement != null ) { for ( Iterator<?> i = extendedPropertiesElement.elementIterator( EXTENDED_PROPERTY_TAG ); i.hasNext(); ) { Element extendedPropertyElement = ( Element ) i.next(); Attribute keyAttribute = extendedPropertyElement.attribute( KEY_TAG ); Attribute valueAttribute = extendedPropertyElement.attribute( VALUE_TAG ); if ( keyAttribute != null ) { connection.setExtendedProperty( keyAttribute.getValue(), valueAttribute.getValue() ); } } } return connection; }
private static ConnectionParameter readConnection( Element element ) throws ConnectionIOException { ConnectionParameter connection = new ConnectionParameter(); // ID Attribute idAttribute = element.attribute( ID_TAG ); if ( idAttribute != null ) { connection.setId( idAttribute.getValue() ); } // Name Attribute nameAttribute = element.attribute( NAME_TAG ); if ( nameAttribute != null ) { connection.setName( nameAttribute.getValue() ); } // Host Attribute hostAttribute = element.attribute( HOST_TAG ); if ( hostAttribute != null ) { connection.setHost( hostAttribute.getValue() ); } // Port Attribute portAttribute = element.attribute( PORT_TAG ); if ( portAttribute != null ) { try { connection.setPort( Integer.parseInt( portAttribute.getValue() ) ); } catch ( NumberFormatException e ) { throw new ConnectionIOException( "Unable to parse 'Port' of connection '" + connection.getName() + "' as int value. Port value :" + portAttribute.getValue() ); } } // Encryption Method Attribute encryptionMethodAttribute = element.attribute( ENCRYPTION_METHOD_TAG ); if ( encryptionMethodAttribute != null ) { try { connection.setEncryptionMethod( EncryptionMethod.valueOf( encryptionMethodAttribute.getValue() ) ); } catch ( IllegalArgumentException e ) { throw new ConnectionIOException( "Unable to parse 'Encryption Method' of connection '" + connection.getName() + "' as int value. Encryption Method value :" + encryptionMethodAttribute.getValue() ); } } // Auth Method Attribute authMethodAttribute = element.attribute( AUTH_METHOD_TAG ); if ( authMethodAttribute != null ) { try { connection.setAuthMethod( AuthenticationMethod.valueOf( authMethodAttribute.getValue() ) ); } catch ( IllegalArgumentException e ) { throw new ConnectionIOException( "Unable to parse 'Authentication Method' of connection '" + connection.getName() + "' as int value. Authentication Method value :" + authMethodAttribute.getValue() ); } } // Bind Principal Attribute bindPrincipalAttribute = element.attribute( BIND_PRINCIPAL_TAG ); if ( bindPrincipalAttribute != null ) { connection.setBindPrincipal( bindPrincipalAttribute.getValue() ); } // Bind Password Attribute bindPasswordAttribute = element.attribute( BIND_PASSWORD_TAG ); if ( bindPasswordAttribute != null ) { connection.setBindPassword( bindPasswordAttribute.getValue() ); } // Extended Properties Element extendedPropertiesElement = element.element( EXTENDED_PROPERTIES_TAG ); if ( extendedPropertiesElement != null ) { for ( Iterator<?> i = extendedPropertiesElement.elementIterator( EXTENDED_PROPERTY_TAG ); i.hasNext(); ) { Element extendedPropertyElement = ( Element ) i.next(); Attribute keyAttribute = extendedPropertyElement.attribute( KEY_TAG ); Attribute valueAttribute = extendedPropertyElement.attribute( VALUE_TAG ); if ( keyAttribute != null && valueAttribute != null ) { connection.setExtendedProperty( keyAttribute.getValue(), valueAttribute.getValue() ); } } } return connection; }
diff --git a/xmlimplsrc/org/mozilla/javascript/xmlimpl/XMLList.java b/xmlimplsrc/org/mozilla/javascript/xmlimpl/XMLList.java index 1dd4118b..48f92cab 100644 --- a/xmlimplsrc/org/mozilla/javascript/xmlimpl/XMLList.java +++ b/xmlimplsrc/org/mozilla/javascript/xmlimpl/XMLList.java @@ -1,763 +1,768 @@ /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-2000 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Ethan Hugg * Terry Lucas * Milen Nankov * David P. Caldwell <[email protected]> * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.xmlimpl; import org.mozilla.javascript.*; import org.mozilla.javascript.xml.*; class XMLList extends XMLObjectImpl implements Function { static final long serialVersionUID = -4543618751670781135L; // Fields private XmlNode.List _annos; private XMLObjectImpl targetObject = null; private XmlNode.QName targetProperty = null; XMLList() { _annos = new XmlNode.List(); } /** @deprecated Will probably end up unnecessary as we move things around */ XmlNode.List getNodeList() { return _annos; } // TODO Should be XMLObjectImpl, XMLName? void setTargets(XMLObjectImpl object, XmlNode.QName property) { targetObject = object; targetProperty = property; } /** @deprecated */ private XML getXmlFromAnnotation(int index) { return getXML(_annos, index); } XML XML() { if (length() == 1) return getXmlFromAnnotation(0); return null; } private void internalRemoveFromList(int index) { _annos.remove(index); } void replace(int index, XML xml) { if (index < length()) { XmlNode.List newAnnoList = new XmlNode.List(); newAnnoList.add(_annos, 0, index); newAnnoList.add(xml); newAnnoList.add(_annos, index+1, length()); _annos = newAnnoList; } } private void insert(int index, XML xml) { if (index < length()) { XmlNode.List newAnnoList = new XmlNode.List(); newAnnoList.add(_annos, 0, index); newAnnoList.add(xml); newAnnoList.add(_annos, index, length()); _annos = newAnnoList; } } // // // methods overriding ScriptableObject // // public String getClassName() { return "XMLList"; } // // // methods overriding IdScriptableObject // // public Object get(int index, Scriptable start) { //Log("get index: " + index); if (index >= 0 && index < length()) { return getXmlFromAnnotation(index); } else { return Scriptable.NOT_FOUND; } } boolean hasXMLProperty(XMLName xmlName) { boolean result = false; // Has now should return true if the property would have results > 0 or // if it's a method name String name = xmlName.localName(); if ((getPropertyList(xmlName).length() > 0) || (getMethod(name) != NOT_FOUND)) { result = true; } return result; } public boolean has(int index, Scriptable start) { return 0 <= index && index < length(); } void putXMLProperty(XMLName xmlName, Object value) { //Log("put property: " + name); // Special-case checks for undefined and null if (value == null) { value = "null"; } else if (value instanceof Undefined) { value = "undefined"; } if (length() > 1) { throw ScriptRuntime.typeError("Assignment to lists with more than one item is not supported"); } else if (length() == 0) { // Secret sauce for super-expandos. // We set an element here, and then add ourselves to our target. if (targetObject != null && targetProperty != null && targetProperty.getLocalName() != null) { // Add an empty element with our targetProperty name and then set it. XML xmlValue = newTextElementXML(null, targetProperty, null); addToList(xmlValue); if(xmlName.isAttributeName()) { setAttribute(xmlName, value); } else { XML xml = (XML)item(0); xml.putXMLProperty(xmlName, value); // Update the list with the new item at location 0. replace(0, (XML)item(0)); } // Now add us to our parent XMLName name2 = XMLName.formProperty(targetProperty.getUri(), targetProperty.getLocalName()); targetObject.putXMLProperty(name2, this); } else { throw ScriptRuntime.typeError("Assignment to empty XMLList without targets not supported"); } } else if(xmlName.isAttributeName()) { setAttribute(xmlName, value); } else { XML xml = (XML)item(0); xml.putXMLProperty(xmlName, value); // Update the list with the new item at location 0. replace(0, (XML)item(0)); } } Object getXMLProperty(XMLName name) { return getPropertyList(name); } private void replaceNode(XML xml, XML with) { xml.replaceWith(with); } public void put(int index, Scriptable start, Object value) { Object parent = Undefined.instance; // Convert text into XML if needed. XMLObject xmlValue; // Special-case checks for undefined and null if (value == null) { value = "null"; } else if (value instanceof Undefined) { value = "undefined"; } if (value instanceof XMLObject) { xmlValue = (XMLObject) value; } else { if (targetProperty == null) { xmlValue = newXMLFromJs(value.toString()); } else { - xmlValue = newTextElementXML(null, targetProperty, value.toString()); + // Note that later in the code, we will use this as an argument to replace(int,value) + // So we will be "replacing" this element with itself + // There may well be a better way to do this + // TODO Find a way to refactor this whole method and simplify it + xmlValue = item(index); + ((XML)xmlValue).setChildren(value); } } // Find the parent if (index < length()) { parent = item(index).parent(); } else { // Appending parent = parent(); } if (parent instanceof XML) { // found parent, alter doc XML xmlParent = (XML) parent; if (index < length()) { // We're replacing the the node. XML xmlNode = getXmlFromAnnotation(index); if (xmlValue instanceof XML) { replaceNode(xmlNode, (XML) xmlValue); replace(index, xmlNode); } else if (xmlValue instanceof XMLList) { // Replace the first one, and add the rest on the list. XMLList list = (XMLList) xmlValue; if (list.length() > 0) { int lastIndexAdded = xmlNode.childIndex(); replaceNode(xmlNode, (XML)list.item(0)); replace(index, (XML)list.item(0)); for (int i = 1; i < list.length(); i++) { xmlParent.insertChildAfter(xmlParent.getXmlChild(lastIndexAdded), list.item(i)); lastIndexAdded++; insert(index + i, (XML)list.item(i)); } } } } else { // Appending xmlParent.appendChild(xmlValue); addToList(xmlParent.getXmlChild(index)); } } else { // Don't all have same parent, no underlying doc to alter if (index < length()) { XML xmlNode = getXML(_annos, index); if (xmlValue instanceof XML) { replaceNode(xmlNode, (XML) xmlValue); replace(index, xmlNode); } else if (xmlValue instanceof XMLList) { // Replace the first one, and add the rest on the list. XMLList list = (XMLList) xmlValue; if (list.length() > 0) { replaceNode(xmlNode, (XML)list.item(0)); replace(index, (XML)list.item(0)); for (int i = 1; i < list.length(); i++) { insert(index + i, (XML)list.item(i)); } } } } else { addToList(xmlValue); } } } private XML getXML(XmlNode.List _annos, int index) { if (index >= 0 && index < length()) { return xmlFromNode(_annos.item(index)); } else { return null; } } void deleteXMLProperty(XMLName name) { for (int i = 0; i < length(); i++) { XML xml = getXmlFromAnnotation(i); if (xml.isElement()) { xml.deleteXMLProperty(name); } } } public void delete(int index) { if (index >= 0 && index < length()) { XML xml = getXmlFromAnnotation(index); xml.remove(); internalRemoveFromList(index); } } public Object[] getIds() { Object enumObjs[]; if (isPrototype()) { enumObjs = new Object[0]; } else { enumObjs = new Object[length()]; for (int i = 0; i < enumObjs.length; i++) { enumObjs[i] = new Integer(i); } } return enumObjs; } public Object[] getIdsForDebug() { return getIds(); } // XMLList will remove will delete all items in the list (a set delete) this differs from the XMLList delete operator. void remove() { int nLen = length(); for (int i = nLen - 1; i >= 0; i--) { XML xml = getXmlFromAnnotation(i); if (xml != null) { xml.remove(); internalRemoveFromList(i); } } } XML item(int index) { return _annos != null ? getXmlFromAnnotation(index) : createEmptyXML(); } private void setAttribute(XMLName xmlName, Object value) { for (int i = 0; i < length(); i++) { XML xml = getXmlFromAnnotation(i); xml.setAttribute(xmlName, value); } } void addToList(Object toAdd) { _annos.addToList(toAdd); } // // // Methods from section 12.4.4 in the spec // // XMLList child(int index) { XMLList result = newXMLList(); for (int i = 0; i < length(); i++) { result.addToList(getXmlFromAnnotation(i).child(index)); } return result; } XMLList child(XMLName xmlName) { XMLList result = newXMLList(); for (int i = 0; i < length(); i++) { result.addToList(getXmlFromAnnotation(i).child(xmlName)); } return result; } void addMatches(XMLList rv, XMLName name) { for (int i=0; i<length(); i++) { getXmlFromAnnotation(i).addMatches(rv, name); } } XMLList children() { java.util.Vector v = new java.util.Vector(); for (int i = 0; i < length(); i++) { XML xml = getXmlFromAnnotation(i); if (xml != null) { Object o = xml.children(); if (o instanceof XMLList) { XMLList childList = (XMLList)o; int cChildren = childList.length(); for (int j = 0; j < cChildren; j++) { v.addElement(childList.item(j)); } } } } XMLList allChildren = newXMLList(); int sz = v.size(); for (int i = 0; i < sz; i++) { allChildren.addToList(v.get(i)); } return allChildren; } XMLList comments() { XMLList result = newXMLList(); for (int i = 0; i < length(); i++) { XML xml = getXmlFromAnnotation(i); result.addToList(xml.comments()); } return result; } XMLList elements(XMLName name) { XMLList rv = newXMLList(); for (int i=0; i<length(); i++) { XML xml = getXmlFromAnnotation(i); rv.addToList(xml.elements(name)); } return rv; } boolean contains(Object xml) { boolean result = false; for (int i = 0; i < length(); i++) { XML member = getXmlFromAnnotation(i); if (member.equivalentXml(xml)) { result = true; break; } } return result; } XMLObjectImpl copy() { XMLList result = newXMLList(); for (int i = 0; i < length(); i++) { XML xml = getXmlFromAnnotation(i); result.addToList(xml.copy()); } return result; } boolean hasOwnProperty(XMLName xmlName) { if (isPrototype()) { String property = xmlName.localName(); return (findPrototypeId(property) != 0); } else { return (getPropertyList(xmlName).length() > 0); } } boolean hasComplexContent() { boolean complexContent; int length = length(); if (length == 0) { complexContent = false; } else if (length == 1) { complexContent = getXmlFromAnnotation(0).hasComplexContent(); } else { complexContent = false; for (int i = 0; i < length; i++) { XML nextElement = getXmlFromAnnotation(i); if (nextElement.isElement()) { complexContent = true; break; } } } return complexContent; } boolean hasSimpleContent() { if (length() == 0) { return true; } else if (length() == 1) { return getXmlFromAnnotation(0).hasSimpleContent(); } else { for (int i=0; i<length(); i++) { XML nextElement = getXmlFromAnnotation(i); if (nextElement.isElement()) { return false; } } return true; } } int length() { int result = 0; if (_annos != null) { result = _annos.length(); } return result; } void normalize() { for (int i = 0; i < length(); i++) { getXmlFromAnnotation(i).normalize(); } } /** * If list is empty, return undefined, if elements have different parents return undefined, * If they all have the same parent, return that parent. * * @return */ Object parent() { if (length() == 0) return Undefined.instance; XML candidateParent = null; for (int i = 0; i < length(); i++) { Object currParent = getXmlFromAnnotation(i).parent(); if (!(currParent instanceof XML)) return Undefined.instance; XML xml = (XML)currParent; if (i == 0) { // Set the first for the rest to compare to. candidateParent = xml; } else { if (candidateParent.is(xml)) { // keep looking } else { return Undefined.instance; } } } return candidateParent; } XMLList processingInstructions(XMLName xmlName) { XMLList result = newXMLList(); for (int i = 0; i < length(); i++) { XML xml = getXmlFromAnnotation(i); result.addToList(xml.processingInstructions(xmlName)); } return result; } boolean propertyIsEnumerable(Object name) { long index; if (name instanceof Integer) { index = ((Integer)name).intValue(); } else if (name instanceof Number) { double x = ((Number)name).doubleValue(); index = (long)x; if ((double)index != x) { return false; } if (index == 0 && 1.0 / x < 0) { // Negative 0 return false; } } else { String s = ScriptRuntime.toString(name); index = ScriptRuntime.testUint32String(s); } return (0 <= index && index < length()); } XMLList text() { XMLList result = newXMLList(); for (int i = 0; i < length(); i++) { result.addToList(getXmlFromAnnotation(i).text()); } return result; } public String toString() { // ECMA357 10.1.2 if (hasSimpleContent()) { StringBuffer sb = new StringBuffer(); for(int i = 0; i < length(); i++) { XML next = getXmlFromAnnotation(i); if (next.isComment() || next.isProcessingInstruction()) { // do nothing } else { sb.append(next.toString()); } } return sb.toString(); } else { return toXMLString(); } } String toXMLString() { // See ECMA 10.2.1 StringBuffer sb = new StringBuffer(); for (int i=0; i<length(); i++) { if (getProcessor().isPrettyPrinting() && i != 0) { sb.append('\n'); } sb.append(getXmlFromAnnotation(i).toXMLString()); } return sb.toString(); } Object valueOf() { return this; } // // Other public Functions from XMLObject // boolean equivalentXml(Object target) { boolean result = false; // Zero length list should equate to undefined if (target instanceof Undefined && length() == 0) { result = true; } else if (length() == 1) { result = getXmlFromAnnotation(0).equivalentXml(target); } else if (target instanceof XMLList) { XMLList otherList = (XMLList) target; if (otherList.length() == length()) { result = true; for (int i = 0; i < length(); i++) { if (!getXmlFromAnnotation(i).equivalentXml(otherList.getXmlFromAnnotation(i))) { result = false; break; } } } } return result; } private XMLList getPropertyList(XMLName name) { XMLList propertyList = newXMLList(); XmlNode.QName qname = null; if (!name.isDescendants() && !name.isAttributeName()) { // Only set the targetProperty if this is a regular child get // and not a descendant or attribute get qname = name.toQname(); } propertyList.setTargets(this, qname); for (int i = 0; i < length(); i++) { propertyList.addToList( getXmlFromAnnotation(i).getPropertyList(name)); } return propertyList; } private Object applyOrCall(boolean isApply, Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { String methodName = isApply ? "apply" : "call"; if(!(thisObj instanceof XMLList) || ((XMLList)thisObj).targetProperty == null) throw ScriptRuntime.typeError1("msg.isnt.function", methodName); return ScriptRuntime.applyOrCall(isApply, cx, scope, thisObj, args); } protected Object jsConstructor(Context cx, boolean inNewExpr, Object[] args) { if (args.length == 0) { return newXMLList(); } else { Object arg0 = args[0]; if (!inNewExpr && arg0 instanceof XMLList) { // XMLList(XMLList) returns the same object. return arg0; } return newXMLListFrom(arg0); } } /** * See ECMA 357, 11_2_2_1, Semantics, 3_e. */ public Scriptable getExtraMethodSource(Context cx) { if (length() == 1) { return getXmlFromAnnotation(0); } return null; } public Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { // This XMLList is being called as a Function. // Let's find the real Function object. if(targetProperty == null) throw ScriptRuntime.notFunctionError(this); String methodName = targetProperty.getLocalName(); boolean isApply = methodName.equals("apply"); if(isApply || methodName.equals("call")) return applyOrCall(isApply, cx, scope, thisObj, args); Callable method = ScriptRuntime.getElemFunctionAndThis( this, methodName, cx); // Call lastStoredScriptable to clear stored thisObj // but ignore the result as the method should use the supplied // thisObj, not one from redirected call ScriptRuntime.lastStoredScriptable(cx); return method.call(cx, scope, thisObj, args); } public Scriptable construct(Context cx, Scriptable scope, Object[] args) { throw ScriptRuntime.typeError1("msg.not.ctor", "XMLList"); } }
true
true
public void put(int index, Scriptable start, Object value) { Object parent = Undefined.instance; // Convert text into XML if needed. XMLObject xmlValue; // Special-case checks for undefined and null if (value == null) { value = "null"; } else if (value instanceof Undefined) { value = "undefined"; } if (value instanceof XMLObject) { xmlValue = (XMLObject) value; } else { if (targetProperty == null) { xmlValue = newXMLFromJs(value.toString()); } else { xmlValue = newTextElementXML(null, targetProperty, value.toString()); } } // Find the parent if (index < length()) { parent = item(index).parent(); } else { // Appending parent = parent(); } if (parent instanceof XML) { // found parent, alter doc XML xmlParent = (XML) parent; if (index < length()) { // We're replacing the the node. XML xmlNode = getXmlFromAnnotation(index); if (xmlValue instanceof XML) { replaceNode(xmlNode, (XML) xmlValue); replace(index, xmlNode); } else if (xmlValue instanceof XMLList) { // Replace the first one, and add the rest on the list. XMLList list = (XMLList) xmlValue; if (list.length() > 0) { int lastIndexAdded = xmlNode.childIndex(); replaceNode(xmlNode, (XML)list.item(0)); replace(index, (XML)list.item(0)); for (int i = 1; i < list.length(); i++) { xmlParent.insertChildAfter(xmlParent.getXmlChild(lastIndexAdded), list.item(i)); lastIndexAdded++; insert(index + i, (XML)list.item(i)); } } } } else { // Appending xmlParent.appendChild(xmlValue); addToList(xmlParent.getXmlChild(index)); } } else { // Don't all have same parent, no underlying doc to alter if (index < length()) { XML xmlNode = getXML(_annos, index); if (xmlValue instanceof XML) { replaceNode(xmlNode, (XML) xmlValue); replace(index, xmlNode); } else if (xmlValue instanceof XMLList) { // Replace the first one, and add the rest on the list. XMLList list = (XMLList) xmlValue; if (list.length() > 0) { replaceNode(xmlNode, (XML)list.item(0)); replace(index, (XML)list.item(0)); for (int i = 1; i < list.length(); i++) { insert(index + i, (XML)list.item(i)); } } } } else { addToList(xmlValue); } } }
public void put(int index, Scriptable start, Object value) { Object parent = Undefined.instance; // Convert text into XML if needed. XMLObject xmlValue; // Special-case checks for undefined and null if (value == null) { value = "null"; } else if (value instanceof Undefined) { value = "undefined"; } if (value instanceof XMLObject) { xmlValue = (XMLObject) value; } else { if (targetProperty == null) { xmlValue = newXMLFromJs(value.toString()); } else { // Note that later in the code, we will use this as an argument to replace(int,value) // So we will be "replacing" this element with itself // There may well be a better way to do this // TODO Find a way to refactor this whole method and simplify it xmlValue = item(index); ((XML)xmlValue).setChildren(value); } } // Find the parent if (index < length()) { parent = item(index).parent(); } else { // Appending parent = parent(); } if (parent instanceof XML) { // found parent, alter doc XML xmlParent = (XML) parent; if (index < length()) { // We're replacing the the node. XML xmlNode = getXmlFromAnnotation(index); if (xmlValue instanceof XML) { replaceNode(xmlNode, (XML) xmlValue); replace(index, xmlNode); } else if (xmlValue instanceof XMLList) { // Replace the first one, and add the rest on the list. XMLList list = (XMLList) xmlValue; if (list.length() > 0) { int lastIndexAdded = xmlNode.childIndex(); replaceNode(xmlNode, (XML)list.item(0)); replace(index, (XML)list.item(0)); for (int i = 1; i < list.length(); i++) { xmlParent.insertChildAfter(xmlParent.getXmlChild(lastIndexAdded), list.item(i)); lastIndexAdded++; insert(index + i, (XML)list.item(i)); } } } } else { // Appending xmlParent.appendChild(xmlValue); addToList(xmlParent.getXmlChild(index)); } } else { // Don't all have same parent, no underlying doc to alter if (index < length()) { XML xmlNode = getXML(_annos, index); if (xmlValue instanceof XML) { replaceNode(xmlNode, (XML) xmlValue); replace(index, xmlNode); } else if (xmlValue instanceof XMLList) { // Replace the first one, and add the rest on the list. XMLList list = (XMLList) xmlValue; if (list.length() > 0) { replaceNode(xmlNode, (XML)list.item(0)); replace(index, (XML)list.item(0)); for (int i = 1; i < list.length(); i++) { insert(index + i, (XML)list.item(i)); } } } } else { addToList(xmlValue); } } }
diff --git a/src/com/jidesoft/swing/JideScrollPaneLayout.java b/src/com/jidesoft/swing/JideScrollPaneLayout.java index 894b8d8b..aaeabb64 100644 --- a/src/com/jidesoft/swing/JideScrollPaneLayout.java +++ b/src/com/jidesoft/swing/JideScrollPaneLayout.java @@ -1,1014 +1,1014 @@ /* * @(#)${NAME}.java * * Copyright 2002 - 2005 JIDE Software Inc. All rights reserved. */ package com.jidesoft.swing; import javax.swing.*; import javax.swing.border.Border; import java.awt.*; /** * The layout manager used by <code>JideScrollPane</code>. * <code>JideScrollPaneLayout</code> is * responsible for eleven components: a viewport, two scrollbars, * a row header, a column header, a row footer, a column footer, and four "corner" components. */ class JideScrollPaneLayout extends ScrollPaneLayout implements JideScrollPaneConstants { /** * The row footer child. Default is <code>null</code>. * * @see JideScrollPane#setRowFooter */ protected JViewport _rowFoot; /** * The column footer child. Default is <code>null</code>. * * @see JideScrollPane#setColumnFooter */ protected JViewport _colFoot; /** * The component to the left of horizontal scroll bar. */ protected Component _hLeft; /** * The component to the right of horizontal scroll bar. */ protected Component _hRight; /** * The component to the top of vertical scroll bar. */ protected Component _vTop; /** * The component to the bottom of vertical scroll bar. */ protected Component _vBottom; @Override public void syncWithScrollPane(JScrollPane sp) { super.syncWithScrollPane(sp); if (sp instanceof JideScrollPane) { _rowFoot = ((JideScrollPane) sp).getRowFooter(); _colFoot = ((JideScrollPane) sp).getColumnFooter(); _hLeft = ((JideScrollPane) sp).getScrollBarCorner(HORIZONTAL_LEFT); _hRight = ((JideScrollPane) sp).getScrollBarCorner(HORIZONTAL_RIGHT); _vTop = ((JideScrollPane) sp).getScrollBarCorner(VERTICAL_TOP); _vBottom = ((JideScrollPane) sp).getScrollBarCorner(VERTICAL_BOTTOM); } } protected boolean isHsbCoversWholeWidth(JScrollPane sp) { if (sp instanceof JideScrollPane) { return ((JideScrollPane) sp).isHorizontalScrollBarCoversWholeWidth(); } else { return false; } } protected boolean isVsbCoversWholeHeight(JScrollPane sp) { if (sp instanceof JideScrollPane) { return ((JideScrollPane) sp).isVerticalScrollBarCoversWholeHeight(); } else { return false; } } @Override public void addLayoutComponent(String s, Component c) { if (s.equals(ROW_FOOTER)) { _rowFoot = (JViewport) addSingletonComponent(_rowFoot, c); } else if (s.equals(COLUMN_FOOTER)) { _colFoot = (JViewport) addSingletonComponent(_colFoot, c); } else if (s.equals(HORIZONTAL_LEFT)) { _hLeft = addSingletonComponent(_hLeft, c); } else if (s.equals(HORIZONTAL_RIGHT)) { _hRight = addSingletonComponent(_hRight, c); } else if (s.equals(VERTICAL_TOP)) { _vTop = addSingletonComponent(_vTop, c); } else if (s.equals(VERTICAL_BOTTOM)) { _vBottom = addSingletonComponent(_vBottom, c); } else { super.addLayoutComponent(s, c); } } @Override public void removeLayoutComponent(Component c) { if (c == _rowFoot) { _rowFoot = null; } else if (c == _colFoot) { _colFoot = null; } else if (c == _hLeft) { _hLeft = null; } else if (c == _hRight) { _hRight = null; } else if (c == _vTop) { _vTop = null; } else if (c == _vBottom) { _vBottom = null; } else { super.removeLayoutComponent(c); } } /** * Returns the <code>JViewport</code> object that is the row footer. * * @return the <code>JViewport</code> object that is the row footer * @see JideScrollPane#getRowFooter */ public JViewport getRowFooter() { return _rowFoot; } /** * Returns the <code>JViewport</code> object that is the column footer. * * @return the <code>JViewport</code> object that is the column footer * @see JideScrollPane#getColumnFooter */ public JViewport getColumnFooter() { return _colFoot; } /** * Returns the <code>Component</code> at the specified corner. * * @param key the <code>String</code> specifying the corner * @return the <code>Component</code> at the specified corner, as defined in * {@link ScrollPaneConstants}; if <code>key</code> is not one of the * four corners, <code>null</code> is returned * @see JScrollPane#getCorner */ public Component getScrollBarCorner(String key) { if (key.equals(HORIZONTAL_LEFT)) { return _hLeft; } else if (key.equals(HORIZONTAL_RIGHT)) { return _hRight; } else if (key.equals(VERTICAL_BOTTOM)) { return _vBottom; } else if (key.equals(VERTICAL_TOP)) { return _vTop; } else { return super.getCorner(key); } } /** * The preferred size of a <code>ScrollPane</code> is the size of the insets, * plus the preferred size of the viewport, plus the preferred size of * the visible headers, plus the preferred size of the scrollbars * that will appear given the current view and the current * scrollbar displayPolicies. * <p>Note that the rowHeader is calculated as part of the preferred width * and the colHeader is calculated as part of the preferred size. * * @param parent the <code>Container</code> that will be laid out * @return a <code>Dimension</code> object specifying the preferred size of the * viewport and any scrollbars * @see ViewportLayout * @see LayoutManager */ @Override public Dimension preferredLayoutSize(Container parent) { /* Sync the (now obsolete) policy fields with the * JScrollPane. */ JScrollPane scrollPane = (JScrollPane) parent; vsbPolicy = scrollPane.getVerticalScrollBarPolicy(); hsbPolicy = scrollPane.getHorizontalScrollBarPolicy(); Insets insets = parent.getInsets(); int prefWidth = insets.left + insets.right; int prefHeight = insets.top + insets.bottom; /* Note that viewport.getViewSize() is equivalent to * viewport.getView().getPreferredSize() modulo a null * view or a view whose size was explicitly set. */ Dimension extentSize = null; Dimension viewSize = null; Component view = null; if (viewport != null) { extentSize = viewport.getPreferredSize(); viewSize = viewport.getViewSize(); view = viewport.getView(); } /* If there's a viewport add its preferredSize. */ if (extentSize != null) { prefWidth += extentSize.width; prefHeight += extentSize.height; } /* If there's a JScrollPane.viewportBorder, add its insets. */ Border viewportBorder = scrollPane.getViewportBorder(); if (viewportBorder != null) { Insets vpbInsets = viewportBorder.getBorderInsets(parent); prefWidth += vpbInsets.left + vpbInsets.right; prefHeight += vpbInsets.top + vpbInsets.bottom; } /* If a header exists and it's visible, factor its * preferred size in. */ int rowHeaderWidth = 0; if (rowHead != null && rowHead.isVisible()) { rowHeaderWidth = rowHead.getPreferredSize().width; } if (upperLeft != null && upperLeft.isVisible()) { rowHeaderWidth = Math.max(rowHeaderWidth, upperLeft.getPreferredSize().width); } if (lowerLeft != null && lowerLeft.isVisible()) { rowHeaderWidth = Math.max(rowHeaderWidth, lowerLeft.getPreferredSize().width); } prefWidth += rowHeaderWidth; int upperHeight = getUpperHeight(); prefHeight += upperHeight; if ((_rowFoot != null) && _rowFoot.isVisible()) { prefWidth += _rowFoot.getPreferredSize().width; } int lowerHeight = getLowerHeight(); prefHeight += lowerHeight; /* If a scrollbar is going to appear, factor its preferred size in. * If the scrollbars policy is AS_NEEDED, this can be a little * tricky: * * - If the view is a Scrollable then scrollableTracksViewportWidth * and scrollableTracksViewportHeight can be used to effectively * disable scrolling (if they're true) in their respective dimensions. * * - Assuming that a scrollbar hasn't been disabled by the * previous constraint, we need to decide if the scrollbar is going * to appear to correctly compute the JScrollPanes preferred size. * To do this we compare the preferredSize of the viewport (the * extentSize) to the preferredSize of the view. Although we're * not responsible for laying out the view we'll assume that the * JViewport will always give it its preferredSize. */ if ((vsb != null) && (vsbPolicy != VERTICAL_SCROLLBAR_NEVER)) { if (vsbPolicy == VERTICAL_SCROLLBAR_ALWAYS) { prefWidth += vsb.getPreferredSize().width; } else if ((viewSize != null) && (extentSize != null)) { boolean canScroll = true; if (view instanceof Scrollable) { canScroll = !((Scrollable) view).getScrollableTracksViewportHeight(); } if (canScroll && (viewSize.height > extentSize.height)) { prefWidth += vsb.getPreferredSize().width; } } } if ((hsb != null) && (hsbPolicy != HORIZONTAL_SCROLLBAR_NEVER)) { if (hsbPolicy == HORIZONTAL_SCROLLBAR_ALWAYS) { prefHeight += hsb.getPreferredSize().height; } else if ((viewSize != null) && (extentSize != null)) { boolean canScroll = true; if (view instanceof Scrollable) { canScroll = !((Scrollable) view).getScrollableTracksViewportWidth(); } if (canScroll && (viewSize.width > extentSize.width)) { prefHeight += hsb.getPreferredSize().height; } } } return new Dimension(prefWidth, prefHeight); } private int getUpperHeight() { int upperHeight = 0; if ((upperLeft != null) && upperLeft.isVisible()) { upperHeight = upperLeft.getPreferredSize().height; } if ((upperRight != null) && upperRight.isVisible()) { upperHeight = Math.max(upperRight.getPreferredSize().height, upperHeight); } if ((colHead != null) && colHead.isVisible()) { upperHeight = Math.max(colHead.getPreferredSize().height, upperHeight); } return upperHeight; } private int getLowerHeight() { int lowerHeight = 0; if ((lowerLeft != null) && lowerLeft.isVisible()) { lowerHeight = lowerLeft.getPreferredSize().height; } if ((lowerRight != null) && lowerRight.isVisible()) { lowerHeight = Math.max(lowerRight.getPreferredSize().height, lowerHeight); } if ((_colFoot != null) && _colFoot.isVisible()) { lowerHeight = Math.max(_colFoot.getPreferredSize().height, lowerHeight); } return lowerHeight; } /** * The minimum size of a <code>ScrollPane</code> is the size of the insets * plus minimum size of the viewport, plus the scrollpane's * viewportBorder insets, plus the minimum size * of the visible headers, plus the minimum size of the * scrollbars whose displayPolicy isn't NEVER. * * @param parent the <code>Container</code> that will be laid out * @return a <code>Dimension</code> object specifying the minimum size */ @Override public Dimension minimumLayoutSize(Container parent) { /* Sync the (now obsolete) policy fields with the * JScrollPane. */ JScrollPane scrollPane = (JScrollPane) parent; vsbPolicy = scrollPane.getVerticalScrollBarPolicy(); hsbPolicy = scrollPane.getHorizontalScrollBarPolicy(); Insets insets = parent.getInsets(); int minWidth = insets.left + insets.right; int minHeight = insets.top + insets.bottom; /* If there's a viewport add its minimumSize. */ if (viewport != null) { Dimension size = viewport.getMinimumSize(); minWidth += size.width; minHeight += size.height; } /* If there's a JScrollPane.viewportBorder, add its insets. */ Border viewportBorder = scrollPane.getViewportBorder(); if (viewportBorder != null) { Insets vpbInsets = viewportBorder.getBorderInsets(parent); minWidth += vpbInsets.left + vpbInsets.right; minHeight += vpbInsets.top + vpbInsets.bottom; } /* If a header exists and it's visible, factor its * minimum size in. */ int rowHeaderWidth = 0; if (rowHead != null && rowHead.isVisible()) { Dimension size = rowHead.getMinimumSize(); rowHeaderWidth = size.width; minHeight = Math.max(minHeight, size.height); } if (upperLeft != null && upperLeft.isVisible()) { rowHeaderWidth = Math.max(rowHeaderWidth, upperLeft.getMinimumSize().width); } if (lowerLeft != null && lowerLeft.isVisible()) { rowHeaderWidth = Math.max(rowHeaderWidth, lowerLeft.getMinimumSize().width); } minWidth += rowHeaderWidth; int upperHeight = 0; if ((upperLeft != null) && upperLeft.isVisible()) { upperHeight = upperLeft.getMinimumSize().height; } if ((upperRight != null) && upperRight.isVisible()) { upperHeight = Math.max(upperRight.getMinimumSize().height, upperHeight); } if ((colHead != null) && colHead.isVisible()) { Dimension size = colHead.getMinimumSize(); minWidth = Math.max(minWidth, size.width); upperHeight = Math.max(size.height, upperHeight); } minHeight += upperHeight; // JIDE: added for JideScrollPaneLayout int lowerHeight = 0; if ((lowerLeft != null) && lowerLeft.isVisible()) { lowerHeight = lowerLeft.getMinimumSize().height; } if ((lowerRight != null) && lowerRight.isVisible()) { lowerHeight = Math.max(lowerRight.getMinimumSize().height, lowerHeight); } if ((_colFoot != null) && _colFoot.isVisible()) { Dimension size = _colFoot.getMinimumSize(); minWidth = Math.max(minWidth, size.width); lowerHeight = Math.max(size.height, lowerHeight); } minHeight += lowerHeight; if ((_rowFoot != null) && _rowFoot.isVisible()) { Dimension size = _rowFoot.getMinimumSize(); minWidth = Math.max(minWidth, size.width); minHeight += size.height; } // JIDE: End of added for JideScrollPaneLayout /* If a scrollbar might appear, factor its minimum * size in. */ if ((vsb != null) && (vsbPolicy != VERTICAL_SCROLLBAR_NEVER)) { Dimension size = vsb.getMinimumSize(); minWidth += size.width; minHeight = Math.max(minHeight, size.height); } if ((hsb != null) && (hsbPolicy != HORIZONTAL_SCROLLBAR_NEVER)) { Dimension size = hsb.getMinimumSize(); minWidth = Math.max(minWidth, size.width); minHeight += size.height; } return new Dimension(minWidth, minHeight); } /** * Lays out the scrollpane. The positioning of components depends on * the following constraints: * <ul> * <li> The row header, if present and visible, gets its preferred * width and the viewport's height. * <p/> * <li> The column header, if present and visible, gets its preferred * height and the viewport's width. * <p/> * <li> If a vertical scrollbar is needed, i.e. if the viewport's extent * height is smaller than its view height or if the <code>displayPolicy</code> * is ALWAYS, it's treated like the row header with respect to its * dimensions and is made visible. * <p/> * <li> If a horizontal scrollbar is needed, it is treated like the * column header (see the paragraph above regarding the vertical scrollbar). * <p/> * <li> If the scrollpane has a non-<code>null</code> * <code>viewportBorder</code>, then space is allocated for that. * <p/> * <li> The viewport gets the space available after accounting for * the previous constraints. * <p/> * <li> The corner components, if provided, are aligned with the * ends of the scrollbars and headers. If there is a vertical * scrollbar, the right corners appear; if there is a horizontal * scrollbar, the lower corners appear; a row header gets left * corners, and a column header gets upper corners. * </ul> * * @param parent the <code>Container</code> to lay out */ @Override public void layoutContainer(Container parent) { /* Sync the (now obsolete) policy fields with the * JScrollPane. */ JScrollPane scrollPane = (JScrollPane) parent; vsbPolicy = scrollPane.getVerticalScrollBarPolicy(); hsbPolicy = scrollPane.getHorizontalScrollBarPolicy(); Rectangle availR = scrollPane.getBounds(); availR.x = availR.y = 0; Insets insets = parent.getInsets(); availR.x = insets.left; availR.y = insets.top; availR.width -= insets.left + insets.right; availR.height -= insets.top + insets.bottom; /* Get the scrollPane's orientation. */ boolean leftToRight = scrollPane.getComponentOrientation().isLeftToRight(); /* If there's a visible column header remove the space it * needs from the top of availR. The column header is treated * as if it were fixed height, arbitrary width. */ Rectangle colHeadR = new Rectangle(0, availR.y, 0, 0); int upperHeight = getUpperHeight(); if ((colHead != null) && (colHead.isVisible())) { int colHeadHeight = Math.min(availR.height, upperHeight); colHeadR.height = colHeadHeight; availR.y += colHeadHeight; availR.height -= colHeadHeight; } /* If there's a visible row header remove the space it needs * from the left or right of availR. The row header is treated * as if it were fixed width, arbitrary height. */ Rectangle rowHeadR = new Rectangle(0, 0, 0, 0); if ((rowHead != null) && (rowHead.isVisible())) { int rowHeadWidth = rowHead.getPreferredSize().width; if (upperLeft != null && upperLeft.isVisible()) { rowHeadWidth = Math.max(rowHeadWidth, upperLeft.getPreferredSize().width); } if (lowerLeft != null && lowerLeft.isVisible()) { rowHeadWidth = Math.max(rowHeadWidth, lowerLeft.getPreferredSize().width); } rowHeadWidth = Math.min(availR.width, rowHeadWidth); rowHeadR.width = rowHeadWidth; availR.width -= rowHeadWidth; if (leftToRight) { rowHeadR.x = availR.x; availR.x += rowHeadWidth; } else { rowHeadR.x = availR.x + availR.width; } } /* If there's a JScrollPane.viewportBorder, remove the * space it occupies for availR. */ Border viewportBorder = scrollPane.getViewportBorder(); Insets vpbInsets; if (viewportBorder != null) { vpbInsets = viewportBorder.getBorderInsets(parent); availR.x += vpbInsets.left; availR.y += vpbInsets.top; availR.width -= vpbInsets.left + vpbInsets.right; availR.height -= vpbInsets.top + vpbInsets.bottom; } else { vpbInsets = new Insets(0, 0, 0, 0); } /* If there's a visible row footer remove the space it needs * from the left or right of availR. The row footer is treated * as if it were fixed width, arbitrary height. */ Rectangle rowFootR = new Rectangle(0, 0, 0, 0); if ((_rowFoot != null) && (_rowFoot.isVisible())) { int rowFootWidth = Math.min(availR.width, _rowFoot.getPreferredSize().width); rowFootR.width = rowFootWidth; availR.width -= rowFootWidth; if (leftToRight) { rowFootR.x = availR.x + availR.width; } else { rowFootR.x = availR.x; availR.x += rowFootWidth; } } /* If there's a visible column footer remove the space it * needs from the top of availR. The column footer is treated * as if it were fixed height, arbitrary width. */ Rectangle colFootR = new Rectangle(0, availR.y, 0, 0); int lowerHeight = getLowerHeight(); if ((_colFoot != null) && (_colFoot.isVisible())) { int colFootHeight = Math.min(availR.height, lowerHeight); colFootR.height = colFootHeight; availR.height -= colFootHeight; colFootR.y = availR.y + availR.height; } /* At this point availR is the space available for the viewport * and scrollbars. rowHeadR is correct except for its height and y * and colHeadR is correct except for its width and x. Once we're * through computing the dimensions of these three parts we can * go back and set the dimensions of rowHeadR.height, rowHeadR.y, * colHeadR.width, colHeadR.x and the bounds for the corners. * * We'll decide about putting up scrollbars by comparing the * viewport views preferred size with the viewports extent * size (generally just its size). Using the preferredSize is * reasonable because layout proceeds top down - so we expect * the viewport to be laid out next. And we assume that the * viewports layout manager will give the view it's preferred * size. One exception to this is when the view implements * Scrollable and Scrollable.getViewTracksViewport{Width,Height} * methods return true. If the view is tracking the viewports * width we don't bother with a horizontal scrollbar, similarly * if view.getViewTracksViewport(Height) is true we don't bother * with a vertical scrollbar. */ Component view = (viewport != null) ? viewport.getView() : null; Dimension viewPrefSize = (view != null) ? view.getPreferredSize() : new Dimension(0, 0); Dimension extentSize = (viewport != null) ? viewport.toViewCoordinates(availR.getSize()) : new Dimension(0, 0); boolean viewTracksViewportWidth = false; boolean viewTracksViewportHeight = false; boolean isEmpty = (availR.width < 0 || availR.height < 0); Scrollable sv; // Don't bother checking the Scrollable methods if there is no room // for the viewport, we aren't going to show any scrollbars in this // case anyway. if (!isEmpty && view instanceof Scrollable) { sv = (Scrollable) view; viewTracksViewportWidth = sv.getScrollableTracksViewportWidth(); viewTracksViewportHeight = sv.getScrollableTracksViewportHeight(); } else { sv = null; } /* If there's a vertical scrollbar and we need one, allocate * space for it (we'll make it visible later). A vertical * scrollbar is considered to be fixed width, arbitrary height. */ Rectangle vsbR = new Rectangle(0, isVsbCoversWholeHeight(scrollPane) ? -vpbInsets.top : availR.y - vpbInsets.top, 0, 0); boolean vsbNeeded; if (isEmpty) { vsbNeeded = false; } else if (vsbPolicy == VERTICAL_SCROLLBAR_ALWAYS) { vsbNeeded = true; } else if (vsbPolicy == VERTICAL_SCROLLBAR_NEVER) { vsbNeeded = false; } else { // vsbPolicy == VERTICAL_SCROLLBAR_AS_NEEDED - vsbNeeded = !viewTracksViewportHeight && (viewPrefSize.height > extentSize.height || (rowHead != null && rowHead.getView().getPreferredSize().height > extentSize.height)); + vsbNeeded = !viewTracksViewportHeight && (viewPrefSize.height > extentSize.height || (rowHead != null && rowHead.getView() != null && rowHead.getView().getPreferredSize().height > extentSize.height)); } if ((vsb != null) && vsbNeeded) { adjustForVSB(true, availR, vsbR, vpbInsets, leftToRight); extentSize = viewport.toViewCoordinates(availR.getSize()); } /* If there's a horizontal scrollbar and we need one, allocate * space for it (we'll make it visible later). A horizontal * scrollbar is considered to be fixed height, arbitrary width. */ Rectangle hsbR = new Rectangle(isHsbCoversWholeWidth(scrollPane) ? -vpbInsets.left : availR.x - vpbInsets.left, 0, 0, 0); boolean hsbNeeded; if (isEmpty) { hsbNeeded = false; } else if (hsbPolicy == HORIZONTAL_SCROLLBAR_ALWAYS) { hsbNeeded = true; } else if (hsbPolicy == HORIZONTAL_SCROLLBAR_NEVER) { hsbNeeded = false; } else { // hsbPolicy == HORIZONTAL_SCROLLBAR_AS_NEEDED hsbNeeded = !viewTracksViewportWidth && (viewPrefSize.width > extentSize.width || (colHead != null && colHead.getView() != null && colHead.getView().getPreferredSize().width > extentSize.width)); } if ((hsb != null) && hsbNeeded) { adjustForHSB(true, availR, hsbR, vpbInsets); /* If we added the horizontal scrollbar then we've implicitly * reduced the vertical space available to the viewport. * As a consequence we may have to add the vertical scrollbar, * if that hasn't been done so already. Of course we * don't bother with any of this if the vsbPolicy is NEVER. */ if ((vsb != null) && !vsbNeeded && (vsbPolicy != VERTICAL_SCROLLBAR_NEVER)) { extentSize = viewport.toViewCoordinates(availR.getSize()); vsbNeeded = viewPrefSize.height > extentSize.height; if (vsbNeeded) { adjustForVSB(true, availR, vsbR, vpbInsets, leftToRight); } } } /* Set the size of the viewport first, and then recheck the Scrollable * methods. Some components base their return values for the Scrollable * methods on the size of the Viewport, so that if we don't * ask after resetting the bounds we may have gotten the wrong * answer. */ if (viewport != null) { viewport.setBounds(availR); // viewport.setViewSize(availR.getSize()); // to fix the strange scroll bar problem reported on http://www.jidesoft.com/forum/viewtopic.php?p=20526#20526 if (sv != null) { extentSize = viewport.toViewCoordinates(availR.getSize()); boolean oldHSBNeeded = hsbNeeded; boolean oldVSBNeeded = vsbNeeded; viewTracksViewportWidth = sv.getScrollableTracksViewportWidth(); viewTracksViewportHeight = sv.getScrollableTracksViewportHeight(); if (vsb != null && vsbPolicy == VERTICAL_SCROLLBAR_AS_NEEDED) { - boolean newVSBNeeded = !viewTracksViewportHeight && (viewPrefSize.height > extentSize.height || (rowHead != null && rowHead.getView().getPreferredSize().height > extentSize.height)); + boolean newVSBNeeded = !viewTracksViewportHeight && (viewPrefSize.height > extentSize.height || (rowHead != null && rowHead.getView() != null && rowHead.getView().getPreferredSize().height > extentSize.height)); if (newVSBNeeded != vsbNeeded) { vsbNeeded = newVSBNeeded; adjustForVSB(vsbNeeded, availR, vsbR, vpbInsets, leftToRight); extentSize = viewport.toViewCoordinates (availR.getSize()); } } if (hsb != null && hsbPolicy == HORIZONTAL_SCROLLBAR_AS_NEEDED) { - boolean newHSBbNeeded = !viewTracksViewportWidth && (viewPrefSize.width > extentSize.width || (colHead != null && colHead.getView().getPreferredSize().width > extentSize.width)); + boolean newHSBbNeeded = !viewTracksViewportWidth && (viewPrefSize.width > extentSize.width || (colHead != null && colHead.getView() != null && colHead.getView().getPreferredSize().width > extentSize.width)); if (newHSBbNeeded != hsbNeeded) { hsbNeeded = newHSBbNeeded; adjustForHSB(hsbNeeded, availR, hsbR, vpbInsets); if ((vsb != null) && !vsbNeeded && (vsbPolicy != VERTICAL_SCROLLBAR_NEVER)) { extentSize = viewport.toViewCoordinates (availR.getSize()); vsbNeeded = viewPrefSize.height > extentSize.height; if (vsbNeeded) { adjustForVSB(true, availR, vsbR, vpbInsets, leftToRight); } } if (_rowFoot != null && _rowFoot.isVisible()) { vsbR.x += rowFootR.width; } } } if (oldHSBNeeded != hsbNeeded || oldVSBNeeded != vsbNeeded) { viewport.setBounds(availR); // You could argue that we should recheck the // Scrollable methods again until they stop changing, // but they might never stop changing, so we stop here // and don't do any additional checks. } } } /* We now have the final size of the viewport: availR. * Now fixup the header and scrollbar widths/heights. */ vsbR.height = isVsbCoversWholeHeight(scrollPane) ? scrollPane.getHeight() - 1 : availR.height + vpbInsets.top + vpbInsets.bottom; hsbR.width = isHsbCoversWholeWidth(scrollPane) ? scrollPane.getWidth() - vsbR.width : availR.width + vpbInsets.left + vpbInsets.right; rowHeadR.height = availR.height + vpbInsets.top + vpbInsets.bottom; rowHeadR.y = availR.y - vpbInsets.top; colHeadR.width = availR.width + vpbInsets.left + vpbInsets.right; colHeadR.x = availR.x - vpbInsets.left; colFootR.x = availR.x; colFootR.y = rowHeadR.y + rowHeadR.height; colFootR.width = availR.width; rowFootR.x = availR.x + availR.width; rowFootR.y = availR.y; rowFootR.height = availR.height; vsbR.x += rowFootR.width; hsbR.y += colFootR.height; /* Set the bounds of the remaining components. The scrollbars * are made invisible if they're not needed. */ if (rowHead != null) { rowHead.setBounds(rowHeadR); } if (_rowFoot != null) { _rowFoot.setBounds(rowFootR); } if (colHead != null) { int height = Math.min(colHeadR.height, colHead.getPreferredSize().height); colHead.setBounds(new Rectangle(colHeadR.x, colHeadR.y + colHeadR.height - height, colHeadR.width, height)); } if (_colFoot != null) { int height = Math.min(colFootR.height, _colFoot.getPreferredSize().height); _colFoot.setBounds(new Rectangle(colFootR.x, colFootR.y, colFootR.width, height)); } if (vsb != null) { if (vsbNeeded) { vsb.setVisible(true); if (_vTop == null && _vBottom == null) vsb.setBounds(vsbR); else { Rectangle rect = new Rectangle(vsbR); if (_vTop != null) { Dimension dim = _vTop.getPreferredSize(); rect.y += dim.height; rect.height -= dim.height; _vTop.setVisible(true); _vTop.setBounds(vsbR.x, vsbR.y, vsbR.width, dim.height); } if (_vBottom != null) { Dimension dim = _vBottom.getPreferredSize(); rect.height -= dim.height; _vBottom.setVisible(true); _vBottom.setBounds(vsbR.x, vsbR.y + vsbR.height - dim.height, vsbR.width, dim.height); } vsb.setBounds(rect); } } else { if (viewPrefSize.height > extentSize.height) { vsb.setVisible(true); vsb.setBounds(vsbR.x, vsbR.y, 0, vsbR.height); } else { vsb.setVisible(false); } if (_vTop != null) _vTop.setVisible(false); if (_vBottom != null) _vBottom.setVisible(false); } } if (hsb != null) { if (hsbNeeded) { hsb.setVisible(true); if (_hLeft == null && _hRight == null) hsb.setBounds(hsbR); else { Rectangle rect = new Rectangle(hsbR); if (_hLeft != null) { Dimension dim = _hLeft.getPreferredSize(); rect.x += dim.width; rect.width -= dim.width; _hLeft.setVisible(true); _hLeft.setBounds(hsbR.x, hsbR.y, dim.width, hsbR.height); _hLeft.doLayout(); } if (_hRight != null) { Dimension dim = _hRight.getPreferredSize(); rect.width -= dim.width; _hRight.setVisible(true); _hRight.setBounds(hsbR.x + hsbR.width - dim.width, hsbR.y, dim.width, hsbR.height); } hsb.setBounds(rect); } } else { if (viewPrefSize.width > extentSize.width) { hsb.setVisible(true); hsb.setBounds(hsbR.x, hsbR.y, hsbR.width, 0); } else { hsb.setVisible(false); } if (_hLeft != null) _hLeft.setVisible(false); if (_hRight != null) _hRight.setVisible(false); } } if (lowerLeft != null && lowerLeft.isVisible()) { int height = Math.min(lowerLeft.getPreferredSize().height, colFootR.height); lowerLeft.setBounds(leftToRight ? rowHeadR.x : vsbR.x, colFootR.y != 0 ? colFootR.y : hsbR.y, leftToRight ? rowHeadR.width : vsbR.width, height); } if (lowerRight != null && lowerRight.isVisible()) { int height = Math.min(lowerRight.getPreferredSize().height, colFootR.height); lowerRight.setBounds(leftToRight ? rowFootR.x : rowHeadR.x, colFootR.y != 0 ? colFootR.y : hsbR.y, leftToRight ? rowFootR.width + (isVsbCoversWholeHeight(scrollPane) ? 0 : vsbR.width) : rowHeadR.width, height); } if (upperLeft != null && upperLeft.isVisible()) { int height = Math.min(upperLeft.getPreferredSize().height, colHeadR.height); upperLeft.setBounds(leftToRight ? rowHeadR.x : vsbR.x, colHeadR.y + colHeadR.height - height, leftToRight ? rowHeadR.width : vsbR.width, height); } if (upperRight != null && upperRight.isVisible()) { int height = Math.min(upperRight.getPreferredSize().height, colHeadR.height); upperRight.setBounds(leftToRight ? rowFootR.x : rowHeadR.x, colHeadR.y + colHeadR.height - height, leftToRight ? rowFootR.width + (isVsbCoversWholeHeight(scrollPane) ? 0 : vsbR.width) : rowHeadR.width, height); } } /** * Adjusts the <code>Rectangle</code> <code>available</code> based on if * the vertical scrollbar is needed (<code>wantsVSB</code>). * The location of the vsb is updated in <code>vsbR</code>, and * the viewport border insets (<code>vpbInsets</code>) are used to offset * the vsb. This is only called when <code>wantsVSB</code> has * changed, eg you shouldn't invoke adjustForVSB(true) twice. */ private void adjustForVSB(boolean wantsVSB, Rectangle available, Rectangle vsbR, Insets vpbInsets, boolean leftToRight) { int oldWidth = vsbR.width; if (wantsVSB) { int vsbWidth = Math.max(0, Math.min(vsb.getPreferredSize().width, available.width)); available.width -= vsbWidth; vsbR.width = vsbWidth; if (leftToRight) { vsbR.x = available.x + available.width + vpbInsets.right; } else { vsbR.x = available.x - vpbInsets.left; available.x += vsbWidth; } } else { available.width += oldWidth; } } /** * Adjusts the <code>Rectangle</code> <code>available</code> based on if * the horizontal scrollbar is needed (<code>wantsHSB</code>). * The location of the hsb is updated in <code>hsbR</code>, and * the viewport border insets (<code>vpbInsets</code>) are used to offset * the hsb. This is only called when <code>wantsHSB</code> has * changed, eg you shouldn't invoked adjustForHSB(true) twice. */ private void adjustForHSB(boolean wantsHSB, Rectangle available, Rectangle hsbR, Insets vpbInsets) { int oldHeight = hsbR.height; if (wantsHSB) { int hsbHeight = Math.max(0, Math.min(available.height, hsb.getPreferredSize().height)); available.height -= hsbHeight; hsbR.y = available.y + available.height + vpbInsets.bottom; hsbR.height = hsbHeight; } else { available.height += oldHeight; } } /** * The UI resource version of <code>ScrollPaneLayout</code>. */ static class UIResource extends JideScrollPaneLayout implements javax.swing.plaf.UIResource { } }
false
true
public void layoutContainer(Container parent) { /* Sync the (now obsolete) policy fields with the * JScrollPane. */ JScrollPane scrollPane = (JScrollPane) parent; vsbPolicy = scrollPane.getVerticalScrollBarPolicy(); hsbPolicy = scrollPane.getHorizontalScrollBarPolicy(); Rectangle availR = scrollPane.getBounds(); availR.x = availR.y = 0; Insets insets = parent.getInsets(); availR.x = insets.left; availR.y = insets.top; availR.width -= insets.left + insets.right; availR.height -= insets.top + insets.bottom; /* Get the scrollPane's orientation. */ boolean leftToRight = scrollPane.getComponentOrientation().isLeftToRight(); /* If there's a visible column header remove the space it * needs from the top of availR. The column header is treated * as if it were fixed height, arbitrary width. */ Rectangle colHeadR = new Rectangle(0, availR.y, 0, 0); int upperHeight = getUpperHeight(); if ((colHead != null) && (colHead.isVisible())) { int colHeadHeight = Math.min(availR.height, upperHeight); colHeadR.height = colHeadHeight; availR.y += colHeadHeight; availR.height -= colHeadHeight; } /* If there's a visible row header remove the space it needs * from the left or right of availR. The row header is treated * as if it were fixed width, arbitrary height. */ Rectangle rowHeadR = new Rectangle(0, 0, 0, 0); if ((rowHead != null) && (rowHead.isVisible())) { int rowHeadWidth = rowHead.getPreferredSize().width; if (upperLeft != null && upperLeft.isVisible()) { rowHeadWidth = Math.max(rowHeadWidth, upperLeft.getPreferredSize().width); } if (lowerLeft != null && lowerLeft.isVisible()) { rowHeadWidth = Math.max(rowHeadWidth, lowerLeft.getPreferredSize().width); } rowHeadWidth = Math.min(availR.width, rowHeadWidth); rowHeadR.width = rowHeadWidth; availR.width -= rowHeadWidth; if (leftToRight) { rowHeadR.x = availR.x; availR.x += rowHeadWidth; } else { rowHeadR.x = availR.x + availR.width; } } /* If there's a JScrollPane.viewportBorder, remove the * space it occupies for availR. */ Border viewportBorder = scrollPane.getViewportBorder(); Insets vpbInsets; if (viewportBorder != null) { vpbInsets = viewportBorder.getBorderInsets(parent); availR.x += vpbInsets.left; availR.y += vpbInsets.top; availR.width -= vpbInsets.left + vpbInsets.right; availR.height -= vpbInsets.top + vpbInsets.bottom; } else { vpbInsets = new Insets(0, 0, 0, 0); } /* If there's a visible row footer remove the space it needs * from the left or right of availR. The row footer is treated * as if it were fixed width, arbitrary height. */ Rectangle rowFootR = new Rectangle(0, 0, 0, 0); if ((_rowFoot != null) && (_rowFoot.isVisible())) { int rowFootWidth = Math.min(availR.width, _rowFoot.getPreferredSize().width); rowFootR.width = rowFootWidth; availR.width -= rowFootWidth; if (leftToRight) { rowFootR.x = availR.x + availR.width; } else { rowFootR.x = availR.x; availR.x += rowFootWidth; } } /* If there's a visible column footer remove the space it * needs from the top of availR. The column footer is treated * as if it were fixed height, arbitrary width. */ Rectangle colFootR = new Rectangle(0, availR.y, 0, 0); int lowerHeight = getLowerHeight(); if ((_colFoot != null) && (_colFoot.isVisible())) { int colFootHeight = Math.min(availR.height, lowerHeight); colFootR.height = colFootHeight; availR.height -= colFootHeight; colFootR.y = availR.y + availR.height; } /* At this point availR is the space available for the viewport * and scrollbars. rowHeadR is correct except for its height and y * and colHeadR is correct except for its width and x. Once we're * through computing the dimensions of these three parts we can * go back and set the dimensions of rowHeadR.height, rowHeadR.y, * colHeadR.width, colHeadR.x and the bounds for the corners. * * We'll decide about putting up scrollbars by comparing the * viewport views preferred size with the viewports extent * size (generally just its size). Using the preferredSize is * reasonable because layout proceeds top down - so we expect * the viewport to be laid out next. And we assume that the * viewports layout manager will give the view it's preferred * size. One exception to this is when the view implements * Scrollable and Scrollable.getViewTracksViewport{Width,Height} * methods return true. If the view is tracking the viewports * width we don't bother with a horizontal scrollbar, similarly * if view.getViewTracksViewport(Height) is true we don't bother * with a vertical scrollbar. */ Component view = (viewport != null) ? viewport.getView() : null; Dimension viewPrefSize = (view != null) ? view.getPreferredSize() : new Dimension(0, 0); Dimension extentSize = (viewport != null) ? viewport.toViewCoordinates(availR.getSize()) : new Dimension(0, 0); boolean viewTracksViewportWidth = false; boolean viewTracksViewportHeight = false; boolean isEmpty = (availR.width < 0 || availR.height < 0); Scrollable sv; // Don't bother checking the Scrollable methods if there is no room // for the viewport, we aren't going to show any scrollbars in this // case anyway. if (!isEmpty && view instanceof Scrollable) { sv = (Scrollable) view; viewTracksViewportWidth = sv.getScrollableTracksViewportWidth(); viewTracksViewportHeight = sv.getScrollableTracksViewportHeight(); } else { sv = null; } /* If there's a vertical scrollbar and we need one, allocate * space for it (we'll make it visible later). A vertical * scrollbar is considered to be fixed width, arbitrary height. */ Rectangle vsbR = new Rectangle(0, isVsbCoversWholeHeight(scrollPane) ? -vpbInsets.top : availR.y - vpbInsets.top, 0, 0); boolean vsbNeeded; if (isEmpty) { vsbNeeded = false; } else if (vsbPolicy == VERTICAL_SCROLLBAR_ALWAYS) { vsbNeeded = true; } else if (vsbPolicy == VERTICAL_SCROLLBAR_NEVER) { vsbNeeded = false; } else { // vsbPolicy == VERTICAL_SCROLLBAR_AS_NEEDED vsbNeeded = !viewTracksViewportHeight && (viewPrefSize.height > extentSize.height || (rowHead != null && rowHead.getView().getPreferredSize().height > extentSize.height)); } if ((vsb != null) && vsbNeeded) { adjustForVSB(true, availR, vsbR, vpbInsets, leftToRight); extentSize = viewport.toViewCoordinates(availR.getSize()); } /* If there's a horizontal scrollbar and we need one, allocate * space for it (we'll make it visible later). A horizontal * scrollbar is considered to be fixed height, arbitrary width. */ Rectangle hsbR = new Rectangle(isHsbCoversWholeWidth(scrollPane) ? -vpbInsets.left : availR.x - vpbInsets.left, 0, 0, 0); boolean hsbNeeded; if (isEmpty) { hsbNeeded = false; } else if (hsbPolicy == HORIZONTAL_SCROLLBAR_ALWAYS) { hsbNeeded = true; } else if (hsbPolicy == HORIZONTAL_SCROLLBAR_NEVER) { hsbNeeded = false; } else { // hsbPolicy == HORIZONTAL_SCROLLBAR_AS_NEEDED hsbNeeded = !viewTracksViewportWidth && (viewPrefSize.width > extentSize.width || (colHead != null && colHead.getView() != null && colHead.getView().getPreferredSize().width > extentSize.width)); } if ((hsb != null) && hsbNeeded) { adjustForHSB(true, availR, hsbR, vpbInsets); /* If we added the horizontal scrollbar then we've implicitly * reduced the vertical space available to the viewport. * As a consequence we may have to add the vertical scrollbar, * if that hasn't been done so already. Of course we * don't bother with any of this if the vsbPolicy is NEVER. */ if ((vsb != null) && !vsbNeeded && (vsbPolicy != VERTICAL_SCROLLBAR_NEVER)) { extentSize = viewport.toViewCoordinates(availR.getSize()); vsbNeeded = viewPrefSize.height > extentSize.height; if (vsbNeeded) { adjustForVSB(true, availR, vsbR, vpbInsets, leftToRight); } } } /* Set the size of the viewport first, and then recheck the Scrollable * methods. Some components base their return values for the Scrollable * methods on the size of the Viewport, so that if we don't * ask after resetting the bounds we may have gotten the wrong * answer. */ if (viewport != null) { viewport.setBounds(availR); // viewport.setViewSize(availR.getSize()); // to fix the strange scroll bar problem reported on http://www.jidesoft.com/forum/viewtopic.php?p=20526#20526 if (sv != null) { extentSize = viewport.toViewCoordinates(availR.getSize()); boolean oldHSBNeeded = hsbNeeded; boolean oldVSBNeeded = vsbNeeded; viewTracksViewportWidth = sv.getScrollableTracksViewportWidth(); viewTracksViewportHeight = sv.getScrollableTracksViewportHeight(); if (vsb != null && vsbPolicy == VERTICAL_SCROLLBAR_AS_NEEDED) { boolean newVSBNeeded = !viewTracksViewportHeight && (viewPrefSize.height > extentSize.height || (rowHead != null && rowHead.getView().getPreferredSize().height > extentSize.height)); if (newVSBNeeded != vsbNeeded) { vsbNeeded = newVSBNeeded; adjustForVSB(vsbNeeded, availR, vsbR, vpbInsets, leftToRight); extentSize = viewport.toViewCoordinates (availR.getSize()); } } if (hsb != null && hsbPolicy == HORIZONTAL_SCROLLBAR_AS_NEEDED) { boolean newHSBbNeeded = !viewTracksViewportWidth && (viewPrefSize.width > extentSize.width || (colHead != null && colHead.getView().getPreferredSize().width > extentSize.width)); if (newHSBbNeeded != hsbNeeded) { hsbNeeded = newHSBbNeeded; adjustForHSB(hsbNeeded, availR, hsbR, vpbInsets); if ((vsb != null) && !vsbNeeded && (vsbPolicy != VERTICAL_SCROLLBAR_NEVER)) { extentSize = viewport.toViewCoordinates (availR.getSize()); vsbNeeded = viewPrefSize.height > extentSize.height; if (vsbNeeded) { adjustForVSB(true, availR, vsbR, vpbInsets, leftToRight); } } if (_rowFoot != null && _rowFoot.isVisible()) { vsbR.x += rowFootR.width; } } } if (oldHSBNeeded != hsbNeeded || oldVSBNeeded != vsbNeeded) { viewport.setBounds(availR); // You could argue that we should recheck the // Scrollable methods again until they stop changing, // but they might never stop changing, so we stop here // and don't do any additional checks. } } } /* We now have the final size of the viewport: availR. * Now fixup the header and scrollbar widths/heights. */ vsbR.height = isVsbCoversWholeHeight(scrollPane) ? scrollPane.getHeight() - 1 : availR.height + vpbInsets.top + vpbInsets.bottom; hsbR.width = isHsbCoversWholeWidth(scrollPane) ? scrollPane.getWidth() - vsbR.width : availR.width + vpbInsets.left + vpbInsets.right; rowHeadR.height = availR.height + vpbInsets.top + vpbInsets.bottom; rowHeadR.y = availR.y - vpbInsets.top; colHeadR.width = availR.width + vpbInsets.left + vpbInsets.right; colHeadR.x = availR.x - vpbInsets.left; colFootR.x = availR.x; colFootR.y = rowHeadR.y + rowHeadR.height; colFootR.width = availR.width; rowFootR.x = availR.x + availR.width; rowFootR.y = availR.y; rowFootR.height = availR.height; vsbR.x += rowFootR.width; hsbR.y += colFootR.height; /* Set the bounds of the remaining components. The scrollbars * are made invisible if they're not needed. */ if (rowHead != null) { rowHead.setBounds(rowHeadR); } if (_rowFoot != null) { _rowFoot.setBounds(rowFootR); } if (colHead != null) { int height = Math.min(colHeadR.height, colHead.getPreferredSize().height); colHead.setBounds(new Rectangle(colHeadR.x, colHeadR.y + colHeadR.height - height, colHeadR.width, height)); } if (_colFoot != null) { int height = Math.min(colFootR.height, _colFoot.getPreferredSize().height); _colFoot.setBounds(new Rectangle(colFootR.x, colFootR.y, colFootR.width, height)); } if (vsb != null) { if (vsbNeeded) { vsb.setVisible(true); if (_vTop == null && _vBottom == null) vsb.setBounds(vsbR); else { Rectangle rect = new Rectangle(vsbR); if (_vTop != null) { Dimension dim = _vTop.getPreferredSize(); rect.y += dim.height; rect.height -= dim.height; _vTop.setVisible(true); _vTop.setBounds(vsbR.x, vsbR.y, vsbR.width, dim.height); } if (_vBottom != null) { Dimension dim = _vBottom.getPreferredSize(); rect.height -= dim.height; _vBottom.setVisible(true); _vBottom.setBounds(vsbR.x, vsbR.y + vsbR.height - dim.height, vsbR.width, dim.height); } vsb.setBounds(rect); } } else { if (viewPrefSize.height > extentSize.height) { vsb.setVisible(true); vsb.setBounds(vsbR.x, vsbR.y, 0, vsbR.height); } else { vsb.setVisible(false); } if (_vTop != null) _vTop.setVisible(false); if (_vBottom != null) _vBottom.setVisible(false); } } if (hsb != null) { if (hsbNeeded) { hsb.setVisible(true); if (_hLeft == null && _hRight == null) hsb.setBounds(hsbR); else { Rectangle rect = new Rectangle(hsbR); if (_hLeft != null) { Dimension dim = _hLeft.getPreferredSize(); rect.x += dim.width; rect.width -= dim.width; _hLeft.setVisible(true); _hLeft.setBounds(hsbR.x, hsbR.y, dim.width, hsbR.height); _hLeft.doLayout(); } if (_hRight != null) { Dimension dim = _hRight.getPreferredSize(); rect.width -= dim.width; _hRight.setVisible(true); _hRight.setBounds(hsbR.x + hsbR.width - dim.width, hsbR.y, dim.width, hsbR.height); } hsb.setBounds(rect); } } else { if (viewPrefSize.width > extentSize.width) { hsb.setVisible(true); hsb.setBounds(hsbR.x, hsbR.y, hsbR.width, 0); } else { hsb.setVisible(false); } if (_hLeft != null) _hLeft.setVisible(false); if (_hRight != null) _hRight.setVisible(false); } } if (lowerLeft != null && lowerLeft.isVisible()) { int height = Math.min(lowerLeft.getPreferredSize().height, colFootR.height); lowerLeft.setBounds(leftToRight ? rowHeadR.x : vsbR.x, colFootR.y != 0 ? colFootR.y : hsbR.y, leftToRight ? rowHeadR.width : vsbR.width, height); } if (lowerRight != null && lowerRight.isVisible()) { int height = Math.min(lowerRight.getPreferredSize().height, colFootR.height); lowerRight.setBounds(leftToRight ? rowFootR.x : rowHeadR.x, colFootR.y != 0 ? colFootR.y : hsbR.y, leftToRight ? rowFootR.width + (isVsbCoversWholeHeight(scrollPane) ? 0 : vsbR.width) : rowHeadR.width, height); } if (upperLeft != null && upperLeft.isVisible()) { int height = Math.min(upperLeft.getPreferredSize().height, colHeadR.height); upperLeft.setBounds(leftToRight ? rowHeadR.x : vsbR.x, colHeadR.y + colHeadR.height - height, leftToRight ? rowHeadR.width : vsbR.width, height); } if (upperRight != null && upperRight.isVisible()) { int height = Math.min(upperRight.getPreferredSize().height, colHeadR.height); upperRight.setBounds(leftToRight ? rowFootR.x : rowHeadR.x, colHeadR.y + colHeadR.height - height, leftToRight ? rowFootR.width + (isVsbCoversWholeHeight(scrollPane) ? 0 : vsbR.width) : rowHeadR.width, height); } }
public void layoutContainer(Container parent) { /* Sync the (now obsolete) policy fields with the * JScrollPane. */ JScrollPane scrollPane = (JScrollPane) parent; vsbPolicy = scrollPane.getVerticalScrollBarPolicy(); hsbPolicy = scrollPane.getHorizontalScrollBarPolicy(); Rectangle availR = scrollPane.getBounds(); availR.x = availR.y = 0; Insets insets = parent.getInsets(); availR.x = insets.left; availR.y = insets.top; availR.width -= insets.left + insets.right; availR.height -= insets.top + insets.bottom; /* Get the scrollPane's orientation. */ boolean leftToRight = scrollPane.getComponentOrientation().isLeftToRight(); /* If there's a visible column header remove the space it * needs from the top of availR. The column header is treated * as if it were fixed height, arbitrary width. */ Rectangle colHeadR = new Rectangle(0, availR.y, 0, 0); int upperHeight = getUpperHeight(); if ((colHead != null) && (colHead.isVisible())) { int colHeadHeight = Math.min(availR.height, upperHeight); colHeadR.height = colHeadHeight; availR.y += colHeadHeight; availR.height -= colHeadHeight; } /* If there's a visible row header remove the space it needs * from the left or right of availR. The row header is treated * as if it were fixed width, arbitrary height. */ Rectangle rowHeadR = new Rectangle(0, 0, 0, 0); if ((rowHead != null) && (rowHead.isVisible())) { int rowHeadWidth = rowHead.getPreferredSize().width; if (upperLeft != null && upperLeft.isVisible()) { rowHeadWidth = Math.max(rowHeadWidth, upperLeft.getPreferredSize().width); } if (lowerLeft != null && lowerLeft.isVisible()) { rowHeadWidth = Math.max(rowHeadWidth, lowerLeft.getPreferredSize().width); } rowHeadWidth = Math.min(availR.width, rowHeadWidth); rowHeadR.width = rowHeadWidth; availR.width -= rowHeadWidth; if (leftToRight) { rowHeadR.x = availR.x; availR.x += rowHeadWidth; } else { rowHeadR.x = availR.x + availR.width; } } /* If there's a JScrollPane.viewportBorder, remove the * space it occupies for availR. */ Border viewportBorder = scrollPane.getViewportBorder(); Insets vpbInsets; if (viewportBorder != null) { vpbInsets = viewportBorder.getBorderInsets(parent); availR.x += vpbInsets.left; availR.y += vpbInsets.top; availR.width -= vpbInsets.left + vpbInsets.right; availR.height -= vpbInsets.top + vpbInsets.bottom; } else { vpbInsets = new Insets(0, 0, 0, 0); } /* If there's a visible row footer remove the space it needs * from the left or right of availR. The row footer is treated * as if it were fixed width, arbitrary height. */ Rectangle rowFootR = new Rectangle(0, 0, 0, 0); if ((_rowFoot != null) && (_rowFoot.isVisible())) { int rowFootWidth = Math.min(availR.width, _rowFoot.getPreferredSize().width); rowFootR.width = rowFootWidth; availR.width -= rowFootWidth; if (leftToRight) { rowFootR.x = availR.x + availR.width; } else { rowFootR.x = availR.x; availR.x += rowFootWidth; } } /* If there's a visible column footer remove the space it * needs from the top of availR. The column footer is treated * as if it were fixed height, arbitrary width. */ Rectangle colFootR = new Rectangle(0, availR.y, 0, 0); int lowerHeight = getLowerHeight(); if ((_colFoot != null) && (_colFoot.isVisible())) { int colFootHeight = Math.min(availR.height, lowerHeight); colFootR.height = colFootHeight; availR.height -= colFootHeight; colFootR.y = availR.y + availR.height; } /* At this point availR is the space available for the viewport * and scrollbars. rowHeadR is correct except for its height and y * and colHeadR is correct except for its width and x. Once we're * through computing the dimensions of these three parts we can * go back and set the dimensions of rowHeadR.height, rowHeadR.y, * colHeadR.width, colHeadR.x and the bounds for the corners. * * We'll decide about putting up scrollbars by comparing the * viewport views preferred size with the viewports extent * size (generally just its size). Using the preferredSize is * reasonable because layout proceeds top down - so we expect * the viewport to be laid out next. And we assume that the * viewports layout manager will give the view it's preferred * size. One exception to this is when the view implements * Scrollable and Scrollable.getViewTracksViewport{Width,Height} * methods return true. If the view is tracking the viewports * width we don't bother with a horizontal scrollbar, similarly * if view.getViewTracksViewport(Height) is true we don't bother * with a vertical scrollbar. */ Component view = (viewport != null) ? viewport.getView() : null; Dimension viewPrefSize = (view != null) ? view.getPreferredSize() : new Dimension(0, 0); Dimension extentSize = (viewport != null) ? viewport.toViewCoordinates(availR.getSize()) : new Dimension(0, 0); boolean viewTracksViewportWidth = false; boolean viewTracksViewportHeight = false; boolean isEmpty = (availR.width < 0 || availR.height < 0); Scrollable sv; // Don't bother checking the Scrollable methods if there is no room // for the viewport, we aren't going to show any scrollbars in this // case anyway. if (!isEmpty && view instanceof Scrollable) { sv = (Scrollable) view; viewTracksViewportWidth = sv.getScrollableTracksViewportWidth(); viewTracksViewportHeight = sv.getScrollableTracksViewportHeight(); } else { sv = null; } /* If there's a vertical scrollbar and we need one, allocate * space for it (we'll make it visible later). A vertical * scrollbar is considered to be fixed width, arbitrary height. */ Rectangle vsbR = new Rectangle(0, isVsbCoversWholeHeight(scrollPane) ? -vpbInsets.top : availR.y - vpbInsets.top, 0, 0); boolean vsbNeeded; if (isEmpty) { vsbNeeded = false; } else if (vsbPolicy == VERTICAL_SCROLLBAR_ALWAYS) { vsbNeeded = true; } else if (vsbPolicy == VERTICAL_SCROLLBAR_NEVER) { vsbNeeded = false; } else { // vsbPolicy == VERTICAL_SCROLLBAR_AS_NEEDED vsbNeeded = !viewTracksViewportHeight && (viewPrefSize.height > extentSize.height || (rowHead != null && rowHead.getView() != null && rowHead.getView().getPreferredSize().height > extentSize.height)); } if ((vsb != null) && vsbNeeded) { adjustForVSB(true, availR, vsbR, vpbInsets, leftToRight); extentSize = viewport.toViewCoordinates(availR.getSize()); } /* If there's a horizontal scrollbar and we need one, allocate * space for it (we'll make it visible later). A horizontal * scrollbar is considered to be fixed height, arbitrary width. */ Rectangle hsbR = new Rectangle(isHsbCoversWholeWidth(scrollPane) ? -vpbInsets.left : availR.x - vpbInsets.left, 0, 0, 0); boolean hsbNeeded; if (isEmpty) { hsbNeeded = false; } else if (hsbPolicy == HORIZONTAL_SCROLLBAR_ALWAYS) { hsbNeeded = true; } else if (hsbPolicy == HORIZONTAL_SCROLLBAR_NEVER) { hsbNeeded = false; } else { // hsbPolicy == HORIZONTAL_SCROLLBAR_AS_NEEDED hsbNeeded = !viewTracksViewportWidth && (viewPrefSize.width > extentSize.width || (colHead != null && colHead.getView() != null && colHead.getView().getPreferredSize().width > extentSize.width)); } if ((hsb != null) && hsbNeeded) { adjustForHSB(true, availR, hsbR, vpbInsets); /* If we added the horizontal scrollbar then we've implicitly * reduced the vertical space available to the viewport. * As a consequence we may have to add the vertical scrollbar, * if that hasn't been done so already. Of course we * don't bother with any of this if the vsbPolicy is NEVER. */ if ((vsb != null) && !vsbNeeded && (vsbPolicy != VERTICAL_SCROLLBAR_NEVER)) { extentSize = viewport.toViewCoordinates(availR.getSize()); vsbNeeded = viewPrefSize.height > extentSize.height; if (vsbNeeded) { adjustForVSB(true, availR, vsbR, vpbInsets, leftToRight); } } } /* Set the size of the viewport first, and then recheck the Scrollable * methods. Some components base their return values for the Scrollable * methods on the size of the Viewport, so that if we don't * ask after resetting the bounds we may have gotten the wrong * answer. */ if (viewport != null) { viewport.setBounds(availR); // viewport.setViewSize(availR.getSize()); // to fix the strange scroll bar problem reported on http://www.jidesoft.com/forum/viewtopic.php?p=20526#20526 if (sv != null) { extentSize = viewport.toViewCoordinates(availR.getSize()); boolean oldHSBNeeded = hsbNeeded; boolean oldVSBNeeded = vsbNeeded; viewTracksViewportWidth = sv.getScrollableTracksViewportWidth(); viewTracksViewportHeight = sv.getScrollableTracksViewportHeight(); if (vsb != null && vsbPolicy == VERTICAL_SCROLLBAR_AS_NEEDED) { boolean newVSBNeeded = !viewTracksViewportHeight && (viewPrefSize.height > extentSize.height || (rowHead != null && rowHead.getView() != null && rowHead.getView().getPreferredSize().height > extentSize.height)); if (newVSBNeeded != vsbNeeded) { vsbNeeded = newVSBNeeded; adjustForVSB(vsbNeeded, availR, vsbR, vpbInsets, leftToRight); extentSize = viewport.toViewCoordinates (availR.getSize()); } } if (hsb != null && hsbPolicy == HORIZONTAL_SCROLLBAR_AS_NEEDED) { boolean newHSBbNeeded = !viewTracksViewportWidth && (viewPrefSize.width > extentSize.width || (colHead != null && colHead.getView() != null && colHead.getView().getPreferredSize().width > extentSize.width)); if (newHSBbNeeded != hsbNeeded) { hsbNeeded = newHSBbNeeded; adjustForHSB(hsbNeeded, availR, hsbR, vpbInsets); if ((vsb != null) && !vsbNeeded && (vsbPolicy != VERTICAL_SCROLLBAR_NEVER)) { extentSize = viewport.toViewCoordinates (availR.getSize()); vsbNeeded = viewPrefSize.height > extentSize.height; if (vsbNeeded) { adjustForVSB(true, availR, vsbR, vpbInsets, leftToRight); } } if (_rowFoot != null && _rowFoot.isVisible()) { vsbR.x += rowFootR.width; } } } if (oldHSBNeeded != hsbNeeded || oldVSBNeeded != vsbNeeded) { viewport.setBounds(availR); // You could argue that we should recheck the // Scrollable methods again until they stop changing, // but they might never stop changing, so we stop here // and don't do any additional checks. } } } /* We now have the final size of the viewport: availR. * Now fixup the header and scrollbar widths/heights. */ vsbR.height = isVsbCoversWholeHeight(scrollPane) ? scrollPane.getHeight() - 1 : availR.height + vpbInsets.top + vpbInsets.bottom; hsbR.width = isHsbCoversWholeWidth(scrollPane) ? scrollPane.getWidth() - vsbR.width : availR.width + vpbInsets.left + vpbInsets.right; rowHeadR.height = availR.height + vpbInsets.top + vpbInsets.bottom; rowHeadR.y = availR.y - vpbInsets.top; colHeadR.width = availR.width + vpbInsets.left + vpbInsets.right; colHeadR.x = availR.x - vpbInsets.left; colFootR.x = availR.x; colFootR.y = rowHeadR.y + rowHeadR.height; colFootR.width = availR.width; rowFootR.x = availR.x + availR.width; rowFootR.y = availR.y; rowFootR.height = availR.height; vsbR.x += rowFootR.width; hsbR.y += colFootR.height; /* Set the bounds of the remaining components. The scrollbars * are made invisible if they're not needed. */ if (rowHead != null) { rowHead.setBounds(rowHeadR); } if (_rowFoot != null) { _rowFoot.setBounds(rowFootR); } if (colHead != null) { int height = Math.min(colHeadR.height, colHead.getPreferredSize().height); colHead.setBounds(new Rectangle(colHeadR.x, colHeadR.y + colHeadR.height - height, colHeadR.width, height)); } if (_colFoot != null) { int height = Math.min(colFootR.height, _colFoot.getPreferredSize().height); _colFoot.setBounds(new Rectangle(colFootR.x, colFootR.y, colFootR.width, height)); } if (vsb != null) { if (vsbNeeded) { vsb.setVisible(true); if (_vTop == null && _vBottom == null) vsb.setBounds(vsbR); else { Rectangle rect = new Rectangle(vsbR); if (_vTop != null) { Dimension dim = _vTop.getPreferredSize(); rect.y += dim.height; rect.height -= dim.height; _vTop.setVisible(true); _vTop.setBounds(vsbR.x, vsbR.y, vsbR.width, dim.height); } if (_vBottom != null) { Dimension dim = _vBottom.getPreferredSize(); rect.height -= dim.height; _vBottom.setVisible(true); _vBottom.setBounds(vsbR.x, vsbR.y + vsbR.height - dim.height, vsbR.width, dim.height); } vsb.setBounds(rect); } } else { if (viewPrefSize.height > extentSize.height) { vsb.setVisible(true); vsb.setBounds(vsbR.x, vsbR.y, 0, vsbR.height); } else { vsb.setVisible(false); } if (_vTop != null) _vTop.setVisible(false); if (_vBottom != null) _vBottom.setVisible(false); } } if (hsb != null) { if (hsbNeeded) { hsb.setVisible(true); if (_hLeft == null && _hRight == null) hsb.setBounds(hsbR); else { Rectangle rect = new Rectangle(hsbR); if (_hLeft != null) { Dimension dim = _hLeft.getPreferredSize(); rect.x += dim.width; rect.width -= dim.width; _hLeft.setVisible(true); _hLeft.setBounds(hsbR.x, hsbR.y, dim.width, hsbR.height); _hLeft.doLayout(); } if (_hRight != null) { Dimension dim = _hRight.getPreferredSize(); rect.width -= dim.width; _hRight.setVisible(true); _hRight.setBounds(hsbR.x + hsbR.width - dim.width, hsbR.y, dim.width, hsbR.height); } hsb.setBounds(rect); } } else { if (viewPrefSize.width > extentSize.width) { hsb.setVisible(true); hsb.setBounds(hsbR.x, hsbR.y, hsbR.width, 0); } else { hsb.setVisible(false); } if (_hLeft != null) _hLeft.setVisible(false); if (_hRight != null) _hRight.setVisible(false); } } if (lowerLeft != null && lowerLeft.isVisible()) { int height = Math.min(lowerLeft.getPreferredSize().height, colFootR.height); lowerLeft.setBounds(leftToRight ? rowHeadR.x : vsbR.x, colFootR.y != 0 ? colFootR.y : hsbR.y, leftToRight ? rowHeadR.width : vsbR.width, height); } if (lowerRight != null && lowerRight.isVisible()) { int height = Math.min(lowerRight.getPreferredSize().height, colFootR.height); lowerRight.setBounds(leftToRight ? rowFootR.x : rowHeadR.x, colFootR.y != 0 ? colFootR.y : hsbR.y, leftToRight ? rowFootR.width + (isVsbCoversWholeHeight(scrollPane) ? 0 : vsbR.width) : rowHeadR.width, height); } if (upperLeft != null && upperLeft.isVisible()) { int height = Math.min(upperLeft.getPreferredSize().height, colHeadR.height); upperLeft.setBounds(leftToRight ? rowHeadR.x : vsbR.x, colHeadR.y + colHeadR.height - height, leftToRight ? rowHeadR.width : vsbR.width, height); } if (upperRight != null && upperRight.isVisible()) { int height = Math.min(upperRight.getPreferredSize().height, colHeadR.height); upperRight.setBounds(leftToRight ? rowFootR.x : rowHeadR.x, colHeadR.y + colHeadR.height - height, leftToRight ? rowFootR.width + (isVsbCoversWholeHeight(scrollPane) ? 0 : vsbR.width) : rowHeadR.width, height); } }
diff --git a/SWADroid/src/es/ugr/swad/swadroid/SWADMain.java b/SWADroid/src/es/ugr/swad/swadroid/SWADMain.java index 6d020ed1..f3a3b575 100644 --- a/SWADroid/src/es/ugr/swad/swadroid/SWADMain.java +++ b/SWADroid/src/es/ugr/swad/swadroid/SWADMain.java @@ -1,864 +1,865 @@ /* * This file is part of SWADroid. * * Copyright (C) 2010 Juan Miguel Boyero Corral <[email protected]> * * SWADroid is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SWADroid is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with SWADroid. If not, see <http://www.gnu.org/licenses/>. */ package es.ugr.swad.swadroid; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.annotation.TargetApi; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.os.Build; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ArrayAdapter; import android.widget.ExpandableListView; import android.widget.ExpandableListView.OnChildClickListener; import android.widget.SimpleCursorAdapter; import android.widget.Spinner; import android.widget.Toast; import com.bugsense.trace.BugSenseHandler; import es.ugr.swad.swadroid.gui.DialogFactory; import es.ugr.swad.swadroid.gui.ImageExpandableListAdapter; import es.ugr.swad.swadroid.gui.MenuExpandableListActivity; import es.ugr.swad.swadroid.model.Course; import es.ugr.swad.swadroid.model.DataBaseHelper; import es.ugr.swad.swadroid.model.Model; import es.ugr.swad.swadroid.modules.Courses; import es.ugr.swad.swadroid.modules.GenerateQR; import es.ugr.swad.swadroid.modules.Messages; import es.ugr.swad.swadroid.modules.Notices; import es.ugr.swad.swadroid.modules.downloads.DownloadsManager; import es.ugr.swad.swadroid.modules.groups.MyGroupsManager; import es.ugr.swad.swadroid.modules.information.Information; import es.ugr.swad.swadroid.modules.notifications.Notifications; import es.ugr.swad.swadroid.modules.rollcall.Rollcall; import es.ugr.swad.swadroid.modules.tests.Tests; import es.ugr.swad.swadroid.ssl.SecureConnection; import es.ugr.swad.swadroid.sync.AccountAuthenticator; import es.ugr.swad.swadroid.sync.SyncUtils; import es.ugr.swad.swadroid.utils.Utils; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Main class of the application. * * @author Juan Miguel Boyero Corral <[email protected]> * @author Antonio Aguilera Malagon <[email protected]> * @author Helena Rodriguez Gijon <[email protected]> * @author Jose Antonio Guerrero Aviles <[email protected]> */ public class SWADMain extends MenuExpandableListActivity { /** * Application preferences */ Preferences prefs; /** * SSL connection */ SecureConnection conn; /** * Array of strings for main ListView */ protected String[] functions; /** * Function name field */ private final String NAME = "listText"; /** * Function text field */ private final String IMAGE = "listIcon"; /** * Code of selected course */ private long courseCode; /** * Cursor for database access */ private Cursor dbCursor; /** * User courses list */ private List<Model> listCourses; /** * Tests tag name for Logcat */ public static final String TAG = Constants.APP_TAG; /** * Indicates if it is the first run */ private boolean firstRun = false; /** * Current role 2 - student 3 - teacher -1 - none role was chosen */ private int currentRole = -1; private boolean dBCleaned = false; private ExpandableListView mExpandableListView; private ImageExpandableListAdapter mExpandableListAdapter; private OnChildClickListener mExpandableClickListener; private final ArrayList<HashMap<String, Object>> mHeaderData = new ArrayList<HashMap<String, Object>>(); private final ArrayList<ArrayList<HashMap<String, Object>>> mChildData = new ArrayList<ArrayList<HashMap<String, Object>>>(); private final ArrayList<HashMap<String, Object>> mMessagesData = new ArrayList<HashMap<String, Object>>(); private final ArrayList<HashMap<String, Object>> mUsersData = new ArrayList<HashMap<String, Object>>(); /** * Gets the database helper * * @return the database helper */ public static DataBaseHelper getDbHelper() { return dbHelper; } /** * Shows initial dialog after application upgrade. */ public void showUpgradeDialog(Context context) { AlertDialog alertDialog = DialogFactory.createWebViewDialog(context, R.string.changelogTitle, R.raw.changes); alertDialog.show(); } /* (non-Javadoc) * @see android.app.Activity#onCreate() */ @Override public void onCreate(Bundle icicle) { int lastVersion, currentVersion; Intent activity; //Initialize Bugsense plugin try { BugSenseHandler.initAndStartSession(this, Constants.BUGSENSE_API_KEY); } catch (Exception e) { Log.e(TAG, "Error initializing BugSense", e); } //Initialize screen super.onCreate(icicle); setContentView(R.layout.main); initializeMainViews(); //Initialize preferences prefs = new Preferences(this); try { //Initialize HTTPS connections /* * Terena root certificate is not included by default on Gingerbread and older * If Android API < 11 (HONEYCOMB) add Terena certificate manually */ if(Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { conn = new SecureConnection(); conn.initSecureConnection(this); Log.i(TAG, "Android API < 11 (HONEYCOMB). Adding Terena certificate manually"); } else { Log.i(TAG, "Android API >= 11 (HONEYCOMB). Using Terena built-in certificate"); } //Check if this is the first run after an install or upgrade lastVersion = Preferences.getLastVersion(); currentVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode; dbHelper.initializeDB(); //lastVersion = 57; //currentVersion = 58; //If this is the first run, show configuration dialog if (lastVersion == 0) { //Configure automatic synchronization Preferences.setSyncTime(String.valueOf(Constants.DEFAULT_SYNC_TIME)); activity = new Intent(this, AccountAuthenticator.class); startActivity(activity); Preferences.setLastVersion(currentVersion); firstRun = true; Constants.setSelectedCourseCode(-1); Constants.setSelectedCourseShortName(""); Constants.setSelectedCourseFullName(""); Constants.setCurrentUserRole(-1); //If this is an upgrade, show upgrade dialog } else if (lastVersion < currentVersion) { showUpgradeDialog(this); dbHelper.upgradeDB(this); if(lastVersion < 52) { //Encrypts users table dbHelper.encryptUsers(); //If the app is updating from an unencrypted user password version, encrypt user password Preferences.upgradeCredentials(); Preferences.setSyncTime(String.valueOf(Constants.DEFAULT_SYNC_TIME)); } else if(lastVersion < 57) { //Reconfigure automatic synchronization SyncUtils.removePeriodicSync(Constants.AUTHORITY, Bundle.EMPTY, this); if(!Preferences.getSyncTime().equals("0") && Preferences.isSyncEnabled()) { SyncUtils.addPeriodicSync(Constants.AUTHORITY, Bundle.EMPTY, Long.valueOf(Preferences.getSyncTime()), this); } } Preferences.setLastVersion(currentVersion); } listCourses = dbHelper.getAllRows(Constants.DB_TABLE_COURSES, "", "shortName"); if (listCourses.size() > 0) { Course c = (Course) listCourses.get(Preferences.getLastCourseSelected()); Constants.setSelectedCourseCode(c.getId()); Constants.setSelectedCourseShortName(c.getShortName()); Constants.setSelectedCourseFullName(c.getFullName()); Constants.setCurrentUserRole(c.getUserRole()); } else { Constants.setSelectedCourseCode(-1); Constants.setSelectedCourseShortName(""); Constants.setSelectedCourseFullName(""); Constants.setCurrentUserRole(-1); } currentRole = -1; } catch (Exception ex) { error(TAG, ex.getMessage(), ex, true); } } /* * (non-Javadoc) * @see android.app.Activity#onResume() */ @Override protected void onResume() { super.onResume(); if (isUserOrPasswordEmpty() && (listCourses.size() == 0)) { startActivityForResult(new Intent(this, LoginActivity.class), Constants.LOGIN_REQUEST_CODE); } else { if (!Preferences.isPreferencesChanged() && !Utils.isDbCleaned()) { createSpinnerAdapter(); if (!firstRun) { courseCode = Constants.getSelectedCourseCode(); createMenu(); } } else { Preferences.setPreferencesChanged(false); Utils.setDbCleaned(false); setMenuDbClean(); } } } /* (non-Javadoc) * @see android.app.Activity#onDestroy() */ @Override protected void onDestroy() { try { BugSenseHandler.closeSession(this); } catch (Exception e) { Log.e(TAG, "Error initializing BugSense", e); } super.onDestroy(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == Activity.RESULT_OK) { switch (requestCode) { //After get the list of courses, a dialog is launched to choice the course case Constants.COURSES_REQUEST_CODE: setMenuDbClean(); createSpinnerAdapter(); createMenu(); //User credentials are correct. Set periodic synchronization if enabled if (!Preferences.getSyncTime().equals("0") && Preferences.isSyncEnabled() && SyncUtils.isPeriodicSynced(this)) { SyncUtils.addPeriodicSync(Constants.AUTHORITY, Bundle.EMPTY, Long.parseLong(Preferences.getSyncTime()), this); } showProgress(false); break; case Constants.LOGIN_REQUEST_CODE: getCurrentCourses(); break; } } else if (resultCode == Activity.RESULT_CANCELED) { switch (requestCode) { //After get the list of courses, a dialog is launched to choice the course case Constants.COURSES_REQUEST_CODE: //User credentials are wrong. Remove periodic synchronization SyncUtils.removePeriodicSync(Constants.AUTHORITY, Bundle.EMPTY, this); showProgress(false); break; case Constants.LOGIN_REQUEST_CODE: finish(); break; } } } private void createSpinnerAdapter() { Spinner spinner = (Spinner) this.findViewById(R.id.spinner); listCourses = dbHelper.getAllRows(Constants.DB_TABLE_COURSES, null, "fullName"); dbCursor = dbHelper.getDb().getCursor(Constants.DB_TABLE_COURSES, null, "fullName"); startManagingCursor(dbCursor); if (listCourses.size() != 0) { SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, dbCursor, new String[]{"fullName"}, new int[]{android.R.id.text1}); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); spinner.setOnItemSelectedListener(new onItemSelectedListener()); if (Preferences.getLastCourseSelected() < listCourses.size()) spinner.setSelection(Preferences.getLastCourseSelected()); else spinner.setSelection(0); spinner.setOnTouchListener(Spinner_OnTouch); } else { cleanSpinner(); } } /** * Create an empty spinner. It is called when the database is cleaned. */ private void cleanSpinner() { Spinner spinner = (Spinner) this.findViewById(R.id.spinner); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, new String[]{getString(R.string.clickToGetCourses)}); spinner.setAdapter(adapter); spinner.setOnTouchListener(Spinner_OnTouch); } private class onItemSelectedListener implements OnItemSelectedListener { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if (!listCourses.isEmpty()) { Preferences.setLastCourseSelected(position); Course courseSelected = (Course) listCourses.get(position); courseCode = courseSelected.getId(); Constants.setSelectedCourseCode(courseCode); Constants.setSelectedCourseShortName(courseSelected.getShortName()); Constants.setSelectedCourseFullName(courseSelected.getFullName()); Constants.setCurrentUserRole(courseSelected.getUserRole()); createMenu(); } } @Override public void onNothingSelected(AdapterView<?> arg0) { } } private final View.OnTouchListener Spinner_OnTouch = new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_UP) { if (dbHelper.getAllRows(Constants.DB_TABLE_COURSES).size() == 0) { if (Utils.connectionAvailable(getApplicationContext())) getCurrentCourses(); //else } else { v.performClick(); } } return true; } }; private void getCurrentCourses() { showProgress(true); Intent activity; activity = new Intent(this, Courses.class); startActivityForResult(activity, Constants.COURSES_REQUEST_CODE); } private void createMenu() { if (listCourses.size() != 0) { Course courseSelected; if (Constants.getSelectedCourseCode() != -1) { courseSelected = (Course) dbHelper.getRow(Constants.DB_TABLE_COURSES, "id", String.valueOf(Constants.getSelectedCourseCode())); } else { int lastSelected = Preferences.getLastCourseSelected(); if (lastSelected != -1 && lastSelected < listCourses.size()) { courseSelected = (Course) listCourses.get(lastSelected); Constants.setSelectedCourseCode(courseSelected.getId()); Constants.setSelectedCourseShortName(courseSelected.getShortName()); Constants.setSelectedCourseFullName(courseSelected.getFullName()); Constants.setCurrentUserRole(courseSelected.getUserRole()); Preferences.setLastCourseSelected(lastSelected); } else { courseSelected = (Course) listCourses.get(0); Constants.setSelectedCourseCode(courseSelected.getId()); Constants.setSelectedCourseShortName(courseSelected.getShortName()); Constants.setSelectedCourseFullName(courseSelected.getFullName()); Constants.setCurrentUserRole(courseSelected.getUserRole()); Preferences.setLastCourseSelected(0); } } if (courseSelected != null) { if ((mExpandableListView.getAdapter() == null) || dBCleaned) { createBaseMenu(); } int userRole = courseSelected.getUserRole(); if ((userRole == Constants.TEACHER_TYPE_CODE) && (currentRole != Constants.TEACHER_TYPE_CODE)) changeToTeacherMenu(); if ((userRole == Constants.STUDENT_TYPE_CODE) && (currentRole != Constants.STUDENT_TYPE_CODE)) changeToStudentMenu(); dBCleaned = false; } } } /** * Creates base menu. The menu base is common for students and teachers. * Sets currentRole to student role */ private void createBaseMenu() { mExpandableListView.setVisibility(View.VISIBLE); if (mExpandableListView.getAdapter() == null || currentRole == -1) { //the menu base is equal to students menu. currentRole = Constants.STUDENT_TYPE_CODE; //Order: // 1- Course // 2- Evaluation // 3- Messages // 4- Enrollment // 5- Users final HashMap<String, Object> courses = new HashMap<String, Object>(); courses.put(NAME, getString(R.string.course)); courses.put(IMAGE, getResources().getDrawable(R.drawable.crs)); mHeaderData.add(courses); final HashMap<String, Object> evaluation = new HashMap<String, Object>(); evaluation.put(NAME, getString(R.string.evaluation)); evaluation.put(IMAGE, getResources().getDrawable(R.drawable.grades)); mHeaderData.add(evaluation); final HashMap<String, Object> users = new HashMap<String, Object>(); users.put(NAME, getString(R.string.users)); users.put(IMAGE, getResources().getDrawable(R.drawable.users)); mHeaderData.add(users); final HashMap<String, Object> messages = new HashMap<String, Object>(); messages.put(NAME, getString(R.string.messages)); messages.put(IMAGE, getResources().getDrawable(R.drawable.msg)); mHeaderData.add(messages); final ArrayList<HashMap<String, Object>> courseData = new ArrayList<HashMap<String, Object>>(); mChildData.add(courseData); final ArrayList<HashMap<String, Object>> evaluationData = new ArrayList<HashMap<String, Object>>(); mChildData.add(evaluationData); mChildData.add(mUsersData); mChildData.add(mMessagesData); HashMap<String, Object> map; //Course category //Introduction map = new HashMap<String, Object>(); map.put(NAME, getString(R.string.introductionModuleLabel)); map.put(IMAGE, getResources().getDrawable(R.drawable.info)); courseData.add(map); //Teaching Guide map = new HashMap<String, Object>(); map.put(NAME, getString(R.string.teachingguideModuleLabel)); map.put(IMAGE, getResources().getDrawable(R.drawable.file)); courseData.add(map); //Syllabus (lectures) map = new HashMap<String, Object>(); map.put(NAME, getString(R.string.syllabusLecturesModuleLabel)); map.put(IMAGE, getResources().getDrawable(R.drawable.syllabus)); courseData.add(map); //Syllabus (practicals) map = new HashMap<String, Object>(); map.put(NAME, getString(R.string.syllabusPracticalsModuleLabel)); map.put(IMAGE, getResources().getDrawable(R.drawable.lab)); courseData.add(map); //Documents map = new HashMap<String, Object>(); map.put(NAME, getString(R.string.documentsDownloadModuleLabel)); - map.put(IMAGE, getResources().getDrawable(R.drawable.folder)); courseData.add(map); + map.put(IMAGE, getResources().getDrawable(R.drawable.folder)); + courseData.add(map); //Shared area map = new HashMap<String, Object>(); map.put(NAME, getString(R.string.sharedsDownloadModuleLabel)); map.put(IMAGE, getResources().getDrawable(R.drawable.folder_users)); courseData.add(map); //Bibliography map = new HashMap<String, Object>(); map.put(NAME, getString(R.string.bibliographyModuleLabel)); map.put(IMAGE, getResources().getDrawable(R.drawable.book)); courseData.add(map); //FAQs map = new HashMap<String, Object>(); map.put(NAME, getString(R.string.faqsModuleLabel)); map.put(IMAGE, getResources().getDrawable(R.drawable.faq)); courseData.add(map); //Links map = new HashMap<String, Object>(); map.put(NAME, getString(R.string.linksModuleLabel)); map.put(IMAGE, getResources().getDrawable(R.drawable.link)); courseData.add(map); //Evaluation category //Assessment system map = new HashMap<String, Object>(); map.put(NAME, getString(R.string.assessmentModuleLabel)); map.put(IMAGE, getResources().getDrawable(R.drawable.info)); evaluationData.add(map); //Test map = new HashMap<String, Object>(); map.put(NAME, getString(R.string.testsModuleLabel)); map.put(IMAGE, getResources().getDrawable(R.drawable.test)); evaluationData.add(map); //Users category //Groups map = new HashMap<String, Object>(); map.put(NAME, getString(R.string.myGroupsModuleLabel)); map.put(IMAGE, getResources().getDrawable(R.drawable.my_groups)); mUsersData.add(map); //Generate QR code map = new HashMap<String, Object>(); map.put(NAME, getString(R.string.generateQRModuleLabel)); map.put(IMAGE, getResources().getDrawable(R.drawable.qr)); mUsersData.add(map); //Messages category //Notifications map = new HashMap<String, Object>(); map.put(NAME, getString(R.string.notificationsModuleLabel)); map.put(IMAGE, getResources().getDrawable(R.drawable.notif)); mMessagesData.add(map); //Messages map = new HashMap<String, Object>(); map.put(NAME, getString(R.string.messagesModuleLabel)); map.put(IMAGE, getResources().getDrawable(R.drawable.msg_write)); mMessagesData.add(map); mExpandableListAdapter = new ImageExpandableListAdapter( this, mHeaderData, R.layout.image_list_item, new String[]{NAME}, // the name of the field data new int[]{R.id.listText}, // the text field to populate with the field data mChildData, 0, null, new int[]{} ); mExpandableListView.setAdapter(mExpandableListAdapter); } } /** * Adapts the current menu to students view. Removes options unique to teachers and adds options unique to students */ private void changeToStudentMenu() { if (currentRole == Constants.TEACHER_TYPE_CODE) { //Removes Publish Note from messages menu mExpandableListAdapter.removeChild(Constants.MESSAGES_GROUP, Constants.PUBLISH_NOTE_CHILD); //Removes Rollcall from users menu mExpandableListAdapter.removeChild(Constants.USERS_GROUP, Constants.ROLLCALL_CHILD); } currentRole = Constants.STUDENT_TYPE_CODE; } /** * Adapts the current menu to teachers view. Removes options unique to students and adds options unique to teachers */ private void changeToTeacherMenu() { if (currentRole == Constants.STUDENT_TYPE_CODE) { HashMap<String, Object> map = new HashMap<String, Object>(); map.put(NAME, getString(R.string.noticesModuleLabel)); map.put(IMAGE, getResources().getDrawable(R.drawable.note)); mMessagesData.add(map); map = new HashMap<String, Object>(); map.put(NAME, getString(R.string.rollcallModuleLabel)); map.put(IMAGE, getResources().getDrawable(R.drawable.roll_call)); mUsersData.add(map); mExpandableListAdapter = new ImageExpandableListAdapter(this, mHeaderData, R.layout.image_list_item, new String[] { NAME }, new int[] { R.id.listText }, mChildData, 0, null, new int[] {} ); mExpandableListView.setAdapter(mExpandableListAdapter); } currentRole = Constants.TEACHER_TYPE_CODE; } /** * Creates an empty Menu and spinner when the data base is empty */ protected void setMenuDbClean() { Utils.setDbCleaned(false); Constants.setSelectedCourseCode(-1); Constants.setSelectedCourseShortName(""); Constants.setSelectedCourseFullName(""); Constants.setCurrentUserRole(-1); Preferences.setLastCourseSelected(-1); dBCleaned = true; listCourses.clear(); cleanSpinner(); mExpandableListView.setVisibility(View.GONE); } // TODO /** * Launches an action when refresh button is pushed * * @param v Actual view */ public void onRefreshClick(View v) { getCurrentCourses(); } /** * @return true if user or password preference is empty */ private boolean isUserOrPasswordEmpty() { return TextUtils.isEmpty(Preferences.getUserID()) || TextUtils.isEmpty(Preferences.getUserPassword()); } private void initializeMainViews() { mExpandableListView = (ExpandableListView) findViewById(R.id.expandableList); mExpandableClickListener = new OnChildClickListener() { @Override public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) { // Get the item that was clicked Object o = parent.getExpandableListAdapter().getChild(groupPosition, childPosition); @SuppressWarnings("unchecked") String keyword = (String) ((Map<String, Object>) o).get(NAME); // boolean rollCallAndroidVersionOK = // (android.os.Build.VERSION.SDK_INT >= // android.os.Build.VERSION_CODES.FROYO); // PackageManager pm = getPackageManager(); // boolean rearCam; // It would be safer to use the constant // PackageManager.FEATURE_CAMERA_FRONT // but since it is not defined for Android 2.2, I substituted // the literal value // frontCam = // pm.hasSystemFeature("android.hardware.camera.front"); // rearCam = pm.hasSystemFeature(PackageManager.FEATURE_CAMERA); Intent activity; Context ctx = getApplicationContext(); if (keyword.equals(getString(R.string.notificationsModuleLabel))) { activity = new Intent(ctx, Notifications.class); startActivityForResult(activity, Constants.NOTIFICATIONS_REQUEST_CODE); } else if (keyword.equals(getString(R.string.testsModuleLabel))) { activity = new Intent(ctx, Tests.class); startActivityForResult(activity, Constants.TESTS_REQUEST_CODE); } else if (keyword.equals(getString(R.string.messagesModuleLabel))) { activity = new Intent(ctx, Messages.class); activity.putExtra("eventCode", Long.valueOf(0)); startActivityForResult(activity, Constants.MESSAGES_REQUEST_CODE); } else if (keyword.equals(getString(R.string.noticesModuleLabel))) { activity = new Intent(ctx, Notices.class); startActivityForResult(activity, Constants.NOTICES_REQUEST_CODE); } else if (keyword.equals(getString(R.string.rollcallModuleLabel))) { activity = new Intent(ctx, Rollcall.class); startActivityForResult(activity, Constants.ROLLCALL_REQUEST_CODE); } else if (keyword.equals(getString(R.string.generateQRModuleLabel))) { activity = new Intent(ctx, GenerateQR.class); startActivityForResult(activity, Constants.GENERATE_QR_REQUEST_CODE); } else if (keyword.equals(getString(R.string.documentsDownloadModuleLabel))) { activity = new Intent(ctx, DownloadsManager.class); activity.putExtra("downloadsAreaCode", Constants.DOCUMENTS_AREA_CODE); startActivityForResult(activity, Constants.DOWNLOADSMANAGER_REQUEST_CODE); } else if (keyword.equals(getString(R.string.sharedsDownloadModuleLabel))) { activity = new Intent(ctx, DownloadsManager.class); activity.putExtra("downloadsAreaCode", Constants.SHARE_AREA_CODE); startActivityForResult(activity, Constants.DOWNLOADSMANAGER_REQUEST_CODE); } else if (keyword.equals(getString(R.string.myGroupsModuleLabel))) { activity = new Intent(ctx, MyGroupsManager.class); activity.putExtra("courseCode", Constants.getSelectedCourseCode()); startActivityForResult(activity, Constants.MYGROUPSMANAGER_REQUEST_CODE); } else if (keyword.equals(getString(R.string.introductionModuleLabel))) { activity = new Intent(ctx, Information.class); activity.putExtra("requestCode", Constants.INTRODUCTION_REQUEST_CODE); startActivityForResult(activity, Constants.INTRODUCTION_REQUEST_CODE); } else if (keyword.equals(getString(R.string.faqsModuleLabel))) { activity = new Intent(ctx, Information.class); activity.putExtra("requestCode", Constants.FAQS_REQUEST_CODE); startActivityForResult(activity, Constants.FAQS_REQUEST_CODE); } else if (keyword.equals(getString(R.string.bibliographyModuleLabel))) { activity = new Intent(ctx, Information.class); activity.putExtra("requestCode", Constants.BIBLIOGRAPHY_REQUEST_CODE); startActivityForResult(activity, Constants.BIBLIOGRAPHY_REQUEST_CODE); } else if (keyword.equals(getString(R.string.syllabusPracticalsModuleLabel))) { activity = new Intent(ctx, Information.class); activity.putExtra("requestCode", Constants.SYLLABUSPRACTICALS_REQUEST_CODE); startActivityForResult(activity, Constants.SYLLABUSPRACTICALS_REQUEST_CODE); } else if (keyword.equals(getString(R.string.syllabusLecturesModuleLabel))) { activity = new Intent(ctx, Information.class); activity.putExtra("requestCode", Constants.SYLLABUSLECTURES_REQUEST_CODE); startActivityForResult(activity, Constants.SYLLABUSLECTURES_REQUEST_CODE); } else if (keyword.equals(getString(R.string.linksModuleLabel))) { activity = new Intent(ctx, Information.class); activity.putExtra("requestCode", Constants.LINKS_REQUEST_CODE); startActivityForResult(activity, Constants.LINKS_REQUEST_CODE); } else if (keyword.equals(getString(R.string.teachingguideModuleLabel))) { activity = new Intent(ctx, Information.class); activity.putExtra("requestCode", Constants.TEACHINGGUIDE_REQUEST_CODE); startActivityForResult(activity, Constants.TEACHINGGUIDE_REQUEST_CODE); } else if (keyword.equals(getString(R.string.assessmentModuleLabel))) { activity = new Intent(ctx, Information.class); activity.putExtra("requestCode", Constants.ASSESSMENT_REQUEST_CODE); startActivityForResult(activity, Constants.ASSESSMENT_REQUEST_CODE); } return true; } }; mExpandableListView.setOnChildClickListener(mExpandableClickListener); } /** * Shows the progress UI and hides the login form. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) private void showProgress(final boolean show) { final View course_list = findViewById(R.id.courses_list_view); final View progressAnimation = findViewById(R.id.get_courses_status); // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow // for very easy animations. If available, use these APIs to fade-in // the progress spinner. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) { int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime); progressAnimation.setVisibility(View.VISIBLE); progressAnimation.animate() .setDuration(shortAnimTime) .alpha(show ? 1 : 0) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { progressAnimation.setVisibility(show ? View.VISIBLE : View.GONE); } }); course_list.setVisibility(View.VISIBLE); course_list.animate() .setDuration(shortAnimTime) .alpha(show ? 0 : 1) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { course_list.setVisibility(show ? View.GONE : View.VISIBLE); } }); } else { // The ViewPropertyAnimator APIs are not available, so simply show // and hide the relevant UI components. progressAnimation.setVisibility(show ? View.VISIBLE : View.GONE); course_list.setVisibility(show ? View.GONE : View.VISIBLE); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main_activity_actions, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_refresh: getCurrentCourses(); return true; default: return super.onOptionsItemSelected(item); } } }
true
true
private void createBaseMenu() { mExpandableListView.setVisibility(View.VISIBLE); if (mExpandableListView.getAdapter() == null || currentRole == -1) { //the menu base is equal to students menu. currentRole = Constants.STUDENT_TYPE_CODE; //Order: // 1- Course // 2- Evaluation // 3- Messages // 4- Enrollment // 5- Users final HashMap<String, Object> courses = new HashMap<String, Object>(); courses.put(NAME, getString(R.string.course)); courses.put(IMAGE, getResources().getDrawable(R.drawable.crs)); mHeaderData.add(courses); final HashMap<String, Object> evaluation = new HashMap<String, Object>(); evaluation.put(NAME, getString(R.string.evaluation)); evaluation.put(IMAGE, getResources().getDrawable(R.drawable.grades)); mHeaderData.add(evaluation); final HashMap<String, Object> users = new HashMap<String, Object>(); users.put(NAME, getString(R.string.users)); users.put(IMAGE, getResources().getDrawable(R.drawable.users)); mHeaderData.add(users); final HashMap<String, Object> messages = new HashMap<String, Object>(); messages.put(NAME, getString(R.string.messages)); messages.put(IMAGE, getResources().getDrawable(R.drawable.msg)); mHeaderData.add(messages); final ArrayList<HashMap<String, Object>> courseData = new ArrayList<HashMap<String, Object>>(); mChildData.add(courseData); final ArrayList<HashMap<String, Object>> evaluationData = new ArrayList<HashMap<String, Object>>(); mChildData.add(evaluationData); mChildData.add(mUsersData); mChildData.add(mMessagesData); HashMap<String, Object> map; //Course category //Introduction map = new HashMap<String, Object>(); map.put(NAME, getString(R.string.introductionModuleLabel)); map.put(IMAGE, getResources().getDrawable(R.drawable.info)); courseData.add(map); //Teaching Guide map = new HashMap<String, Object>(); map.put(NAME, getString(R.string.teachingguideModuleLabel)); map.put(IMAGE, getResources().getDrawable(R.drawable.file)); courseData.add(map); //Syllabus (lectures) map = new HashMap<String, Object>(); map.put(NAME, getString(R.string.syllabusLecturesModuleLabel)); map.put(IMAGE, getResources().getDrawable(R.drawable.syllabus)); courseData.add(map); //Syllabus (practicals) map = new HashMap<String, Object>(); map.put(NAME, getString(R.string.syllabusPracticalsModuleLabel)); map.put(IMAGE, getResources().getDrawable(R.drawable.lab)); courseData.add(map); //Documents map = new HashMap<String, Object>(); map.put(NAME, getString(R.string.documentsDownloadModuleLabel)); map.put(IMAGE, getResources().getDrawable(R.drawable.folder)); courseData.add(map); //Shared area map = new HashMap<String, Object>(); map.put(NAME, getString(R.string.sharedsDownloadModuleLabel)); map.put(IMAGE, getResources().getDrawable(R.drawable.folder_users)); courseData.add(map); //Bibliography map = new HashMap<String, Object>(); map.put(NAME, getString(R.string.bibliographyModuleLabel)); map.put(IMAGE, getResources().getDrawable(R.drawable.book)); courseData.add(map); //FAQs map = new HashMap<String, Object>(); map.put(NAME, getString(R.string.faqsModuleLabel)); map.put(IMAGE, getResources().getDrawable(R.drawable.faq)); courseData.add(map); //Links map = new HashMap<String, Object>(); map.put(NAME, getString(R.string.linksModuleLabel)); map.put(IMAGE, getResources().getDrawable(R.drawable.link)); courseData.add(map); //Evaluation category //Assessment system map = new HashMap<String, Object>(); map.put(NAME, getString(R.string.assessmentModuleLabel)); map.put(IMAGE, getResources().getDrawable(R.drawable.info)); evaluationData.add(map); //Test map = new HashMap<String, Object>(); map.put(NAME, getString(R.string.testsModuleLabel)); map.put(IMAGE, getResources().getDrawable(R.drawable.test)); evaluationData.add(map); //Users category //Groups map = new HashMap<String, Object>(); map.put(NAME, getString(R.string.myGroupsModuleLabel)); map.put(IMAGE, getResources().getDrawable(R.drawable.my_groups)); mUsersData.add(map); //Generate QR code map = new HashMap<String, Object>(); map.put(NAME, getString(R.string.generateQRModuleLabel)); map.put(IMAGE, getResources().getDrawable(R.drawable.qr)); mUsersData.add(map); //Messages category //Notifications map = new HashMap<String, Object>(); map.put(NAME, getString(R.string.notificationsModuleLabel)); map.put(IMAGE, getResources().getDrawable(R.drawable.notif)); mMessagesData.add(map); //Messages map = new HashMap<String, Object>(); map.put(NAME, getString(R.string.messagesModuleLabel)); map.put(IMAGE, getResources().getDrawable(R.drawable.msg_write)); mMessagesData.add(map); mExpandableListAdapter = new ImageExpandableListAdapter( this, mHeaderData, R.layout.image_list_item, new String[]{NAME}, // the name of the field data new int[]{R.id.listText}, // the text field to populate with the field data mChildData, 0, null, new int[]{} ); mExpandableListView.setAdapter(mExpandableListAdapter); } }
private void createBaseMenu() { mExpandableListView.setVisibility(View.VISIBLE); if (mExpandableListView.getAdapter() == null || currentRole == -1) { //the menu base is equal to students menu. currentRole = Constants.STUDENT_TYPE_CODE; //Order: // 1- Course // 2- Evaluation // 3- Messages // 4- Enrollment // 5- Users final HashMap<String, Object> courses = new HashMap<String, Object>(); courses.put(NAME, getString(R.string.course)); courses.put(IMAGE, getResources().getDrawable(R.drawable.crs)); mHeaderData.add(courses); final HashMap<String, Object> evaluation = new HashMap<String, Object>(); evaluation.put(NAME, getString(R.string.evaluation)); evaluation.put(IMAGE, getResources().getDrawable(R.drawable.grades)); mHeaderData.add(evaluation); final HashMap<String, Object> users = new HashMap<String, Object>(); users.put(NAME, getString(R.string.users)); users.put(IMAGE, getResources().getDrawable(R.drawable.users)); mHeaderData.add(users); final HashMap<String, Object> messages = new HashMap<String, Object>(); messages.put(NAME, getString(R.string.messages)); messages.put(IMAGE, getResources().getDrawable(R.drawable.msg)); mHeaderData.add(messages); final ArrayList<HashMap<String, Object>> courseData = new ArrayList<HashMap<String, Object>>(); mChildData.add(courseData); final ArrayList<HashMap<String, Object>> evaluationData = new ArrayList<HashMap<String, Object>>(); mChildData.add(evaluationData); mChildData.add(mUsersData); mChildData.add(mMessagesData); HashMap<String, Object> map; //Course category //Introduction map = new HashMap<String, Object>(); map.put(NAME, getString(R.string.introductionModuleLabel)); map.put(IMAGE, getResources().getDrawable(R.drawable.info)); courseData.add(map); //Teaching Guide map = new HashMap<String, Object>(); map.put(NAME, getString(R.string.teachingguideModuleLabel)); map.put(IMAGE, getResources().getDrawable(R.drawable.file)); courseData.add(map); //Syllabus (lectures) map = new HashMap<String, Object>(); map.put(NAME, getString(R.string.syllabusLecturesModuleLabel)); map.put(IMAGE, getResources().getDrawable(R.drawable.syllabus)); courseData.add(map); //Syllabus (practicals) map = new HashMap<String, Object>(); map.put(NAME, getString(R.string.syllabusPracticalsModuleLabel)); map.put(IMAGE, getResources().getDrawable(R.drawable.lab)); courseData.add(map); //Documents map = new HashMap<String, Object>(); map.put(NAME, getString(R.string.documentsDownloadModuleLabel)); map.put(IMAGE, getResources().getDrawable(R.drawable.folder)); courseData.add(map); //Shared area map = new HashMap<String, Object>(); map.put(NAME, getString(R.string.sharedsDownloadModuleLabel)); map.put(IMAGE, getResources().getDrawable(R.drawable.folder_users)); courseData.add(map); //Bibliography map = new HashMap<String, Object>(); map.put(NAME, getString(R.string.bibliographyModuleLabel)); map.put(IMAGE, getResources().getDrawable(R.drawable.book)); courseData.add(map); //FAQs map = new HashMap<String, Object>(); map.put(NAME, getString(R.string.faqsModuleLabel)); map.put(IMAGE, getResources().getDrawable(R.drawable.faq)); courseData.add(map); //Links map = new HashMap<String, Object>(); map.put(NAME, getString(R.string.linksModuleLabel)); map.put(IMAGE, getResources().getDrawable(R.drawable.link)); courseData.add(map); //Evaluation category //Assessment system map = new HashMap<String, Object>(); map.put(NAME, getString(R.string.assessmentModuleLabel)); map.put(IMAGE, getResources().getDrawable(R.drawable.info)); evaluationData.add(map); //Test map = new HashMap<String, Object>(); map.put(NAME, getString(R.string.testsModuleLabel)); map.put(IMAGE, getResources().getDrawable(R.drawable.test)); evaluationData.add(map); //Users category //Groups map = new HashMap<String, Object>(); map.put(NAME, getString(R.string.myGroupsModuleLabel)); map.put(IMAGE, getResources().getDrawable(R.drawable.my_groups)); mUsersData.add(map); //Generate QR code map = new HashMap<String, Object>(); map.put(NAME, getString(R.string.generateQRModuleLabel)); map.put(IMAGE, getResources().getDrawable(R.drawable.qr)); mUsersData.add(map); //Messages category //Notifications map = new HashMap<String, Object>(); map.put(NAME, getString(R.string.notificationsModuleLabel)); map.put(IMAGE, getResources().getDrawable(R.drawable.notif)); mMessagesData.add(map); //Messages map = new HashMap<String, Object>(); map.put(NAME, getString(R.string.messagesModuleLabel)); map.put(IMAGE, getResources().getDrawable(R.drawable.msg_write)); mMessagesData.add(map); mExpandableListAdapter = new ImageExpandableListAdapter( this, mHeaderData, R.layout.image_list_item, new String[]{NAME}, // the name of the field data new int[]{R.id.listText}, // the text field to populate with the field data mChildData, 0, null, new int[]{} ); mExpandableListView.setAdapter(mExpandableListAdapter); } }
diff --git a/com/ngc0202/warningplugin/WarningPlugin.java b/com/ngc0202/warningplugin/WarningPlugin.java index c44eff8..c615709 100644 --- a/com/ngc0202/warningplugin/WarningPlugin.java +++ b/com/ngc0202/warningplugin/WarningPlugin.java @@ -1,138 +1,167 @@ package com.ngc0202.warningplugin; import java.io.File; import java.util.Map; import org.bukkit.ChatColor; import org.bukkit.OfflinePlayer; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; /** * * @author ngc0202 */ public class WarningPlugin extends JavaPlugin { final WarningPlugin plugin = this; PropertiesFile warns; PropertiesFile bans; @Override public void onEnable() { getDataFolder().mkdirs(); File warnFile = new File(getDataFolder(), "warns.properties"); File banFile = new File(getDataFolder(), "bans.properties"); warns = new PropertiesFile(warnFile.getAbsolutePath()); warns.load(); bans = new PropertiesFile(banFile.getAbsolutePath()); bans.load(); this.getServer().getScheduler().scheduleSyncRepeatingTask(this, new Runnable() { public void run() { plugin.banCheckAll(); } }, 1L, 6000L); System.out.println(getDescription().getFullName() + " von ngc0202 ist aktiviert."); } @Override public void onDisable() { System.out.println(getDescription().getName() + " ist deaktiviert."); warns.save(); } @Override public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { warns.load(); if (commandLabel.equalsIgnoreCase("warnen")) { if (args.length == 0) { return false; } + if (sender.hasPermission("WarningPlugin.warnen")) { + sender.sendMessage(ChatColor.RED + this.getCommand("warnungen").getPermissionMessage()); + return true; + } Player ply; if (args[0].equalsIgnoreCase("mindern")) { if (!((args.length == 2) || (args.length == 3))) { return false; } ply = sender.getServer().getPlayer(args[1]); if (ply == null) { sender.sendMessage(ChatColor.RED + "Konnte nicht finden " + args[1] + "."); return false; } - int remCnt = Integer.parseInt(args[2]); + int remCnt; + if (args.length == 2) { + remCnt = 1; + } else { + remCnt = Integer.parseInt(args[2]); + } + if (remCnt < 1) { + sender.sendMessage(ChatColor.RED + "Ungültig Zahl."); + return true; + } if (!warns.keyExists(ply.getName())) { sender.sendMessage(ChatColor.BLUE + ply.getName() + " hat schon keine Warnungen."); return true; } int newCnt = warns.getInt(ply.getName()) - remCnt; if (newCnt < 0) { newCnt = 0; } warns.setInt(ply.getName(), newCnt); warns.save(); sender.sendMessage(ChatColor.BLUE + ply.getName() + " hat jetzt " + newCnt + " Warnungen."); return true; } else { if (args.length == 0) { return false; } ply = sender.getServer().getPlayer(args[0]); if (ply == null) { sender.sendMessage(ChatColor.RED + "Konnte nicht finden " + args[0] + "."); return false; } if (args.length == 1) { sender.sendMessage(ChatColor.RED + "Bitte gib einen Grund an."); return false; } int newCnt = warns.getInt(ply.getName()) + 1; warns.setInt(ply.getName(), newCnt); warns.save(); String reason = this.buildReason(args); ply.sendMessage(ChatColor.RED + "Sie wurden verwarnt, für: \"" + reason + "\""); if (newCnt == 4) { bans.setLong(ply.getName(), System.currentTimeMillis() + 3600000L); ply.setBanned(true); ply.kickPlayer("Verbannte für zu viel Warnungen. (1 Stunden)"); } else if (newCnt >= 10) { bans.removeKey(ply.getName()); ply.setBanned(true); ply.kickPlayer("Verbannte für zu viel Warnungen."); } return true; } + } else if (commandLabel.equalsIgnoreCase("warnungen")) { + if (args.length == 0) { + int warnings = warns.getInt(sender.getName()); + sender.sendMessage(ChatColor.BLUE + "Du hast jetzt " + warnings + " Warnungen."); + return true; + } else if (args.length == 1) { + if (!sender.hasPermission("WarningPlugin.warnungen")) { + sender.sendMessage(ChatColor.RED + "Sie haben nicht die Erlaubnis, das zu tun."); + return true; + } + Player ply = getServer().getPlayer(args[0]); + int warnings = warns.getInt(ply.getName()); + sender.sendMessage(ChatColor.BLUE + ply.getName() + " hat jetzt " + warnings + " Warnungen."); + } else { + return false; + } } return false; } private void banCheckAll() { try { bans.load(); Map<String, String> map = bans.returnMap(); for (Map.Entry<String, String> entry : map.entrySet()) { String key = entry.getKey(); String val = entry.getValue(); if (Long.parseLong(val) <= System.currentTimeMillis()) { OfflinePlayer ply = getServer().getOfflinePlayer(key); ply.setBanned(false); bans.removeKey(key); } } } catch (Exception ex) { System.out.println(ChatColor.RED + "Unfähig, die WarningPlugin-Bannliste zu laden."); } } private String buildReason(String[] args) { String reason = ""; int len = args.length; for (int i = 1; i < len; i++) { reason += args[i]; if (i < (len - 1)) { reason += " "; } } return reason; } }
false
true
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { warns.load(); if (commandLabel.equalsIgnoreCase("warnen")) { if (args.length == 0) { return false; } Player ply; if (args[0].equalsIgnoreCase("mindern")) { if (!((args.length == 2) || (args.length == 3))) { return false; } ply = sender.getServer().getPlayer(args[1]); if (ply == null) { sender.sendMessage(ChatColor.RED + "Konnte nicht finden " + args[1] + "."); return false; } int remCnt = Integer.parseInt(args[2]); if (!warns.keyExists(ply.getName())) { sender.sendMessage(ChatColor.BLUE + ply.getName() + " hat schon keine Warnungen."); return true; } int newCnt = warns.getInt(ply.getName()) - remCnt; if (newCnt < 0) { newCnt = 0; } warns.setInt(ply.getName(), newCnt); warns.save(); sender.sendMessage(ChatColor.BLUE + ply.getName() + " hat jetzt " + newCnt + " Warnungen."); return true; } else { if (args.length == 0) { return false; } ply = sender.getServer().getPlayer(args[0]); if (ply == null) { sender.sendMessage(ChatColor.RED + "Konnte nicht finden " + args[0] + "."); return false; } if (args.length == 1) { sender.sendMessage(ChatColor.RED + "Bitte gib einen Grund an."); return false; } int newCnt = warns.getInt(ply.getName()) + 1; warns.setInt(ply.getName(), newCnt); warns.save(); String reason = this.buildReason(args); ply.sendMessage(ChatColor.RED + "Sie wurden verwarnt, für: \"" + reason + "\""); if (newCnt == 4) { bans.setLong(ply.getName(), System.currentTimeMillis() + 3600000L); ply.setBanned(true); ply.kickPlayer("Verbannte für zu viel Warnungen. (1 Stunden)"); } else if (newCnt >= 10) { bans.removeKey(ply.getName()); ply.setBanned(true); ply.kickPlayer("Verbannte für zu viel Warnungen."); } return true; } } return false; }
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { warns.load(); if (commandLabel.equalsIgnoreCase("warnen")) { if (args.length == 0) { return false; } if (sender.hasPermission("WarningPlugin.warnen")) { sender.sendMessage(ChatColor.RED + this.getCommand("warnungen").getPermissionMessage()); return true; } Player ply; if (args[0].equalsIgnoreCase("mindern")) { if (!((args.length == 2) || (args.length == 3))) { return false; } ply = sender.getServer().getPlayer(args[1]); if (ply == null) { sender.sendMessage(ChatColor.RED + "Konnte nicht finden " + args[1] + "."); return false; } int remCnt; if (args.length == 2) { remCnt = 1; } else { remCnt = Integer.parseInt(args[2]); } if (remCnt < 1) { sender.sendMessage(ChatColor.RED + "Ungültig Zahl."); return true; } if (!warns.keyExists(ply.getName())) { sender.sendMessage(ChatColor.BLUE + ply.getName() + " hat schon keine Warnungen."); return true; } int newCnt = warns.getInt(ply.getName()) - remCnt; if (newCnt < 0) { newCnt = 0; } warns.setInt(ply.getName(), newCnt); warns.save(); sender.sendMessage(ChatColor.BLUE + ply.getName() + " hat jetzt " + newCnt + " Warnungen."); return true; } else { if (args.length == 0) { return false; } ply = sender.getServer().getPlayer(args[0]); if (ply == null) { sender.sendMessage(ChatColor.RED + "Konnte nicht finden " + args[0] + "."); return false; } if (args.length == 1) { sender.sendMessage(ChatColor.RED + "Bitte gib einen Grund an."); return false; } int newCnt = warns.getInt(ply.getName()) + 1; warns.setInt(ply.getName(), newCnt); warns.save(); String reason = this.buildReason(args); ply.sendMessage(ChatColor.RED + "Sie wurden verwarnt, für: \"" + reason + "\""); if (newCnt == 4) { bans.setLong(ply.getName(), System.currentTimeMillis() + 3600000L); ply.setBanned(true); ply.kickPlayer("Verbannte für zu viel Warnungen. (1 Stunden)"); } else if (newCnt >= 10) { bans.removeKey(ply.getName()); ply.setBanned(true); ply.kickPlayer("Verbannte für zu viel Warnungen."); } return true; } } else if (commandLabel.equalsIgnoreCase("warnungen")) { if (args.length == 0) { int warnings = warns.getInt(sender.getName()); sender.sendMessage(ChatColor.BLUE + "Du hast jetzt " + warnings + " Warnungen."); return true; } else if (args.length == 1) { if (!sender.hasPermission("WarningPlugin.warnungen")) { sender.sendMessage(ChatColor.RED + "Sie haben nicht die Erlaubnis, das zu tun."); return true; } Player ply = getServer().getPlayer(args[0]); int warnings = warns.getInt(ply.getName()); sender.sendMessage(ChatColor.BLUE + ply.getName() + " hat jetzt " + warnings + " Warnungen."); } else { return false; } } return false; }
diff --git a/liquibase-core/src/main/java/liquibase/sqlgenerator/core/CreateIndexGenerator.java b/liquibase-core/src/main/java/liquibase/sqlgenerator/core/CreateIndexGenerator.java index ae4f0f5f..9a60ced2 100644 --- a/liquibase-core/src/main/java/liquibase/sqlgenerator/core/CreateIndexGenerator.java +++ b/liquibase-core/src/main/java/liquibase/sqlgenerator/core/CreateIndexGenerator.java @@ -1,68 +1,71 @@ package liquibase.sqlgenerator.core; import liquibase.database.Database; import liquibase.database.core.DB2Database; import liquibase.database.core.InformixDatabase; import liquibase.database.core.MSSQLDatabase; import liquibase.database.core.SybaseASADatabase; import liquibase.exception.ValidationErrors; import liquibase.sql.Sql; import liquibase.sql.UnparsedSql; import liquibase.sqlgenerator.SqlGenerator; import liquibase.sqlgenerator.SqlGeneratorChain; import liquibase.statement.core.CreateIndexStatement; import liquibase.util.StringUtils; import java.util.Arrays; import java.util.Iterator; public class CreateIndexGenerator implements SqlGenerator<CreateIndexStatement> { public int getPriority() { return PRIORITY_DEFAULT; } public boolean supports(CreateIndexStatement statement, Database database) { return true; } public ValidationErrors validate(CreateIndexStatement createIndexStatement, Database database, SqlGeneratorChain sqlGeneratorChain) { ValidationErrors validationErrors = new ValidationErrors(); validationErrors.checkRequiredField("tableName", createIndexStatement.getTableName()); validationErrors.checkRequiredField("columns", createIndexStatement.getColumns()); return validationErrors; } public Sql[] generateSql(CreateIndexStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer buffer = new StringBuffer(); buffer.append("CREATE "); if (statement.isUnique() != null && statement.isUnique()) { buffer.append("UNIQUE "); } buffer.append("INDEX "); - buffer.append(statement.getIndexName()).append(" ON "); + if (statement.getIndexName() != null) { + buffer.append(statement.getIndexName()).append(" "); + } + buffer.append("ON "); buffer.append(database.escapeTableName(statement.getTableSchemaName(), statement.getTableName())).append("("); Iterator<String> iterator = Arrays.asList(statement.getColumns()).iterator(); while (iterator.hasNext()) { String column = iterator.next(); buffer.append(database.escapeColumnName(statement.getTableSchemaName(), statement.getTableName(), column)); if (iterator.hasNext()) { buffer.append(", "); } } buffer.append(")"); if (StringUtils.trimToNull(statement.getTablespace()) != null && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) { buffer.append(" ON ").append(statement.getTablespace()); } else if (database instanceof DB2Database || database instanceof InformixDatabase) { buffer.append(" IN ").append(statement.getTablespace()); } else { buffer.append(" TABLESPACE ").append(statement.getTablespace()); } } return new Sql[]{new UnparsedSql(buffer.toString())}; } }
true
true
public Sql[] generateSql(CreateIndexStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer buffer = new StringBuffer(); buffer.append("CREATE "); if (statement.isUnique() != null && statement.isUnique()) { buffer.append("UNIQUE "); } buffer.append("INDEX "); buffer.append(statement.getIndexName()).append(" ON "); buffer.append(database.escapeTableName(statement.getTableSchemaName(), statement.getTableName())).append("("); Iterator<String> iterator = Arrays.asList(statement.getColumns()).iterator(); while (iterator.hasNext()) { String column = iterator.next(); buffer.append(database.escapeColumnName(statement.getTableSchemaName(), statement.getTableName(), column)); if (iterator.hasNext()) { buffer.append(", "); } } buffer.append(")"); if (StringUtils.trimToNull(statement.getTablespace()) != null && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) { buffer.append(" ON ").append(statement.getTablespace()); } else if (database instanceof DB2Database || database instanceof InformixDatabase) { buffer.append(" IN ").append(statement.getTablespace()); } else { buffer.append(" TABLESPACE ").append(statement.getTablespace()); } } return new Sql[]{new UnparsedSql(buffer.toString())}; }
public Sql[] generateSql(CreateIndexStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer buffer = new StringBuffer(); buffer.append("CREATE "); if (statement.isUnique() != null && statement.isUnique()) { buffer.append("UNIQUE "); } buffer.append("INDEX "); if (statement.getIndexName() != null) { buffer.append(statement.getIndexName()).append(" "); } buffer.append("ON "); buffer.append(database.escapeTableName(statement.getTableSchemaName(), statement.getTableName())).append("("); Iterator<String> iterator = Arrays.asList(statement.getColumns()).iterator(); while (iterator.hasNext()) { String column = iterator.next(); buffer.append(database.escapeColumnName(statement.getTableSchemaName(), statement.getTableName(), column)); if (iterator.hasNext()) { buffer.append(", "); } } buffer.append(")"); if (StringUtils.trimToNull(statement.getTablespace()) != null && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) { buffer.append(" ON ").append(statement.getTablespace()); } else if (database instanceof DB2Database || database instanceof InformixDatabase) { buffer.append(" IN ").append(statement.getTablespace()); } else { buffer.append(" TABLESPACE ").append(statement.getTablespace()); } } return new Sql[]{new UnparsedSql(buffer.toString())}; }
diff --git a/deegree-services/src/main/java/org/deegree/services/wfs/GetFeatureHandler.java b/deegree-services/src/main/java/org/deegree/services/wfs/GetFeatureHandler.java index 21c591dcba..47a7388e0c 100644 --- a/deegree-services/src/main/java/org/deegree/services/wfs/GetFeatureHandler.java +++ b/deegree-services/src/main/java/org/deegree/services/wfs/GetFeatureHandler.java @@ -1,715 +1,716 @@ //$HeadURL: svn+ssh://[email protected]/deegree/base/trunk/resources/eclipse/files_template.xml $ /*---------------------------------------------------------------------------- This file is part of deegree, http://deegree.org/ Copyright (C) 2001-2009 by: Department of Geography, University of Bonn and lat/lon GmbH This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact information: lat/lon GmbH Aennchenstr. 19, 53177 Bonn Germany http://lat-lon.de/ Department of Geography, University of Bonn Prof. Dr. Klaus Greve Postfach 1147, 53001 Bonn Germany http://www.geographie.uni-bonn.de/deegree/ e-mail: [email protected] ----------------------------------------------------------------------------*/ package org.deegree.services.wfs; import static org.deegree.commons.xml.CommonNamespaces.GML3_2_NS; import static org.deegree.commons.xml.CommonNamespaces.GMLNS; import static org.deegree.commons.xml.CommonNamespaces.XLNNS; import static org.deegree.gml.GMLVersion.GML_2; import static org.deegree.gml.GMLVersion.GML_31; import static org.deegree.gml.GMLVersion.GML_32; import static org.deegree.protocol.wfs.WFSConstants.VERSION_100; import static org.deegree.protocol.wfs.WFSConstants.VERSION_110; import static org.deegree.protocol.wfs.WFSConstants.VERSION_200; import static org.deegree.protocol.wfs.WFSConstants.WFS_200_NS; import static org.deegree.protocol.wfs.WFSConstants.WFS_NS; import static org.deegree.protocol.wfs.WFSConstants.WFS_PREFIX; import static org.deegree.protocol.wfs.getfeature.ResultType.RESULTS; import static org.deegree.services.controller.exception.ControllerException.NO_APPLICABLE_CODE; import java.io.IOException; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.servlet.http.HttpServletResponse; import javax.xml.namespace.QName; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import org.deegree.commons.tom.ows.Version; import org.deegree.commons.utils.kvp.InvalidParameterValueException; import org.deegree.commons.utils.time.DateUtils; import org.deegree.cs.exceptions.TransformationException; import org.deegree.cs.exceptions.UnknownCRSException; import org.deegree.feature.Feature; import org.deegree.feature.FeatureCollection; import org.deegree.feature.GenericFeatureCollection; import org.deegree.feature.persistence.FeatureStore; import org.deegree.feature.persistence.FeatureStoreException; import org.deegree.feature.persistence.lock.Lock; import org.deegree.feature.persistence.lock.LockManager; import org.deegree.feature.persistence.query.FeatureResultSet; import org.deegree.feature.persistence.query.Query; import org.deegree.feature.types.FeatureType; import org.deegree.filter.FilterEvaluationException; import org.deegree.geometry.Envelope; import org.deegree.geometry.io.DoubleCoordinateFormatter; import org.deegree.gml.GMLOutputFactory; import org.deegree.gml.GMLStreamWriter; import org.deegree.gml.GMLVersion; import org.deegree.protocol.wfs.getfeature.BBoxQuery; import org.deegree.protocol.wfs.getfeature.FeatureIdQuery; import org.deegree.protocol.wfs.getfeature.FilterQuery; import org.deegree.protocol.wfs.getfeature.GetFeature; import org.deegree.protocol.wfs.getfeature.ResultType; import org.deegree.protocol.wfs.getfeaturewithlock.GetFeatureWithLock; import org.deegree.protocol.wfs.lockfeature.BBoxLock; import org.deegree.protocol.wfs.lockfeature.FeatureIdLock; import org.deegree.protocol.wfs.lockfeature.FilterLock; import org.deegree.protocol.wfs.lockfeature.LockOperation; import org.deegree.services.controller.ows.OWSException; import org.deegree.services.controller.utils.HttpResponseBuffer; import org.deegree.services.i18n.Messages; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Handles {@link GetFeature} requests for the {@link WFSController}. * * @see WFSController * * @author <a href="mailto:[email protected]">Markus Schneider</a> * @author last edited by: $Author: schneider $ * * @version $Revision: $, $Date: $ */ class GetFeatureHandler { private static final Logger LOG = LoggerFactory.getLogger( GetFeatureHandler.class ); private final boolean streamMode; private final WFSController master; protected final WFService service; private final int featureLimit; private final boolean checkAreaOfUse; /** * Creates a new {@link GetFeatureHandler} instance that uses the given service to lookup requested * {@link FeatureType}s. * * @param master * corresponding WFS controller * @param service * WFS instance used to lookup the feature types * @param streamMode * if <code>true</code>, features are streamed (implies that the FeatureCollection's boundedBy-element * cannot be populated and that the numberOfFeatures attribute cannot be written) * @param featureLimit * hard limit for returned features (-1 means no limit) * @param checkAreaOfUse * true, if geometries in query constraints should be checked agains validity domain of the SRS (needed * for CITE 1.1.0 compliance) */ GetFeatureHandler( WFSController master, WFService service, boolean streamMode, int featureLimit, boolean checkAreaOfUse ) { this.master = master; this.service = service; this.streamMode = streamMode; this.featureLimit = featureLimit; this.checkAreaOfUse = checkAreaOfUse; } /** * Performs the given {@link GetFeature} request. * * @param request * request to be handled * @param response * response that is used to write the result * @throws Exception */ void doGetFeature( GetFeature request, HttpResponseBuffer response ) throws Exception { ResultType type = request.getResultType(); if ( type == RESULTS || type == null ) { doResults( request, response ); } else { doHits( request, response ); } } private void doResults( GetFeature request, HttpResponseBuffer response ) throws Exception { LOG.debug( "Performing GetFeature (results) request." ); GMLVersion outputFormat = determineOutputFormat( request ); GetFeatureAnalyzer analyzer = new GetFeatureAnalyzer( request, service, outputFormat, checkAreaOfUse ); String lockId = acquireLock( request, analyzer ); String schemaLocation = getSchemaLocation( request.getVersion(), outputFormat, analyzer.getFeatureTypes() ); int traverseXLinkDepth = 0; int traverseXLinkExpiry = -1; String xLinkTemplate = master.getObjectXlinkTemplate( request.getVersion(), outputFormat ); if ( VERSION_110.equals( request.getVersion() ) || VERSION_200.equals( request.getVersion() ) ) { if ( request.getTraverseXlinkDepth() != null ) { if ( "*".equals( request.getTraverseXlinkDepth() ) ) { traverseXLinkDepth = -1; } else { try { traverseXLinkDepth = Integer.parseInt( request.getTraverseXlinkDepth() ); } catch ( NumberFormatException e ) { String msg = Messages.get( "WFS_TRAVERSEXLINKDEPTH_INVALID", request.getTraverseXlinkDepth() ); throw new OWSException( new InvalidParameterValueException( msg ) ); } } } if ( request.getTraverseXlinkExpiry() != null ) { traverseXLinkExpiry = request.getTraverseXlinkExpiry(); // needed for CITE 1.1.0 compliance (wfs:GetFeature-traverseXlinkExpiry) if ( traverseXLinkExpiry <= 0 ) { String msg = Messages.get( "WFS_TRAVERSEXLINKEXPIRY_ZERO", request.getTraverseXlinkDepth() ); throw new OWSException( new InvalidParameterValueException( msg ) ); } } } XMLStreamWriter xmlStream = WFSController.getXMLResponseWriter( response, schemaLocation ); setContentType( outputFormat, response ); // open "wfs:FeatureCollection" element if ( request.getVersion().equals( VERSION_100 ) ) { xmlStream.writeStartElement( "wfs", "FeatureCollection", WFS_NS ); if ( lockId != null ) { xmlStream.writeAttribute( "lockId", lockId ); } } else if ( request.getVersion().equals( VERSION_110 ) ) { xmlStream.writeStartElement( "wfs", "FeatureCollection", WFS_NS ); if ( lockId != null ) { xmlStream.writeAttribute( "lockId", lockId ); } xmlStream.writeAttribute( "timeStamp", DateUtils.formatISO8601Date( new Date() ) ); } else if ( request.getVersion().equals( VERSION_200 ) ) { xmlStream.writeStartElement( "wfs", "FeatureCollection", WFS_200_NS ); xmlStream.writeAttribute( "timeStamp", DateUtils.formatISO8601Date( new Date() ) ); } if ( GML_32 == outputFormat ) { xmlStream.writeAttribute( "gml", GML3_2_NS, "id", "GML_32_FEATURECOLLECTION" ); } int maxFeatures = featureLimit; if ( request.getMaxFeatures() != null && request.getMaxFeatures() < maxFeatures ) { maxFeatures = request.getMaxFeatures(); } if ( streamMode ) { writeFeatureMembersStream( request.getVersion(), xmlStream, analyzer, outputFormat, xLinkTemplate, traverseXLinkDepth, traverseXLinkExpiry, maxFeatures ); } else { writeFeatureMembersCached( request.getVersion(), xmlStream, analyzer, outputFormat, xLinkTemplate, traverseXLinkDepth, traverseXLinkExpiry, maxFeatures ); } // close "wfs:FeatureCollection" xmlStream.writeEndElement(); xmlStream.flush(); } private void writeFeatureMembersStream( Version wfsVersion, XMLStreamWriter xmlStream, GetFeatureAnalyzer analyzer, GMLVersion outputFormat, String xLinkTemplate, int traverseXLinkDepth, int traverseXLinkExpiry, int maxFeatures ) throws XMLStreamException, UnknownCRSException, TransformationException, FeatureStoreException, FilterEvaluationException { GMLStreamWriter gmlStream = GMLOutputFactory.createGMLStreamWriter( outputFormat, xmlStream ); gmlStream.setOutputCRS( analyzer.getRequestedCRS() ); // TODO make this configurable gmlStream.setCoordinateFormatter( new DoubleCoordinateFormatter() ); gmlStream.setFeatureProperties( analyzer.getRequestedProps() ); gmlStream.setLocalXLinkTemplate( xLinkTemplate ); gmlStream.setXLinkDepth( traverseXLinkDepth ); gmlStream.setXLinkExpiry( traverseXLinkExpiry ); gmlStream.setXLinkFeatureProperties( analyzer.getXLinkProps() ); bindFeatureTypePrefixes( xmlStream, analyzer.getFeatureTypes() ); if ( outputFormat == GML_2 ) { writeBoundedBy( gmlStream, outputFormat ); } // retrieve and write result features int featuresAdded = 0; // limit the number of features written to maxfeatures for ( Map.Entry<FeatureStore, List<Query>> fsToQueries : analyzer.getQueries().entrySet() ) { FeatureStore fs = fsToQueries.getKey(); Query[] queries = fsToQueries.getValue().toArray( new Query[fsToQueries.getValue().size()] ); FeatureResultSet rs = fs.query( queries ); try { for ( Feature feature : rs ) { if ( gmlStream.isObjectExported( feature.getId() ) ) { if ( GML_32 == outputFormat ) { if ( VERSION_200.equals( wfsVersion ) ) { xmlStream.writeEmptyElement( "wfs", "member", WFS_200_NS ); } else { xmlStream.writeEmptyElement( "wfs", "member", WFS_NS ); } } else { xmlStream.writeEmptyElement( "gml", "featureMember", GMLNS ); } xmlStream.writeAttribute( "xlink", XLNNS, "href", "#" + feature.getId() ); } else { if ( GML_32 == outputFormat ) { if ( VERSION_200.equals( wfsVersion ) ) { xmlStream.writeStartElement( "wfs", "member", WFS_200_NS ); } else { xmlStream.writeStartElement( "wfs", "member", WFS_NS ); } } else { xmlStream.writeStartElement( "gml", "featureMember", GMLNS ); } gmlStream.write( feature ); xmlStream.writeEndElement(); } featuresAdded++; if ( featuresAdded == maxFeatures ) { break; } } } finally { LOG.debug( "Closing FeatureResultSet (stream)" ); rs.close(); } } } private void writeBoundedBy( GMLStreamWriter gmlStream, GMLVersion outputFormat ) throws XMLStreamException, UnknownCRSException, TransformationException { XMLStreamWriter xmlStream = gmlStream.getXMLStream(); switch ( outputFormat ) { case GML_2: { xmlStream.writeStartElement( "gml", "boundedBy", GMLNS ); xmlStream.writeStartElement( "gml", "null", GMLNS ); xmlStream.writeCharacters( "unknown" ); xmlStream.writeEndElement(); xmlStream.writeEndElement(); break; } case GML_30: case GML_31: { xmlStream.writeStartElement( "gml", "boundedBy", GMLNS ); xmlStream.writeStartElement( "gml", "Null", GMLNS ); xmlStream.writeCharacters( "unknown" ); xmlStream.writeEndElement(); xmlStream.writeEndElement(); break; } case GML_32: { xmlStream.writeStartElement( "gml", "boundedBy", GML3_2_NS ); xmlStream.writeStartElement( "gml", "Null", GML3_2_NS ); xmlStream.writeCharacters( "unknown" ); xmlStream.writeEndElement(); xmlStream.writeEndElement(); break; } } } private void writeFeatureMembersCached( Version wfsVersion, XMLStreamWriter xmlStream, GetFeatureAnalyzer analyzer, GMLVersion outputFormat, String xLinkTemplate, int traverseXLinkDepth, int traverseXLinkExpiry, int maxFeatures ) throws XMLStreamException, UnknownCRSException, TransformationException, FeatureStoreException, FilterEvaluationException { FeatureCollection allFeatures = new GenericFeatureCollection(); Set<String> fids = new HashSet<String>(); // retrieve maxfeatures features int featuresAdded = 0; for ( Map.Entry<FeatureStore, List<Query>> fsToQueries : analyzer.getQueries().entrySet() ) { FeatureStore fs = fsToQueries.getKey(); Query[] queries = fsToQueries.getValue().toArray( new Query[fsToQueries.getValue().size()] ); FeatureResultSet rs = fs.query( queries ); try { for ( Feature feature : rs ) { if ( !fids.contains( feature.getId() ) ) { allFeatures.add( feature ); fids.add( feature.getId() ); featuresAdded++; if ( featuresAdded == maxFeatures ) { break; } } } } finally { LOG.debug( "Closing FeatureResultSet (cached)" ); rs.close(); } } if ( !wfsVersion.equals( VERSION_100 ) ) { xmlStream.writeAttribute( "numberOfFeatures", "" + allFeatures.size() ); } GMLStreamWriter gmlStream = GMLOutputFactory.createGMLStreamWriter( outputFormat, xmlStream ); gmlStream.setLocalXLinkTemplate( xLinkTemplate ); gmlStream.setXLinkDepth( traverseXLinkDepth ); gmlStream.setXLinkExpiry( traverseXLinkExpiry ); gmlStream.setXLinkFeatureProperties( analyzer.getXLinkProps() ); gmlStream.setFeatureProperties( analyzer.getRequestedProps() ); gmlStream.setOutputCRS( analyzer.getRequestedCRS() ); - // TODO make this configurable - gmlStream.setCoordinateFormatter( new DoubleCoordinateFormatter() ); + // TODO make the coordinate formatter configurable, + // but don't use DoubleCoordinateFormatter (1.2122E7 may be the result) +// gmlStream.setCoordinateFormatter( new DoubleCoordinateFormatter() ); bindFeatureTypePrefixes( xmlStream, analyzer.getFeatureTypes() ); if ( outputFormat == GML_2 || allFeatures.getEnvelope() != null ) { writeBoundedBy( gmlStream, outputFormat, allFeatures.getEnvelope() ); } // retrieve and write result features for ( Feature member : allFeatures ) { if ( gmlStream.isObjectExported( member.getId() ) ) { if ( GML_32 == outputFormat ) { if ( VERSION_200.equals( wfsVersion ) ) { xmlStream.writeEmptyElement( "wfs", "member", WFS_200_NS ); } else { xmlStream.writeEmptyElement( "wfs", "member", WFS_NS ); } } else { xmlStream.writeEmptyElement( "gml", "featureMember", GMLNS ); } xmlStream.writeAttribute( "xlink", XLNNS, "href", "#" + member.getId() ); } else { if ( GML_32 == outputFormat ) { if ( VERSION_200.equals( wfsVersion ) ) { xmlStream.writeStartElement( "wfs", "member", WFS_200_NS ); } else { xmlStream.writeStartElement( "wfs", "member", WFS_NS ); } } else { xmlStream.writeStartElement( "gml", "featureMember", GMLNS ); } gmlStream.write( member ); xmlStream.writeEndElement(); } } } private void writeBoundedBy( GMLStreamWriter gmlStream, GMLVersion outputFormat, Envelope env ) throws XMLStreamException, UnknownCRSException, TransformationException { XMLStreamWriter xmlStream = gmlStream.getXMLStream(); switch ( outputFormat ) { case GML_2: { xmlStream.writeStartElement( "gml", "boundedBy", GMLNS ); if ( env == null ) { xmlStream.writeStartElement( "gml", "null", GMLNS ); xmlStream.writeCharacters( "inapplicable" ); xmlStream.writeEndElement(); } else { gmlStream.write( env ); } xmlStream.writeEndElement(); break; } case GML_30: case GML_31: { xmlStream.writeStartElement( "gml", "boundedBy", GMLNS ); if ( env == null ) { xmlStream.writeStartElement( "gml", "Null", GMLNS ); xmlStream.writeCharacters( "inapplicable" ); xmlStream.writeEndElement(); } else { gmlStream.write( env ); } xmlStream.writeEndElement(); break; } case GML_32: { xmlStream.writeStartElement( "gml", "boundedBy", GML3_2_NS ); if ( env == null ) { xmlStream.writeStartElement( "gml", "Null", GML3_2_NS ); xmlStream.writeCharacters( "inapplicable" ); xmlStream.writeEndElement(); } else { gmlStream.write( env ); } xmlStream.writeEndElement(); break; } } } private void bindFeatureTypePrefixes( XMLStreamWriter xmlStream, Collection<FeatureType> fts ) throws XMLStreamException { if ( fts == null ) { fts = service.getFeatureTypes(); } Map<String, String> nsToPrefix = new HashMap<String, String>(); for ( FeatureType ft : fts ) { QName ftName = ft.getName(); if ( ftName.getPrefix() != null ) { nsToPrefix.put( ftName.getNamespaceURI(), ftName.getPrefix() ); } } for ( Map.Entry<String, String> nsBinding : nsToPrefix.entrySet() ) { xmlStream.setPrefix( nsBinding.getValue(), nsBinding.getKey() ); } } private void doHits( GetFeature request, HttpResponseBuffer response ) throws OWSException, XMLStreamException, IOException, FeatureStoreException, FilterEvaluationException { LOG.debug( "Performing GetFeature (hits) request." ); GMLVersion outputFormat = determineOutputFormat( request ); GetFeatureAnalyzer analyzer = new GetFeatureAnalyzer( request, service, outputFormat, checkAreaOfUse ); String lockId = acquireLock( request, analyzer ); String schemaLocation = getSchemaLocation( request.getVersion(), outputFormat, analyzer.getFeatureTypes() ); XMLStreamWriter xmlStream = WFSController.getXMLResponseWriter( response, schemaLocation ); setContentType( outputFormat, response ); // open "wfs:FeatureCollection" element if ( request.getVersion().equals( VERSION_100 ) ) { xmlStream.writeStartElement( "wfs", "FeatureCollection", WFS_NS ); if ( lockId != null ) { xmlStream.writeAttribute( "lockId", lockId ); } } else if ( request.getVersion().equals( VERSION_110 ) ) { xmlStream.writeStartElement( "wfs", "FeatureCollection", WFS_NS ); if ( lockId != null ) { xmlStream.writeAttribute( "lockId", lockId ); } xmlStream.writeAttribute( "timeStamp", DateUtils.formatISO8601Date( new Date() ) ); } else if ( request.getVersion().equals( VERSION_200 ) ) { xmlStream.writeStartElement( "wfs", "FeatureCollection", WFS_200_NS ); xmlStream.writeAttribute( "timeStamp", DateUtils.formatISO8601Date( new Date() ) ); } int numHits = 0; for ( Map.Entry<FeatureStore, List<Query>> fsToQueries : analyzer.getQueries().entrySet() ) { FeatureStore fs = fsToQueries.getKey(); Query[] queries = fsToQueries.getValue().toArray( new Query[fsToQueries.getValue().size()] ); // TODO what about features that occur multiple times as result of different queries? numHits += fs.queryHits( queries ); } xmlStream.writeAttribute( "numberOfFeatures", "" + numHits ); // "gml:boundedBy" is necessary for GML 2 // TODO strategies for including the correct value if ( outputFormat.equals( GMLVersion.GML_2 ) ) { xmlStream.writeStartElement( "gml", GMLNS, "boundedBy" ); xmlStream.writeStartElement( GMLNS, "null" ); xmlStream.writeCharacters( "not available (WFS streaming mode)" ); xmlStream.writeEndElement(); xmlStream.writeEndElement(); } // close "wfs:FeatureCollection" xmlStream.writeEndElement(); xmlStream.flush(); } /** * Returns the value for the <code>xsi:schemaLocation</code> attribute in the response document. * * @param requestVersion * requested WFS version, must not be <code>null</code> * @param requestedFts * requested feature types, can be <code>null</code> (any feature type may occur in the output) * @return value for the <code>xsi:schemaLocation</code> attribute, never <code>null</code> */ private String getSchemaLocation( Version requestVersion, GMLVersion gmlVersion, Collection<FeatureType> requestedFts ) { String schemaLocation = null; QName wfsFeatureCollection = new QName( WFS_NS, "FeatureCollection", WFS_PREFIX ); if ( VERSION_100.equals( requestVersion ) ) { if ( GML_2 == gmlVersion ) { schemaLocation = WFS_NS + " http://schemas.opengis.net/wfs/1.0.0/WFS-basic.xsd"; } else { schemaLocation = WFSController.getSchemaLocation( requestVersion, gmlVersion, wfsFeatureCollection ); } } else if ( VERSION_110.equals( requestVersion ) ) { if ( GML_31 == gmlVersion ) { schemaLocation = WFS_NS + " http://schemas.opengis.net/wfs/1.1.0/wfs.xsd"; } else { schemaLocation = WFSController.getSchemaLocation( requestVersion, gmlVersion, wfsFeatureCollection ); } } else if ( VERSION_200.equals( requestVersion ) ) { if ( GML_32 == gmlVersion ) { schemaLocation = WFS_200_NS + " http://schemas.opengis.net/wfs/2.0.0/wfs.xsd"; } else { schemaLocation = WFSController.getSchemaLocation( requestVersion, gmlVersion, wfsFeatureCollection ); } } else { throw new RuntimeException( "Internal error: Unhandled WFS version: " + requestVersion ); } if ( requestedFts == null ) { requestedFts = service.getFeatureTypes(); } QName[] requestedFtNames = new QName[requestedFts.size()]; int i = 0; for ( FeatureType requestedFt : requestedFts ) { requestedFtNames[i++] = requestedFt.getName(); } return schemaLocation + " " + WFSController.getSchemaLocation( requestVersion, gmlVersion, requestedFtNames ); } /** * Sets the content type header for the HTTP response. * * TODO integrate handling for custom formats * * @param outputFormat * output format to be used, must not be <code>null</code> * @param response * http response, must not be <code>null</code> */ private void setContentType( GMLVersion outputFormat, HttpServletResponse response ) { switch ( outputFormat ) { case GML_2: response.setContentType( "text/xml; subtype=gml/2.1.2" ); break; case GML_30: response.setContentType( "text/xml; subtype=gml/3.0.1" ); break; case GML_31: response.setContentType( "text/xml; subtype=gml/3.1.1" ); break; case GML_32: response.setContentType( "text/xml; subtype=gml/3.2.1" ); break; } } /** * Determines the requested (GML) output format. * * TODO integrate handling for custom formats * * @param request * request to be analyzed, must not be <code>null</code> * @return version to use for the written GML, never <code>null</code> * @throws OWSException * if the requested format is not supported */ private GMLVersion determineOutputFormat( GetFeature request ) throws OWSException { GMLVersion gmlVersion = master.determineFormat( request.getVersion(), request.getOutputFormat() ); if ( gmlVersion == null ) { String msg = "Unsupported output format '" + request.getOutputFormat() + "'"; throw new OWSException( msg, OWSException.INVALID_PARAMETER_VALUE, "outputFormat" ); } return gmlVersion; } private String acquireLock( GetFeature request, GetFeatureAnalyzer analyzer ) throws OWSException { String lockId = null; if ( request instanceof GetFeatureWithLock ) { GetFeatureWithLock gfLock = (GetFeatureWithLock) request; // CITE 1.1.0 compliance (wfs:GetFeatureWithLock-Xlink) if ( analyzer.getXLinkProps() != null ) { throw new OWSException( "GetFeatureWithLock does not support XlinkPropertyName", OWSException.OPTION_NOT_SUPPORTED ); } boolean mustLockAll = true; // default: 5 minutes int expiry = 5 * 60 * 1000; if ( gfLock.getExpiry() != null ) { expiry = gfLock.getExpiry() * 60 * 1000; } LockManager manager = null; try { // TODO strategy for multiple LockManagers / feature stores manager = service.getStores()[0].getLockManager(); LockOperation[] lockOperations = new LockOperation[request.getQueries().length]; int i = 0; for ( org.deegree.protocol.wfs.getfeature.Query wfsQuery : request.getQueries() ) { lockOperations[i++] = buildLockOperation( wfsQuery ); } Lock lock = manager.acquireLock( lockOperations, mustLockAll, expiry ); lockId = lock.getId(); } catch ( FeatureStoreException e ) { throw new OWSException( "Cannot acquire lock: " + e.getMessage(), NO_APPLICABLE_CODE ); } } return lockId; } private LockOperation buildLockOperation( org.deegree.protocol.wfs.getfeature.Query wfsQuery ) { LockOperation lockOperation = null; if ( wfsQuery instanceof BBoxQuery ) { BBoxQuery bboxQuery = (BBoxQuery) wfsQuery; lockOperation = new BBoxLock( bboxQuery.getBBox(), bboxQuery.getTypeNames() ); } else if ( wfsQuery instanceof FeatureIdQuery ) { FeatureIdQuery fidQuery = (FeatureIdQuery) wfsQuery; lockOperation = new FeatureIdLock( fidQuery.getFeatureIds(), fidQuery.getTypeNames() ); } else if ( wfsQuery instanceof FilterQuery ) { FilterQuery filterQuery = (FilterQuery) wfsQuery; // TODO multiple type names lockOperation = new FilterLock( null, filterQuery.getTypeNames()[0], filterQuery.getFilter() ); } else { throw new RuntimeException(); } return lockOperation; } }
true
true
private void writeFeatureMembersCached( Version wfsVersion, XMLStreamWriter xmlStream, GetFeatureAnalyzer analyzer, GMLVersion outputFormat, String xLinkTemplate, int traverseXLinkDepth, int traverseXLinkExpiry, int maxFeatures ) throws XMLStreamException, UnknownCRSException, TransformationException, FeatureStoreException, FilterEvaluationException { FeatureCollection allFeatures = new GenericFeatureCollection(); Set<String> fids = new HashSet<String>(); // retrieve maxfeatures features int featuresAdded = 0; for ( Map.Entry<FeatureStore, List<Query>> fsToQueries : analyzer.getQueries().entrySet() ) { FeatureStore fs = fsToQueries.getKey(); Query[] queries = fsToQueries.getValue().toArray( new Query[fsToQueries.getValue().size()] ); FeatureResultSet rs = fs.query( queries ); try { for ( Feature feature : rs ) { if ( !fids.contains( feature.getId() ) ) { allFeatures.add( feature ); fids.add( feature.getId() ); featuresAdded++; if ( featuresAdded == maxFeatures ) { break; } } } } finally { LOG.debug( "Closing FeatureResultSet (cached)" ); rs.close(); } } if ( !wfsVersion.equals( VERSION_100 ) ) { xmlStream.writeAttribute( "numberOfFeatures", "" + allFeatures.size() ); } GMLStreamWriter gmlStream = GMLOutputFactory.createGMLStreamWriter( outputFormat, xmlStream ); gmlStream.setLocalXLinkTemplate( xLinkTemplate ); gmlStream.setXLinkDepth( traverseXLinkDepth ); gmlStream.setXLinkExpiry( traverseXLinkExpiry ); gmlStream.setXLinkFeatureProperties( analyzer.getXLinkProps() ); gmlStream.setFeatureProperties( analyzer.getRequestedProps() ); gmlStream.setOutputCRS( analyzer.getRequestedCRS() ); // TODO make this configurable gmlStream.setCoordinateFormatter( new DoubleCoordinateFormatter() ); bindFeatureTypePrefixes( xmlStream, analyzer.getFeatureTypes() ); if ( outputFormat == GML_2 || allFeatures.getEnvelope() != null ) { writeBoundedBy( gmlStream, outputFormat, allFeatures.getEnvelope() ); } // retrieve and write result features for ( Feature member : allFeatures ) { if ( gmlStream.isObjectExported( member.getId() ) ) { if ( GML_32 == outputFormat ) { if ( VERSION_200.equals( wfsVersion ) ) { xmlStream.writeEmptyElement( "wfs", "member", WFS_200_NS ); } else { xmlStream.writeEmptyElement( "wfs", "member", WFS_NS ); } } else { xmlStream.writeEmptyElement( "gml", "featureMember", GMLNS ); } xmlStream.writeAttribute( "xlink", XLNNS, "href", "#" + member.getId() ); } else { if ( GML_32 == outputFormat ) { if ( VERSION_200.equals( wfsVersion ) ) { xmlStream.writeStartElement( "wfs", "member", WFS_200_NS ); } else { xmlStream.writeStartElement( "wfs", "member", WFS_NS ); } } else { xmlStream.writeStartElement( "gml", "featureMember", GMLNS ); } gmlStream.write( member ); xmlStream.writeEndElement(); } } }
private void writeFeatureMembersCached( Version wfsVersion, XMLStreamWriter xmlStream, GetFeatureAnalyzer analyzer, GMLVersion outputFormat, String xLinkTemplate, int traverseXLinkDepth, int traverseXLinkExpiry, int maxFeatures ) throws XMLStreamException, UnknownCRSException, TransformationException, FeatureStoreException, FilterEvaluationException { FeatureCollection allFeatures = new GenericFeatureCollection(); Set<String> fids = new HashSet<String>(); // retrieve maxfeatures features int featuresAdded = 0; for ( Map.Entry<FeatureStore, List<Query>> fsToQueries : analyzer.getQueries().entrySet() ) { FeatureStore fs = fsToQueries.getKey(); Query[] queries = fsToQueries.getValue().toArray( new Query[fsToQueries.getValue().size()] ); FeatureResultSet rs = fs.query( queries ); try { for ( Feature feature : rs ) { if ( !fids.contains( feature.getId() ) ) { allFeatures.add( feature ); fids.add( feature.getId() ); featuresAdded++; if ( featuresAdded == maxFeatures ) { break; } } } } finally { LOG.debug( "Closing FeatureResultSet (cached)" ); rs.close(); } } if ( !wfsVersion.equals( VERSION_100 ) ) { xmlStream.writeAttribute( "numberOfFeatures", "" + allFeatures.size() ); } GMLStreamWriter gmlStream = GMLOutputFactory.createGMLStreamWriter( outputFormat, xmlStream ); gmlStream.setLocalXLinkTemplate( xLinkTemplate ); gmlStream.setXLinkDepth( traverseXLinkDepth ); gmlStream.setXLinkExpiry( traverseXLinkExpiry ); gmlStream.setXLinkFeatureProperties( analyzer.getXLinkProps() ); gmlStream.setFeatureProperties( analyzer.getRequestedProps() ); gmlStream.setOutputCRS( analyzer.getRequestedCRS() ); // TODO make the coordinate formatter configurable, // but don't use DoubleCoordinateFormatter (1.2122E7 may be the result) // gmlStream.setCoordinateFormatter( new DoubleCoordinateFormatter() ); bindFeatureTypePrefixes( xmlStream, analyzer.getFeatureTypes() ); if ( outputFormat == GML_2 || allFeatures.getEnvelope() != null ) { writeBoundedBy( gmlStream, outputFormat, allFeatures.getEnvelope() ); } // retrieve and write result features for ( Feature member : allFeatures ) { if ( gmlStream.isObjectExported( member.getId() ) ) { if ( GML_32 == outputFormat ) { if ( VERSION_200.equals( wfsVersion ) ) { xmlStream.writeEmptyElement( "wfs", "member", WFS_200_NS ); } else { xmlStream.writeEmptyElement( "wfs", "member", WFS_NS ); } } else { xmlStream.writeEmptyElement( "gml", "featureMember", GMLNS ); } xmlStream.writeAttribute( "xlink", XLNNS, "href", "#" + member.getId() ); } else { if ( GML_32 == outputFormat ) { if ( VERSION_200.equals( wfsVersion ) ) { xmlStream.writeStartElement( "wfs", "member", WFS_200_NS ); } else { xmlStream.writeStartElement( "wfs", "member", WFS_NS ); } } else { xmlStream.writeStartElement( "gml", "featureMember", GMLNS ); } gmlStream.write( member ); xmlStream.writeEndElement(); } } }
diff --git a/src/com/github/kaitoyuuki/MagicArrows/BowListener.java b/src/com/github/kaitoyuuki/MagicArrows/BowListener.java index b2730ef..1b5878a 100644 --- a/src/com/github/kaitoyuuki/MagicArrows/BowListener.java +++ b/src/com/github/kaitoyuuki/MagicArrows/BowListener.java @@ -1,377 +1,376 @@ package com.github.kaitoyuuki.MagicArrows; import java.util.ArrayList; import java.util.List; import java.util.Random; import org.bukkit.Bukkit; import org.bukkit.Effect; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.entity.Arrow; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; import org.bukkit.entity.Projectile; import org.bukkit.event.entity.EntityShootBowEvent; import org.bukkit.event.entity.ProjectileHitEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import org.bukkit.util.Vector; import org.bukkit.entity.Fireball; import com.palmergames.bukkit.towny.Towny; import com.palmergames.bukkit.towny.object.TownyPermission; import com.palmergames.bukkit.towny.object.TownyUniverse; import com.palmergames.bukkit.towny.utils.PlayerCacheUtil; import com.sk89q.worldguard.bukkit.WorldGuardPlugin; import com.sk89q.worldguard.protection.GlobalRegionManager; import com.sk89q.worldguard.protection.flags.StateFlag; @SuppressWarnings("unused") public class BowListener implements Listener { private MagicArrows plugin; private Towny towny; private WorldGuardPlugin worldguard; private TownyUniverse townyUniverse; private PlayerCacheUtil playerCacheUtil; private GlobalRegionManager grm; public BowListener(MagicArrows plugin) { this.plugin = plugin; towny = this.plugin.getTowny(); worldguard = this.plugin.getWG(); if (towny != null) { townyUniverse = towny.getTownyUniverse(); } if (worldguard != null) { grm = worldguard.getGlobalRegionManager(); } } public boolean freezeBlock(Location loc) { Block block = loc.getBlock(); if (block.getType() == Material.STATIONARY_WATER){ block.setType(Material.ICE); return true; } else if (block.getType() == Material.STATIONARY_LAVA){ block.setType(Material.OBSIDIAN); return true; } else if (block.getType() == Material.LAVA){ block.setType(Material.COBBLESTONE); return true; } else { return false; } } @EventHandler public void onArrowLaunch(EntityShootBowEvent event) { ItemStack bow = event.getBow(); Projectile projectile = (Projectile) event.getProjectile(); Player player = null; World world = projectile.getWorld(); if(bow != null && event.getEntityType() == EntityType.PLAYER){ for (Player pcheck : Bukkit.getServer().getOnlinePlayers()) { if (pcheck.getEntityId() == event.getEntity().getEntityId()) { player = pcheck; } } if (player != null) { Material modifier = Material.AIR; int id = 0; if (player.getInventory().getItemInHand().getType() == Material.BOW) { int bowslot = player.getInventory().getHeldItemSlot(); if (bowslot > 0) { try { modifier = player.getInventory().getItem(bowslot - 1).getType(); if (modifier == Material.AIR){ id = 0; } else { id = player.getInventory().getItem(bowslot - 1).getTypeId(); } if (id == 0) { return; } else if (id == 385) { if (player.hasPermission("magicarrows.fireball")) { Random generator = new Random(); int r = generator.nextInt(10); if (r < 3) { Effect effect = Effect.GHAST_SHRIEK; World pworld = player.getWorld(); Location loc = player.getLocation(); pworld.playEffect(loc, effect, 0); } ((Projectile) projectile.getWorld().spawnEntity(projectile.getLocation(), EntityType.FIREBALL)).setShooter(player); Effect effect = Effect.GHAST_SHOOT; World pworld = player.getWorld(); Location loc = player.getLocation(); pworld.playEffect(loc, effect, 0); int slot = bowslot - 1; PlayerInventory inventory = player.getInventory(); ItemStack stack = inventory.getItem(slot); int amt = stack.getAmount(); stack.setAmount(amt - 1); inventory.setItem(slot, stack); projectile.remove(); plugin.incFireBall(); } } } catch (NullPointerException e) { } } } } } } @EventHandler public void onArrowHit(ProjectileHitEvent event) { Projectile projectile = (Projectile) event.getEntity(); Location loc = projectile.getLocation(); Block block = loc.getBlock(); Entity shooter = projectile.getShooter(); Player player = null; - List<Integer> hotslots = new ArrayList<Integer>(); World world = projectile.getWorld(); - for (int i = 0; i < 8; i++) { - hotslots.add(i); - } for (Player pcheck : Bukkit.getServer().getOnlinePlayers()) { if (pcheck.getEntityId() == shooter.getEntityId()) { player = pcheck; } } - if (player != null) { + if (player == null) { + return; + } + else if (player != null) { Material modifier = Material.AIR; int id = 0; if (player.getInventory().getItemInHand().getType() == Material.BOW) { int bowslot = player.getInventory().getHeldItemSlot(); if (bowslot > 0) { try { modifier = player.getInventory().getItem(bowslot - 1).getType(); if (modifier == Material.AIR){ id = 0; } else { id = player.getInventory().getItem(bowslot - 1).getTypeId(); } if (id == 0) { return; } else if (id == 50) { //torch: place a torch where the arrow stopped if (player.hasPermission("magicarrows.torch")) { if (towny != null) { if (townyUniverse != null) { if(!PlayerCacheUtil.getCachePermission(player, loc, block.getTypeId(), TownyPermission.ActionType.BUILD)) { return; } } } else if (worldguard != null) { if (grm != null) { if (!grm.hasBypass(player, world) || !grm.canBuild(player, loc)) { return; } } } else if (block.getType() != Material.AIR) { return; } else { block.setTypeId(50); int slot = bowslot - 1; PlayerInventory inventory = player.getInventory(); ItemStack stack = inventory.getItem(slot); int amt = stack.getAmount(); stack.setAmount(amt - 1); inventory.setItem(slot, stack); projectile.remove(); plugin.incTorch(); return; } } } else if (id == 46) { //tnt: create an explosion where the arrow stops if (player.hasPermission("magicarrows.tnt")) { if (towny != null) { if (townyUniverse != null) { if(!PlayerCacheUtil.getCachePermission(player, loc, block.getTypeId(), TownyPermission.ActionType.BUILD)) { return; } } } else if (worldguard != null) { if (grm != null) { if (!grm.hasBypass(player, world) || !grm.canBuild(player, loc)) { return; } } } else { int blast = plugin.getConfig().getInt("arrows.tnt"); projectile.getWorld().createExplosion(projectile.getLocation(), blast); int slot = bowslot - 1; PlayerInventory inventory = player.getInventory(); ItemStack stack = inventory.getItem(slot); int amt = stack.getAmount(); stack.setAmount(amt - 1); inventory.setItem(slot, stack); projectile.remove(); plugin.incTNT(); return; } } } else if (id == 259) { //flint and steel: real fire arrows if (player.hasPermission("magicarrows.fire")) { if (towny != null) { if (townyUniverse != null) { if(!PlayerCacheUtil.getCachePermission(player, loc, block.getTypeId(), TownyPermission.ActionType.BUILD)) { return; } // also check if flint & steel is allowed here if(!PlayerCacheUtil.getCachePermission(player, loc, block.getTypeId(), TownyPermission.ActionType.ITEM_USE)) { // TODO figure out how to check specifically about flint and steel. return; } } } else if (worldguard != null) { if (grm != null) { if (!grm.hasBypass(player, world) || !grm.canBuild(player, loc)) { return; } // TODO also need to check if lighters are allowed here. How do I do that? } } else if (block.getType() != Material.AIR){ return; } else { block.setTypeId(51); int slot = bowslot - 1; PlayerInventory inventory = player.getInventory(); ItemStack stack = inventory.getItem(slot); short dmg = stack.getDurability(); - dmg--; + dmg++; stack.setDurability(dmg); projectile.remove(); plugin.incFire(); } } } else if (id == 262) { //arrow: double arrow? no, if I want to do something //like this, it would have to be when shooting. } else if (id == 264) { //diamond(maybe iron instead?): lightning charge if (player.hasPermission("magicarrows.smite")) { world.strikeLightning(loc); int slot = bowslot - 1; PlayerInventory inventory = player.getInventory(); ItemStack stack = inventory.getItem(slot); int amt = stack.getAmount(); stack.setAmount(amt - 1); inventory.setItem(slot, stack); projectile.remove(); plugin.incSmite(); } } else if (id == 326) { //water bucket: water balloon? } else if (id == 332) { //snowball: freezer shot //hmm. I may have to set this one up differently... //as it is now, you will have to freeze from the bottom of the lake up. // Ah, actually, I can use this part for if it hits a block or an entity. if (player.hasPermission("magicarrows.freeze")) { plugin.incIce(); int slot = bowslot - 1; PlayerInventory inventory = player.getInventory(); ItemStack stack = inventory.getItem(slot); int amt = stack.getAmount(); stack.setAmount(amt - 1); inventory.setItem(slot, stack); projectile.remove(); // Check the blocks in the appropriate radius around the arrow // If water, lava, fire, or an entity is found // freeze it. Produce smoke effect around the entity // and prevent it from moving or attacking for five seconds or so. // appropriate radius... 3 or so, I guess. // get these from config later, maybe. int radius = 3; int frzTime = 5; int diameter = 2*radius; Location check = loc; double x, y, z; for (x = loc.getX() - radius; x < loc.getX() + radius; x++) { for (y = loc.getY() - radius - 1; y < loc.getY() - 1 + radius; y++) { for (z = loc.getZ() - radius; z < loc.getZ() + radius; z++) { check = new Location(world, x, y, z); if (check.distance(loc) < radius) { freezeBlock(check); } } } } for (x = loc.getX() - radius; x < loc.getX() + radius; x++) { for (y = loc.getY() - radius - 1; y < loc.getY() - 1 + radius; y++) { for (z = loc.getZ() - radius; z < loc.getZ() + radius; z++) { check = new Location(world, x, y, z); if (check.distance(loc) < radius) { freezeBlock(check); } } } } } } else if (id == 385) { //firecharge: ghast fireball //this one might be better to do at the start... if (player.hasPermission("magicarrows.fireball")) { } } else { return; } } catch (NullPointerException e) { return; } } else { return; } } } else { return; } } }
false
true
public void onArrowHit(ProjectileHitEvent event) { Projectile projectile = (Projectile) event.getEntity(); Location loc = projectile.getLocation(); Block block = loc.getBlock(); Entity shooter = projectile.getShooter(); Player player = null; List<Integer> hotslots = new ArrayList<Integer>(); World world = projectile.getWorld(); for (int i = 0; i < 8; i++) { hotslots.add(i); } for (Player pcheck : Bukkit.getServer().getOnlinePlayers()) { if (pcheck.getEntityId() == shooter.getEntityId()) { player = pcheck; } } if (player != null) { Material modifier = Material.AIR; int id = 0; if (player.getInventory().getItemInHand().getType() == Material.BOW) { int bowslot = player.getInventory().getHeldItemSlot(); if (bowslot > 0) { try { modifier = player.getInventory().getItem(bowslot - 1).getType(); if (modifier == Material.AIR){ id = 0; } else { id = player.getInventory().getItem(bowslot - 1).getTypeId(); } if (id == 0) { return; } else if (id == 50) { //torch: place a torch where the arrow stopped if (player.hasPermission("magicarrows.torch")) { if (towny != null) { if (townyUniverse != null) { if(!PlayerCacheUtil.getCachePermission(player, loc, block.getTypeId(), TownyPermission.ActionType.BUILD)) { return; } } } else if (worldguard != null) { if (grm != null) { if (!grm.hasBypass(player, world) || !grm.canBuild(player, loc)) { return; } } } else if (block.getType() != Material.AIR) { return; } else { block.setTypeId(50); int slot = bowslot - 1; PlayerInventory inventory = player.getInventory(); ItemStack stack = inventory.getItem(slot); int amt = stack.getAmount(); stack.setAmount(amt - 1); inventory.setItem(slot, stack); projectile.remove(); plugin.incTorch(); return; } } } else if (id == 46) { //tnt: create an explosion where the arrow stops if (player.hasPermission("magicarrows.tnt")) { if (towny != null) { if (townyUniverse != null) { if(!PlayerCacheUtil.getCachePermission(player, loc, block.getTypeId(), TownyPermission.ActionType.BUILD)) { return; } } } else if (worldguard != null) { if (grm != null) { if (!grm.hasBypass(player, world) || !grm.canBuild(player, loc)) { return; } } } else { int blast = plugin.getConfig().getInt("arrows.tnt"); projectile.getWorld().createExplosion(projectile.getLocation(), blast); int slot = bowslot - 1; PlayerInventory inventory = player.getInventory(); ItemStack stack = inventory.getItem(slot); int amt = stack.getAmount(); stack.setAmount(amt - 1); inventory.setItem(slot, stack); projectile.remove(); plugin.incTNT(); return; } } } else if (id == 259) { //flint and steel: real fire arrows if (player.hasPermission("magicarrows.fire")) { if (towny != null) { if (townyUniverse != null) { if(!PlayerCacheUtil.getCachePermission(player, loc, block.getTypeId(), TownyPermission.ActionType.BUILD)) { return; } // also check if flint & steel is allowed here if(!PlayerCacheUtil.getCachePermission(player, loc, block.getTypeId(), TownyPermission.ActionType.ITEM_USE)) { // TODO figure out how to check specifically about flint and steel. return; } } } else if (worldguard != null) { if (grm != null) { if (!grm.hasBypass(player, world) || !grm.canBuild(player, loc)) { return; } // TODO also need to check if lighters are allowed here. How do I do that? } } else if (block.getType() != Material.AIR){ return; } else { block.setTypeId(51); int slot = bowslot - 1; PlayerInventory inventory = player.getInventory(); ItemStack stack = inventory.getItem(slot); short dmg = stack.getDurability(); dmg--; stack.setDurability(dmg); projectile.remove(); plugin.incFire(); } } } else if (id == 262) { //arrow: double arrow? no, if I want to do something //like this, it would have to be when shooting. } else if (id == 264) { //diamond(maybe iron instead?): lightning charge if (player.hasPermission("magicarrows.smite")) { world.strikeLightning(loc); int slot = bowslot - 1; PlayerInventory inventory = player.getInventory(); ItemStack stack = inventory.getItem(slot); int amt = stack.getAmount(); stack.setAmount(amt - 1); inventory.setItem(slot, stack); projectile.remove(); plugin.incSmite(); } } else if (id == 326) { //water bucket: water balloon? } else if (id == 332) { //snowball: freezer shot //hmm. I may have to set this one up differently... //as it is now, you will have to freeze from the bottom of the lake up. // Ah, actually, I can use this part for if it hits a block or an entity. if (player.hasPermission("magicarrows.freeze")) { plugin.incIce(); int slot = bowslot - 1; PlayerInventory inventory = player.getInventory(); ItemStack stack = inventory.getItem(slot); int amt = stack.getAmount(); stack.setAmount(amt - 1); inventory.setItem(slot, stack); projectile.remove(); // Check the blocks in the appropriate radius around the arrow // If water, lava, fire, or an entity is found // freeze it. Produce smoke effect around the entity // and prevent it from moving or attacking for five seconds or so. // appropriate radius... 3 or so, I guess. // get these from config later, maybe. int radius = 3; int frzTime = 5; int diameter = 2*radius; Location check = loc; double x, y, z; for (x = loc.getX() - radius; x < loc.getX() + radius; x++) { for (y = loc.getY() - radius - 1; y < loc.getY() - 1 + radius; y++) { for (z = loc.getZ() - radius; z < loc.getZ() + radius; z++) { check = new Location(world, x, y, z); if (check.distance(loc) < radius) { freezeBlock(check); } } } } for (x = loc.getX() - radius; x < loc.getX() + radius; x++) { for (y = loc.getY() - radius - 1; y < loc.getY() - 1 + radius; y++) { for (z = loc.getZ() - radius; z < loc.getZ() + radius; z++) { check = new Location(world, x, y, z); if (check.distance(loc) < radius) { freezeBlock(check); } } } } } } else if (id == 385) { //firecharge: ghast fireball //this one might be better to do at the start... if (player.hasPermission("magicarrows.fireball")) { } } else { return; } } catch (NullPointerException e) { return; } } else { return; } } } else { return; } }
public void onArrowHit(ProjectileHitEvent event) { Projectile projectile = (Projectile) event.getEntity(); Location loc = projectile.getLocation(); Block block = loc.getBlock(); Entity shooter = projectile.getShooter(); Player player = null; World world = projectile.getWorld(); for (Player pcheck : Bukkit.getServer().getOnlinePlayers()) { if (pcheck.getEntityId() == shooter.getEntityId()) { player = pcheck; } } if (player == null) { return; } else if (player != null) { Material modifier = Material.AIR; int id = 0; if (player.getInventory().getItemInHand().getType() == Material.BOW) { int bowslot = player.getInventory().getHeldItemSlot(); if (bowslot > 0) { try { modifier = player.getInventory().getItem(bowslot - 1).getType(); if (modifier == Material.AIR){ id = 0; } else { id = player.getInventory().getItem(bowslot - 1).getTypeId(); } if (id == 0) { return; } else if (id == 50) { //torch: place a torch where the arrow stopped if (player.hasPermission("magicarrows.torch")) { if (towny != null) { if (townyUniverse != null) { if(!PlayerCacheUtil.getCachePermission(player, loc, block.getTypeId(), TownyPermission.ActionType.BUILD)) { return; } } } else if (worldguard != null) { if (grm != null) { if (!grm.hasBypass(player, world) || !grm.canBuild(player, loc)) { return; } } } else if (block.getType() != Material.AIR) { return; } else { block.setTypeId(50); int slot = bowslot - 1; PlayerInventory inventory = player.getInventory(); ItemStack stack = inventory.getItem(slot); int amt = stack.getAmount(); stack.setAmount(amt - 1); inventory.setItem(slot, stack); projectile.remove(); plugin.incTorch(); return; } } } else if (id == 46) { //tnt: create an explosion where the arrow stops if (player.hasPermission("magicarrows.tnt")) { if (towny != null) { if (townyUniverse != null) { if(!PlayerCacheUtil.getCachePermission(player, loc, block.getTypeId(), TownyPermission.ActionType.BUILD)) { return; } } } else if (worldguard != null) { if (grm != null) { if (!grm.hasBypass(player, world) || !grm.canBuild(player, loc)) { return; } } } else { int blast = plugin.getConfig().getInt("arrows.tnt"); projectile.getWorld().createExplosion(projectile.getLocation(), blast); int slot = bowslot - 1; PlayerInventory inventory = player.getInventory(); ItemStack stack = inventory.getItem(slot); int amt = stack.getAmount(); stack.setAmount(amt - 1); inventory.setItem(slot, stack); projectile.remove(); plugin.incTNT(); return; } } } else if (id == 259) { //flint and steel: real fire arrows if (player.hasPermission("magicarrows.fire")) { if (towny != null) { if (townyUniverse != null) { if(!PlayerCacheUtil.getCachePermission(player, loc, block.getTypeId(), TownyPermission.ActionType.BUILD)) { return; } // also check if flint & steel is allowed here if(!PlayerCacheUtil.getCachePermission(player, loc, block.getTypeId(), TownyPermission.ActionType.ITEM_USE)) { // TODO figure out how to check specifically about flint and steel. return; } } } else if (worldguard != null) { if (grm != null) { if (!grm.hasBypass(player, world) || !grm.canBuild(player, loc)) { return; } // TODO also need to check if lighters are allowed here. How do I do that? } } else if (block.getType() != Material.AIR){ return; } else { block.setTypeId(51); int slot = bowslot - 1; PlayerInventory inventory = player.getInventory(); ItemStack stack = inventory.getItem(slot); short dmg = stack.getDurability(); dmg++; stack.setDurability(dmg); projectile.remove(); plugin.incFire(); } } } else if (id == 262) { //arrow: double arrow? no, if I want to do something //like this, it would have to be when shooting. } else if (id == 264) { //diamond(maybe iron instead?): lightning charge if (player.hasPermission("magicarrows.smite")) { world.strikeLightning(loc); int slot = bowslot - 1; PlayerInventory inventory = player.getInventory(); ItemStack stack = inventory.getItem(slot); int amt = stack.getAmount(); stack.setAmount(amt - 1); inventory.setItem(slot, stack); projectile.remove(); plugin.incSmite(); } } else if (id == 326) { //water bucket: water balloon? } else if (id == 332) { //snowball: freezer shot //hmm. I may have to set this one up differently... //as it is now, you will have to freeze from the bottom of the lake up. // Ah, actually, I can use this part for if it hits a block or an entity. if (player.hasPermission("magicarrows.freeze")) { plugin.incIce(); int slot = bowslot - 1; PlayerInventory inventory = player.getInventory(); ItemStack stack = inventory.getItem(slot); int amt = stack.getAmount(); stack.setAmount(amt - 1); inventory.setItem(slot, stack); projectile.remove(); // Check the blocks in the appropriate radius around the arrow // If water, lava, fire, or an entity is found // freeze it. Produce smoke effect around the entity // and prevent it from moving or attacking for five seconds or so. // appropriate radius... 3 or so, I guess. // get these from config later, maybe. int radius = 3; int frzTime = 5; int diameter = 2*radius; Location check = loc; double x, y, z; for (x = loc.getX() - radius; x < loc.getX() + radius; x++) { for (y = loc.getY() - radius - 1; y < loc.getY() - 1 + radius; y++) { for (z = loc.getZ() - radius; z < loc.getZ() + radius; z++) { check = new Location(world, x, y, z); if (check.distance(loc) < radius) { freezeBlock(check); } } } } for (x = loc.getX() - radius; x < loc.getX() + radius; x++) { for (y = loc.getY() - radius - 1; y < loc.getY() - 1 + radius; y++) { for (z = loc.getZ() - radius; z < loc.getZ() + radius; z++) { check = new Location(world, x, y, z); if (check.distance(loc) < radius) { freezeBlock(check); } } } } } } else if (id == 385) { //firecharge: ghast fireball //this one might be better to do at the start... if (player.hasPermission("magicarrows.fireball")) { } } else { return; } } catch (NullPointerException e) { return; } } else { return; } } } else { return; } }
diff --git a/atlassian-plugins-refimpl/src/main/java/com/atlassian/plugin/refimpl/ContainerManager.java b/atlassian-plugins-refimpl/src/main/java/com/atlassian/plugin/refimpl/ContainerManager.java index 263bd0fd..3cac12e3 100644 --- a/atlassian-plugins-refimpl/src/main/java/com/atlassian/plugin/refimpl/ContainerManager.java +++ b/atlassian-plugins-refimpl/src/main/java/com/atlassian/plugin/refimpl/ContainerManager.java @@ -1,203 +1,203 @@ package com.atlassian.plugin.refimpl; import com.atlassian.plugin.*; import com.atlassian.plugin.event.PluginEventManager; import com.atlassian.plugin.main.AtlassianPlugins; import com.atlassian.plugin.main.PluginsConfiguration; import com.atlassian.plugin.main.PluginsConfigurationBuilder; import com.atlassian.plugin.osgi.container.OsgiContainerManager; import com.atlassian.plugin.osgi.container.impl.DefaultPackageScannerConfiguration; import com.atlassian.plugin.osgi.hostcomponents.ComponentRegistrar; import com.atlassian.plugin.osgi.hostcomponents.HostComponentProvider; import com.atlassian.plugin.refimpl.servlet.SimpleContextListenerModuleDescriptor; import com.atlassian.plugin.refimpl.servlet.SimpleFilterModuleDescriptor; import com.atlassian.plugin.refimpl.servlet.SimpleServletModuleDescriptor; import com.atlassian.plugin.refimpl.webresource.SimpleWebResourceIntegration; import com.atlassian.plugin.servlet.*; import com.atlassian.plugin.servlet.descriptors.ServletContextParamModuleDescriptor; import com.atlassian.plugin.webresource.WebResourceIntegration; import com.atlassian.plugin.webresource.WebResourceManager; import com.atlassian.plugin.webresource.WebResourceManagerImpl; import com.atlassian.plugin.webresource.WebResourceModuleDescriptor; import javax.servlet.ServletContext; import java.io.File; import java.util.*; /** * A simple class that behaves like Spring's ContianerManager class. */ public class ContainerManager { private final ServletModuleManager servletModuleManager; private final SimpleWebResourceIntegration webResourceIntegration; private final WebResourceManager webResourceManager; private final OsgiContainerManager osgiContainerManager; private final PluginAccessor pluginAccessor; private final HostComponentProvider hostComponentProvider; private final DefaultModuleDescriptorFactory moduleDescriptorFactory; private final Map<Class,Object> publicContainer; private final AtlassianPlugins plugins; private static ContainerManager instance; private List<DownloadStrategy> downloadStrategies; public ContainerManager(ServletContext servletContext) { instance = this; webResourceIntegration = new SimpleWebResourceIntegration(servletContext); webResourceManager = new WebResourceManagerImpl(webResourceIntegration); File pluginDir = new File(servletContext.getRealPath("/WEB-INF/plugins")); if (!pluginDir.exists()) { pluginDir.mkdirs(); } File bundlesDir = new File(servletContext.getRealPath("/WEB-INF/framework-bundles")); if (!bundlesDir.exists()) { bundlesDir.mkdirs(); } moduleDescriptorFactory = new DefaultModuleDescriptorFactory(); moduleDescriptorFactory.addModuleDescriptor("servlet", SimpleServletModuleDescriptor.class); moduleDescriptorFactory.addModuleDescriptor("servlet-filter", SimpleFilterModuleDescriptor.class); moduleDescriptorFactory.addModuleDescriptor("servlet-context-param", ServletContextParamModuleDescriptor.class); moduleDescriptorFactory.addModuleDescriptor("servlet-context-listener", SimpleContextListenerModuleDescriptor.class); moduleDescriptorFactory.addModuleDescriptor("web-resource", WebResourceModuleDescriptor.class); DefaultPackageScannerConfiguration scannerConfig = new DefaultPackageScannerConfiguration(); List<String> packageIncludes = new ArrayList<String>(scannerConfig.getPackageIncludes()); packageIncludes.add("org.bouncycastle*"); scannerConfig.setPackageIncludes(packageIncludes); hostComponentProvider = new SimpleHostComponentProvider(); PluginsConfiguration config = new PluginsConfigurationBuilder() .setPluginDirectory(pluginDir) .setModuleDescriptorFactory(moduleDescriptorFactory) .setPackageScannerConfiguration(scannerConfig) .setHostComponentProvider(hostComponentProvider) - .setFrameworkBundlesDirectory() + .setFrameworkBundlesDirectory(bundlesDir) .build(); plugins = new AtlassianPlugins(config); PluginEventManager pluginEventManager = plugins.getPluginEventManager(); osgiContainerManager = plugins.getOsgiContainerManager(); servletModuleManager = new DefaultServletModuleManager(pluginEventManager); publicContainer = new HashMap<Class,Object>(); pluginAccessor = plugins.getPluginAccessor(); publicContainer.put(PluginController.class, plugins.getPluginController()); publicContainer.put(PluginAccessor.class, pluginAccessor); publicContainer.put(PluginEventManager.class, pluginEventManager); publicContainer.put(Map.class, publicContainer); try { plugins.start(); } catch (PluginParseException e) { e.printStackTrace(); } downloadStrategies = new ArrayList<DownloadStrategy>(); PluginResourceDownload pluginDownloadStrategy = new PluginResourceDownload(); pluginDownloadStrategy.setPluginAccessor(pluginAccessor); pluginDownloadStrategy.setContentTypeResolver(new SimpleContentTypeResolver()); pluginDownloadStrategy.setCharacterEncoding("UTF-8"); downloadStrategies.add(pluginDownloadStrategy); } public static synchronized void setInstance(ContainerManager mgr) { instance = mgr; } public static synchronized ContainerManager getInstance() { return instance; } public ServletModuleManager getServletModuleManager() { return servletModuleManager; } public OsgiContainerManager getOsgiContainerManager() { return osgiContainerManager; } public PluginAccessor getPluginAccessor() { return pluginAccessor; } public HostComponentProvider getHostComponentProvider() { return hostComponentProvider; } public ModuleDescriptorFactory getModuleDescriptorFactory() { return moduleDescriptorFactory; } public List<DownloadStrategy> getDownloadStrategies() { return downloadStrategies; } public WebResourceManager getWebResourceManager() { return webResourceManager; } public WebResourceIntegration getWebResourceIntegration() { return webResourceIntegration; } void shutdown() { plugins.stop(); } /** * A simple content type resolver that can identify css and js resources. */ private class SimpleContentTypeResolver implements ContentTypeResolver { private final Map<String, String> mimeTypes; SimpleContentTypeResolver() { Map<String, String> types = new HashMap<String, String>(); types.put("js", "application/x-javascript"); types.put("css", "text/css"); mimeTypes = Collections.unmodifiableMap(types); } public String getContentType(String requestUrl) { String extension = requestUrl.substring(requestUrl.lastIndexOf('.')); return mimeTypes.get(extension); } } private class SimpleHostComponentProvider implements HostComponentProvider { public void provide(ComponentRegistrar componentRegistrar) { for (Map.Entry<Class,Object> entry : publicContainer.entrySet()) { String name = entry.getKey().getSimpleName(); name = Character.toLowerCase(name.charAt(0)) + name.substring(1); componentRegistrar.register(entry.getKey()).forInstance(entry.getValue()).withName(name); } componentRegistrar.register(WebResourceManager.class).forInstance(webResourceManager).withName("webResourceManager"); } } }
true
true
public ContainerManager(ServletContext servletContext) { instance = this; webResourceIntegration = new SimpleWebResourceIntegration(servletContext); webResourceManager = new WebResourceManagerImpl(webResourceIntegration); File pluginDir = new File(servletContext.getRealPath("/WEB-INF/plugins")); if (!pluginDir.exists()) { pluginDir.mkdirs(); } File bundlesDir = new File(servletContext.getRealPath("/WEB-INF/framework-bundles")); if (!bundlesDir.exists()) { bundlesDir.mkdirs(); } moduleDescriptorFactory = new DefaultModuleDescriptorFactory(); moduleDescriptorFactory.addModuleDescriptor("servlet", SimpleServletModuleDescriptor.class); moduleDescriptorFactory.addModuleDescriptor("servlet-filter", SimpleFilterModuleDescriptor.class); moduleDescriptorFactory.addModuleDescriptor("servlet-context-param", ServletContextParamModuleDescriptor.class); moduleDescriptorFactory.addModuleDescriptor("servlet-context-listener", SimpleContextListenerModuleDescriptor.class); moduleDescriptorFactory.addModuleDescriptor("web-resource", WebResourceModuleDescriptor.class); DefaultPackageScannerConfiguration scannerConfig = new DefaultPackageScannerConfiguration(); List<String> packageIncludes = new ArrayList<String>(scannerConfig.getPackageIncludes()); packageIncludes.add("org.bouncycastle*"); scannerConfig.setPackageIncludes(packageIncludes); hostComponentProvider = new SimpleHostComponentProvider(); PluginsConfiguration config = new PluginsConfigurationBuilder() .setPluginDirectory(pluginDir) .setModuleDescriptorFactory(moduleDescriptorFactory) .setPackageScannerConfiguration(scannerConfig) .setHostComponentProvider(hostComponentProvider) .setFrameworkBundlesDirectory() .build(); plugins = new AtlassianPlugins(config); PluginEventManager pluginEventManager = plugins.getPluginEventManager(); osgiContainerManager = plugins.getOsgiContainerManager(); servletModuleManager = new DefaultServletModuleManager(pluginEventManager); publicContainer = new HashMap<Class,Object>(); pluginAccessor = plugins.getPluginAccessor(); publicContainer.put(PluginController.class, plugins.getPluginController()); publicContainer.put(PluginAccessor.class, pluginAccessor); publicContainer.put(PluginEventManager.class, pluginEventManager); publicContainer.put(Map.class, publicContainer); try { plugins.start(); } catch (PluginParseException e) { e.printStackTrace(); } downloadStrategies = new ArrayList<DownloadStrategy>(); PluginResourceDownload pluginDownloadStrategy = new PluginResourceDownload(); pluginDownloadStrategy.setPluginAccessor(pluginAccessor); pluginDownloadStrategy.setContentTypeResolver(new SimpleContentTypeResolver()); pluginDownloadStrategy.setCharacterEncoding("UTF-8"); downloadStrategies.add(pluginDownloadStrategy); }
public ContainerManager(ServletContext servletContext) { instance = this; webResourceIntegration = new SimpleWebResourceIntegration(servletContext); webResourceManager = new WebResourceManagerImpl(webResourceIntegration); File pluginDir = new File(servletContext.getRealPath("/WEB-INF/plugins")); if (!pluginDir.exists()) { pluginDir.mkdirs(); } File bundlesDir = new File(servletContext.getRealPath("/WEB-INF/framework-bundles")); if (!bundlesDir.exists()) { bundlesDir.mkdirs(); } moduleDescriptorFactory = new DefaultModuleDescriptorFactory(); moduleDescriptorFactory.addModuleDescriptor("servlet", SimpleServletModuleDescriptor.class); moduleDescriptorFactory.addModuleDescriptor("servlet-filter", SimpleFilterModuleDescriptor.class); moduleDescriptorFactory.addModuleDescriptor("servlet-context-param", ServletContextParamModuleDescriptor.class); moduleDescriptorFactory.addModuleDescriptor("servlet-context-listener", SimpleContextListenerModuleDescriptor.class); moduleDescriptorFactory.addModuleDescriptor("web-resource", WebResourceModuleDescriptor.class); DefaultPackageScannerConfiguration scannerConfig = new DefaultPackageScannerConfiguration(); List<String> packageIncludes = new ArrayList<String>(scannerConfig.getPackageIncludes()); packageIncludes.add("org.bouncycastle*"); scannerConfig.setPackageIncludes(packageIncludes); hostComponentProvider = new SimpleHostComponentProvider(); PluginsConfiguration config = new PluginsConfigurationBuilder() .setPluginDirectory(pluginDir) .setModuleDescriptorFactory(moduleDescriptorFactory) .setPackageScannerConfiguration(scannerConfig) .setHostComponentProvider(hostComponentProvider) .setFrameworkBundlesDirectory(bundlesDir) .build(); plugins = new AtlassianPlugins(config); PluginEventManager pluginEventManager = plugins.getPluginEventManager(); osgiContainerManager = plugins.getOsgiContainerManager(); servletModuleManager = new DefaultServletModuleManager(pluginEventManager); publicContainer = new HashMap<Class,Object>(); pluginAccessor = plugins.getPluginAccessor(); publicContainer.put(PluginController.class, plugins.getPluginController()); publicContainer.put(PluginAccessor.class, pluginAccessor); publicContainer.put(PluginEventManager.class, pluginEventManager); publicContainer.put(Map.class, publicContainer); try { plugins.start(); } catch (PluginParseException e) { e.printStackTrace(); } downloadStrategies = new ArrayList<DownloadStrategy>(); PluginResourceDownload pluginDownloadStrategy = new PluginResourceDownload(); pluginDownloadStrategy.setPluginAccessor(pluginAccessor); pluginDownloadStrategy.setContentTypeResolver(new SimpleContentTypeResolver()); pluginDownloadStrategy.setCharacterEncoding("UTF-8"); downloadStrategies.add(pluginDownloadStrategy); }
diff --git a/nuxeo-platform-ui-web/src/main/java/org/nuxeo/ecm/platform/ui/web/rest/FancyURLResponseWrapper.java b/nuxeo-platform-ui-web/src/main/java/org/nuxeo/ecm/platform/ui/web/rest/FancyURLResponseWrapper.java index a3010ab07..9194bca57 100644 --- a/nuxeo-platform-ui-web/src/main/java/org/nuxeo/ecm/platform/ui/web/rest/FancyURLResponseWrapper.java +++ b/nuxeo-platform-ui-web/src/main/java/org/nuxeo/ecm/platform/ui/web/rest/FancyURLResponseWrapper.java @@ -1,123 +1,128 @@ /* * (C) Copyright 2006-2007 Nuxeo SAS (http://nuxeo.com/) and contributors. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * Contributors: * Nuxeo - initial API and implementation * * $Id: FancyURLResponseWrapper.java 28924 2008-01-10 14:04:05Z sfermigier $ */ package org.nuxeo.ecm.platform.ui.web.rest; import java.io.IOException; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponseWrapper; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.nuxeo.common.utils.URIUtils; import org.nuxeo.ecm.platform.ui.web.rest.api.URLPolicyService; import org.nuxeo.ecm.platform.ui.web.util.BaseURL; import org.nuxeo.ecm.platform.url.api.DocumentView; import org.nuxeo.runtime.api.Framework; /** * Used in post methods to rewrite the url with needed get params. * * Encapsulates response into a wrapper. */ public class FancyURLResponseWrapper extends HttpServletResponseWrapper { private static final Log log = LogFactory.getLog(FancyURLResponseWrapper.class); protected HttpServletRequest request = null; protected StaticNavigationHandler navigationHandler; public FancyURLResponseWrapper(HttpServletResponse response) { super(response); } public FancyURLResponseWrapper(HttpServletResponse response, HttpServletRequest request, StaticNavigationHandler navigationHandler) { super(response); this.request = request; this.navigationHandler = navigationHandler; } protected String getViewId(String url, HttpServletRequest request) { return null; } /** * Rewrites url for given document view but extracts view id from the * original url. */ protected String rewriteUrl(String url, DocumentView docView, URLPolicyService service) throws Exception { // try to get outcome that was saved in request by // FancyNavigationHandler String newViewId = (String) request.getAttribute(URLPolicyService.POST_OUTCOME_REQUEST_KEY); String baseUrl = BaseURL.getBaseURL(request); if (newViewId != null) { docView.setViewId(newViewId); } else { // parse url to get outcome from view id String viewId = url; + String webAppName = "/" + BaseURL.getWebAppName(); if (viewId.startsWith(baseUrl)) { + // url is absolute viewId = '/' + viewId.substring(baseUrl.length()); + } else if (viewId.startsWith(webAppName)) { + // url is relative to the web app + viewId = viewId.substring(webAppName.length()); } int index = viewId.indexOf('?'); if (index != -1) { viewId = viewId.substring(0, index); } - docView.setViewId(navigationHandler.getOutcomeFromViewId(viewId)); + String jsfOutcome = navigationHandler.getOutcomeFromViewId(viewId); + docView.setViewId(jsfOutcome); } int index = url.indexOf('?'); if (index != -1) { String uriString = url.substring(index + 1); - Map<String, String> parameters = URIUtils.getRequestParameters( - uriString); + Map<String, String> parameters = URIUtils.getRequestParameters(uriString); if (parameters != null) { for (Map.Entry<String, String> entry : parameters.entrySet()) { docView.addParameter(entry.getKey(), entry.getValue()); } } } url = service.getUrlFromDocumentView(docView, baseUrl); return url; } @Override public void sendRedirect(String url) throws IOException { if (request != null) { try { URLPolicyService pservice = Framework.getService(URLPolicyService.class); if (pservice.isCandidateForEncoding(request)) { DocumentView docView = pservice.getDocumentViewFromRequest(request); if (docView != null) { url = rewriteUrl(url, docView, pservice); } } } catch (Exception e) { log.error("Could not redirect", e); } } super.sendRedirect(url); } }
false
true
protected String rewriteUrl(String url, DocumentView docView, URLPolicyService service) throws Exception { // try to get outcome that was saved in request by // FancyNavigationHandler String newViewId = (String) request.getAttribute(URLPolicyService.POST_OUTCOME_REQUEST_KEY); String baseUrl = BaseURL.getBaseURL(request); if (newViewId != null) { docView.setViewId(newViewId); } else { // parse url to get outcome from view id String viewId = url; if (viewId.startsWith(baseUrl)) { viewId = '/' + viewId.substring(baseUrl.length()); } int index = viewId.indexOf('?'); if (index != -1) { viewId = viewId.substring(0, index); } docView.setViewId(navigationHandler.getOutcomeFromViewId(viewId)); } int index = url.indexOf('?'); if (index != -1) { String uriString = url.substring(index + 1); Map<String, String> parameters = URIUtils.getRequestParameters( uriString); if (parameters != null) { for (Map.Entry<String, String> entry : parameters.entrySet()) { docView.addParameter(entry.getKey(), entry.getValue()); } } } url = service.getUrlFromDocumentView(docView, baseUrl); return url; }
protected String rewriteUrl(String url, DocumentView docView, URLPolicyService service) throws Exception { // try to get outcome that was saved in request by // FancyNavigationHandler String newViewId = (String) request.getAttribute(URLPolicyService.POST_OUTCOME_REQUEST_KEY); String baseUrl = BaseURL.getBaseURL(request); if (newViewId != null) { docView.setViewId(newViewId); } else { // parse url to get outcome from view id String viewId = url; String webAppName = "/" + BaseURL.getWebAppName(); if (viewId.startsWith(baseUrl)) { // url is absolute viewId = '/' + viewId.substring(baseUrl.length()); } else if (viewId.startsWith(webAppName)) { // url is relative to the web app viewId = viewId.substring(webAppName.length()); } int index = viewId.indexOf('?'); if (index != -1) { viewId = viewId.substring(0, index); } String jsfOutcome = navigationHandler.getOutcomeFromViewId(viewId); docView.setViewId(jsfOutcome); } int index = url.indexOf('?'); if (index != -1) { String uriString = url.substring(index + 1); Map<String, String> parameters = URIUtils.getRequestParameters(uriString); if (parameters != null) { for (Map.Entry<String, String> entry : parameters.entrySet()) { docView.addParameter(entry.getKey(), entry.getValue()); } } } url = service.getUrlFromDocumentView(docView, baseUrl); return url; }
diff --git a/src/com/vloxlands/scene/SceneNewGame.java b/src/com/vloxlands/scene/SceneNewGame.java index 9c3e6ad..79cf5b0 100644 --- a/src/com/vloxlands/scene/SceneNewGame.java +++ b/src/com/vloxlands/scene/SceneNewGame.java @@ -1,108 +1,108 @@ package com.vloxlands.scene; import static org.lwjgl.opengl.GL11.*; import org.lwjgl.opengl.Display; import com.vloxlands.game.Game; import com.vloxlands.gen.MapGenerator; import com.vloxlands.settings.Tr; import com.vloxlands.ui.Container; import com.vloxlands.ui.GuiRotation; import com.vloxlands.ui.IGuiEvent; import com.vloxlands.ui.Label; import com.vloxlands.ui.ProgressBar; import com.vloxlands.ui.Spinner; import com.vloxlands.ui.TextButton; import com.vloxlands.util.RenderAssistant; public class SceneNewGame extends Scene { ProgressBar progress; Spinner xSize, zSize, radius; @Override public void init() { - if (!Game.client.isConnected()) Game.client.connectToServer(Game.IP); + if (Game.client != null && !Game.client.isConnected()) Game.client.connectToServer(Game.IP); setBackground(); // setUserZone(); setTitle(Tr._("newGame")); content.add(new Container(0, 115, Display.getWidth() - TextButton.WIDTH - 90, Display.getHeight() - 220 - TextButton.HEIGHT - 30)); // lobby Container lobbyButtons = new Container(0, 115 + Display.getHeight() - 220 - TextButton.HEIGHT - 30, Display.getWidth() - TextButton.WIDTH - 90, TextButton.HEIGHT + 30, false, false); content.add(lobbyButtons); content.add(new Container(Display.getWidth() - TextButton.WIDTH - 90, 115, TextButton.WIDTH + 90, Display.getHeight() - 220)); progress = new ProgressBar(Display.getWidth() / 2, Display.getHeight() / 2 - ProgressBar.HEIGHT / 2, 400, 0, true); progress.setVisible(false); content.add(progress); TextButton back = new TextButton(Display.getWidth() / 2 - TextButton.WIDTH / 2, Display.getHeight() - TextButton.HEIGHT, Tr._("back")); back.setClickEvent(new IGuiEvent() { @Override public void trigger() { Game.currentGame.removeScene(SceneNewGame.this); } }); content.add(back); TextButton skip = new TextButton(Display.getWidth() / 2 + TextButton.WIDTH / 2, Display.getHeight() - TextButton.HEIGHT, Tr._("start")); skip.setClickEvent(new IGuiEvent() { @Override public void trigger() { Game.mapGenerator = new MapGenerator(xSize.getValue(), zSize.getValue(), 20, 24); Game.mapGenerator.start(); lockScene(); progress.setVisible(true); } }); content.add(skip); content.add(new Label(Display.getWidth() - TextButton.WIDTH - 70, 130, (TextButton.WIDTH + 70) / 2, 25, "X-" + Tr._("islands") + ":", false)); xSize = new Spinner(Display.getWidth() - TextButton.WIDTH - 80 + (TextButton.WIDTH + 70) / 2, 125, (TextButton.WIDTH + 70) / 2, 1, 4, 1, 1, GuiRotation.HORIZONTAL); content.add(xSize); content.add(new Label(Display.getWidth() - TextButton.WIDTH - 70, 175, (TextButton.WIDTH + 70) / 2, 25, "Z-" + Tr._("islands") + ":", false)); zSize = new Spinner(Display.getWidth() - TextButton.WIDTH - 80 + (TextButton.WIDTH + 70) / 2, 170, (TextButton.WIDTH + 70) / 2, 1, 4, 1, 1, GuiRotation.HORIZONTAL); content.add(zSize); } @Override public void onTick() { super.onTick(); if (Game.currentMap != null) Game.currentGame.setScene(new SceneGame()); } @Override public void render() { super.render(); if (Game.mapGenerator != null) { glEnable(GL_BLEND); glColor4f(0.4f, 0.4f, 0.4f, 0.6f); glBindTexture(GL_TEXTURE_2D, 0); RenderAssistant.renderRect(0, 0, Display.getWidth(), Display.getHeight()); glColor4f(1, 1, 1, 1); progress.setValue(Game.mapGenerator.progress); progress.render(); glDisable(GL_BLEND); } } }
true
true
public void init() { if (!Game.client.isConnected()) Game.client.connectToServer(Game.IP); setBackground(); // setUserZone(); setTitle(Tr._("newGame")); content.add(new Container(0, 115, Display.getWidth() - TextButton.WIDTH - 90, Display.getHeight() - 220 - TextButton.HEIGHT - 30)); // lobby Container lobbyButtons = new Container(0, 115 + Display.getHeight() - 220 - TextButton.HEIGHT - 30, Display.getWidth() - TextButton.WIDTH - 90, TextButton.HEIGHT + 30, false, false); content.add(lobbyButtons); content.add(new Container(Display.getWidth() - TextButton.WIDTH - 90, 115, TextButton.WIDTH + 90, Display.getHeight() - 220)); progress = new ProgressBar(Display.getWidth() / 2, Display.getHeight() / 2 - ProgressBar.HEIGHT / 2, 400, 0, true); progress.setVisible(false); content.add(progress); TextButton back = new TextButton(Display.getWidth() / 2 - TextButton.WIDTH / 2, Display.getHeight() - TextButton.HEIGHT, Tr._("back")); back.setClickEvent(new IGuiEvent() { @Override public void trigger() { Game.currentGame.removeScene(SceneNewGame.this); } }); content.add(back); TextButton skip = new TextButton(Display.getWidth() / 2 + TextButton.WIDTH / 2, Display.getHeight() - TextButton.HEIGHT, Tr._("start")); skip.setClickEvent(new IGuiEvent() { @Override public void trigger() { Game.mapGenerator = new MapGenerator(xSize.getValue(), zSize.getValue(), 20, 24); Game.mapGenerator.start(); lockScene(); progress.setVisible(true); } }); content.add(skip); content.add(new Label(Display.getWidth() - TextButton.WIDTH - 70, 130, (TextButton.WIDTH + 70) / 2, 25, "X-" + Tr._("islands") + ":", false)); xSize = new Spinner(Display.getWidth() - TextButton.WIDTH - 80 + (TextButton.WIDTH + 70) / 2, 125, (TextButton.WIDTH + 70) / 2, 1, 4, 1, 1, GuiRotation.HORIZONTAL); content.add(xSize); content.add(new Label(Display.getWidth() - TextButton.WIDTH - 70, 175, (TextButton.WIDTH + 70) / 2, 25, "Z-" + Tr._("islands") + ":", false)); zSize = new Spinner(Display.getWidth() - TextButton.WIDTH - 80 + (TextButton.WIDTH + 70) / 2, 170, (TextButton.WIDTH + 70) / 2, 1, 4, 1, 1, GuiRotation.HORIZONTAL); content.add(zSize); }
public void init() { if (Game.client != null && !Game.client.isConnected()) Game.client.connectToServer(Game.IP); setBackground(); // setUserZone(); setTitle(Tr._("newGame")); content.add(new Container(0, 115, Display.getWidth() - TextButton.WIDTH - 90, Display.getHeight() - 220 - TextButton.HEIGHT - 30)); // lobby Container lobbyButtons = new Container(0, 115 + Display.getHeight() - 220 - TextButton.HEIGHT - 30, Display.getWidth() - TextButton.WIDTH - 90, TextButton.HEIGHT + 30, false, false); content.add(lobbyButtons); content.add(new Container(Display.getWidth() - TextButton.WIDTH - 90, 115, TextButton.WIDTH + 90, Display.getHeight() - 220)); progress = new ProgressBar(Display.getWidth() / 2, Display.getHeight() / 2 - ProgressBar.HEIGHT / 2, 400, 0, true); progress.setVisible(false); content.add(progress); TextButton back = new TextButton(Display.getWidth() / 2 - TextButton.WIDTH / 2, Display.getHeight() - TextButton.HEIGHT, Tr._("back")); back.setClickEvent(new IGuiEvent() { @Override public void trigger() { Game.currentGame.removeScene(SceneNewGame.this); } }); content.add(back); TextButton skip = new TextButton(Display.getWidth() / 2 + TextButton.WIDTH / 2, Display.getHeight() - TextButton.HEIGHT, Tr._("start")); skip.setClickEvent(new IGuiEvent() { @Override public void trigger() { Game.mapGenerator = new MapGenerator(xSize.getValue(), zSize.getValue(), 20, 24); Game.mapGenerator.start(); lockScene(); progress.setVisible(true); } }); content.add(skip); content.add(new Label(Display.getWidth() - TextButton.WIDTH - 70, 130, (TextButton.WIDTH + 70) / 2, 25, "X-" + Tr._("islands") + ":", false)); xSize = new Spinner(Display.getWidth() - TextButton.WIDTH - 80 + (TextButton.WIDTH + 70) / 2, 125, (TextButton.WIDTH + 70) / 2, 1, 4, 1, 1, GuiRotation.HORIZONTAL); content.add(xSize); content.add(new Label(Display.getWidth() - TextButton.WIDTH - 70, 175, (TextButton.WIDTH + 70) / 2, 25, "Z-" + Tr._("islands") + ":", false)); zSize = new Spinner(Display.getWidth() - TextButton.WIDTH - 80 + (TextButton.WIDTH + 70) / 2, 170, (TextButton.WIDTH + 70) / 2, 1, 4, 1, 1, GuiRotation.HORIZONTAL); content.add(zSize); }
diff --git a/src/main/java/org/zisist/leaderboard/LeaderboardsHandlerImpl.java b/src/main/java/org/zisist/leaderboard/LeaderboardsHandlerImpl.java index 91ef378..35cbab1 100644 --- a/src/main/java/org/zisist/leaderboard/LeaderboardsHandlerImpl.java +++ b/src/main/java/org/zisist/leaderboard/LeaderboardsHandlerImpl.java @@ -1,88 +1,88 @@ package org.zisist.leaderboard; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.zisist.conf.ConfigurationLoader; import org.zisist.leaderboard.inputanalyzer.InputAnalyzer; import org.zisist.leaderboard.inputsourcehandler.InputSourceHandler; import org.zisist.leaderboard.inputsourcehandler.InputSourceHandlerFactory; import org.zisist.leaderboard.merger.Merger; import org.zisist.leaderboard.publisher.Publisher; import org.zisist.model.Configuration; import org.zisist.model.TopPlayer; import org.zisist.model.xml.Leaderboard; import org.zisist.model.xml.LeaderboardConfiguration; import java.io.InputStream; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by [email protected] on 04/10/2012 at 12:31 AM */ @Service("leaderboardsHandler") @SuppressWarnings("unchecked") public final class LeaderboardsHandlerImpl implements LeaderboardsHandler { private static Logger log = Logger.getLogger(LeaderboardsHandlerImpl.class); @Autowired private ConfigurationLoader configurationLoader; @Autowired private Map<String, InputAnalyzer> inputAnalyzersMap; @Autowired private Map<String, Publisher> publishersMap; @Autowired private Map<String,Merger<TopPlayer>> mergerMap; @Autowired private InputSourceHandlerFactory inputSourceHandlerFactory; public void setConfigurationLoader(ConfigurationLoader configurationLoader) { this.configurationLoader = configurationLoader; } public void setInputAnalyzersMap(Map<String, InputAnalyzer> inputAnalyzersMap) { this.inputAnalyzersMap = inputAnalyzersMap; } public void setPublishersMap(Map<String, Publisher> publishersMap) { this.publishersMap = publishersMap; } public void setMergerMap(Map<String, Merger<TopPlayer>> mergerMap) { this.mergerMap = mergerMap; } public void setInputSourceHandlerFactory(InputSourceHandlerFactory inputSourceHandlerFactory) { this.inputSourceHandlerFactory = inputSourceHandlerFactory; } @Override public final void handleLeaderboards(Configuration configuration) { LeaderboardConfiguration leaderboardConfiguration = configurationLoader.getConfiguration(configuration.getConfigurationName()); log.info(String.format("Loaded configuration %s...", leaderboardConfiguration.getName())); Map<String, List<TopPlayer>> topPlayersPerRegion = new HashMap<String, List<TopPlayer>>(); for (Leaderboard board : leaderboardConfiguration.getLeaderboards().getLeaderboard()) { // open stream to source String inputSourceURI = board.getInputUri(); InputSourceHandler source = inputSourceHandlerFactory.getInputSourceHandler(inputSourceURI); InputStream inputStream = source.openStream(inputSourceURI); log.info(String.format("Read input from %s using handler %s", inputSourceURI, source)); // read from source and generate meaningful representation of data InputAnalyzer analyzer = inputAnalyzersMap.get(board.getInputAnalyzer()); List<TopPlayer> topPlayers = analyzer.getTopPlayersFromInputSource(inputStream); log.info(String.format("Analyzed input using analyzer %s", board.getInputAnalyzer())); - topPlayersPerRegion.put(board.getInputAnalyzer(), topPlayers); + topPlayersPerRegion.put(board.getInputAnalyzer() + "_" + board.getInputUri().hashCode(), topPlayers); } // handle the data from all sources Merger merger = mergerMap.get(leaderboardConfiguration.getMerger()); List<TopPlayer> finalList = merger.merge(topPlayersPerRegion); log.info(String.format("Handled data from all sources using merger %s", leaderboardConfiguration.getMerger())); // publish the final results Publisher publisher = publishersMap.get(leaderboardConfiguration.getPublisher()); publisher.publish(finalList, configuration); log.info(String.format("Published results using publisher %s", leaderboardConfiguration.getPublisher())); } }
true
true
public final void handleLeaderboards(Configuration configuration) { LeaderboardConfiguration leaderboardConfiguration = configurationLoader.getConfiguration(configuration.getConfigurationName()); log.info(String.format("Loaded configuration %s...", leaderboardConfiguration.getName())); Map<String, List<TopPlayer>> topPlayersPerRegion = new HashMap<String, List<TopPlayer>>(); for (Leaderboard board : leaderboardConfiguration.getLeaderboards().getLeaderboard()) { // open stream to source String inputSourceURI = board.getInputUri(); InputSourceHandler source = inputSourceHandlerFactory.getInputSourceHandler(inputSourceURI); InputStream inputStream = source.openStream(inputSourceURI); log.info(String.format("Read input from %s using handler %s", inputSourceURI, source)); // read from source and generate meaningful representation of data InputAnalyzer analyzer = inputAnalyzersMap.get(board.getInputAnalyzer()); List<TopPlayer> topPlayers = analyzer.getTopPlayersFromInputSource(inputStream); log.info(String.format("Analyzed input using analyzer %s", board.getInputAnalyzer())); topPlayersPerRegion.put(board.getInputAnalyzer(), topPlayers); } // handle the data from all sources Merger merger = mergerMap.get(leaderboardConfiguration.getMerger()); List<TopPlayer> finalList = merger.merge(topPlayersPerRegion); log.info(String.format("Handled data from all sources using merger %s", leaderboardConfiguration.getMerger())); // publish the final results Publisher publisher = publishersMap.get(leaderboardConfiguration.getPublisher()); publisher.publish(finalList, configuration); log.info(String.format("Published results using publisher %s", leaderboardConfiguration.getPublisher())); }
public final void handleLeaderboards(Configuration configuration) { LeaderboardConfiguration leaderboardConfiguration = configurationLoader.getConfiguration(configuration.getConfigurationName()); log.info(String.format("Loaded configuration %s...", leaderboardConfiguration.getName())); Map<String, List<TopPlayer>> topPlayersPerRegion = new HashMap<String, List<TopPlayer>>(); for (Leaderboard board : leaderboardConfiguration.getLeaderboards().getLeaderboard()) { // open stream to source String inputSourceURI = board.getInputUri(); InputSourceHandler source = inputSourceHandlerFactory.getInputSourceHandler(inputSourceURI); InputStream inputStream = source.openStream(inputSourceURI); log.info(String.format("Read input from %s using handler %s", inputSourceURI, source)); // read from source and generate meaningful representation of data InputAnalyzer analyzer = inputAnalyzersMap.get(board.getInputAnalyzer()); List<TopPlayer> topPlayers = analyzer.getTopPlayersFromInputSource(inputStream); log.info(String.format("Analyzed input using analyzer %s", board.getInputAnalyzer())); topPlayersPerRegion.put(board.getInputAnalyzer() + "_" + board.getInputUri().hashCode(), topPlayers); } // handle the data from all sources Merger merger = mergerMap.get(leaderboardConfiguration.getMerger()); List<TopPlayer> finalList = merger.merge(topPlayersPerRegion); log.info(String.format("Handled data from all sources using merger %s", leaderboardConfiguration.getMerger())); // publish the final results Publisher publisher = publishersMap.get(leaderboardConfiguration.getPublisher()); publisher.publish(finalList, configuration); log.info(String.format("Published results using publisher %s", leaderboardConfiguration.getPublisher())); }
diff --git a/src/com/davecoss/android/genericserver/GenericServer.java b/src/com/davecoss/android/genericserver/GenericServer.java index da3612d..4922c51 100644 --- a/src/com/davecoss/android/genericserver/GenericServer.java +++ b/src/com/davecoss/android/genericserver/GenericServer.java @@ -1,608 +1,609 @@ package com.davecoss.android.genericserver; import java.io.File; import java.io.IOException; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import org.apache.commons.io.input.BoundedInputStream; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.FileNotFoundException; import java.net.NetworkInterface; import java.net.ServerSocket; import java.net.SocketException; import java.net.Socket; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; import javax.net.ssl.SSLException; public class GenericServer implements Runnable { protected int port = DEFAULT_PORT; protected ServerSocket listener; protected String userdir = null; protected InetAddress addr = null; protected ServerHandler handler; protected String outfile_name = "output.dat"; protected boolean has_write_permission = false; public static final String DEFAULT_HOSTNAME = "localhost"; public static final int DEFAULT_PORT = 4242; public GenericServer(ServerHandler handler) throws UnknownHostException { this.handler = handler; this.addr = InetAddress.getByName("localhost"); this.port = DEFAULT_PORT; } public GenericServer(InetAddress addr, ServerHandler handler) { this.handler = handler; this.port = DEFAULT_PORT; this.addr = addr; } public GenericServer(InetAddress addr, int port, ServerHandler handler) { this.handler = handler; this.port = port; this.addr = addr; } public HTTPReply process_request(HTTPRequest client_request) throws EmptyRequest{ if(client_request == null) throw new EmptyRequest(); String uri = client_request.get_path(); if (uri == null) return HTMLReply.invalid_request(); ArrayList<String> request = new ArrayList<String>( Arrays.asList(uri.split("/"))); if (request.size() < 2) { return new HTMLReply("Welcome", "Welcome to the server."); } request.remove(0); if (request.get(0).equals("date")) { return send_date(request); } else if (request.get(0).equals("user") && request.size() > 1) { try { return process_user_request(request); } catch(HTTPError httpe) { String err = "Error Processing user request: " + httpe.getMessage(); handler.debug("GenericServer.process_request", err); return new HTMLReply("Error processing user request", err, HTTPReply.STATUS_ERROR); } } else if (request.get(0).equals("info")) { String err_msg = "Error getting server info"; try { ByteArrayOutputStream config_buffer = new ByteArrayOutputStream(); dump_config(config_buffer); return new HTMLReply("Current config", config_buffer.toString().replaceAll("\n","<br/>\n")); } catch (Exception e) { handler.error("GenericServer.process_request", err_msg); handler.traceback(e); return new HTMLReply(err_msg, err_msg, HTTPReply.STATUS_ERROR); } } else if (request.get(0).equals("favicon.ico")) { InputStream ico_stream = get_favicon(); if(ico_stream == null) { String no_favicon = "Favicon not found"; return new HTMLReply(no_favicon, no_favicon, HTTPReply.STATUS_NOT_FOUND); } else { ImageReply retval = new ImageReply(); retval.set_input_stream(ico_stream); retval.set_image_type("x-icon"); return retval; } } else if (request.get(0).equals("echo")) { return process_echo(client_request, request); } else if (request.get(0).equals("file")) { try { return process_file(client_request, request); } catch(IOException ioe) { String err = "Error Processing File: " + ioe.getMessage(); handler.debug("GenericServer.process_request", err); return new HTMLReply("Error processing file", err, HTTPReply.STATUS_ERROR); } catch(HTTPError httpe) { String err = "Error Processing File: " + httpe.getMessage(); handler.error("GenericServer.process_request", err); return new HTMLReply("Error processing file", err, HTTPReply.STATUS_ERROR); } } return new HTMLReply(request.get(0), "You asked for (" + request.get(0) + ")"); } @Override public void run() { boolean has_fatal_error = false; handler.info("GenericServer.run", "Thread Run Called"); while (!Thread.currentThread().isInterrupted() && !has_fatal_error) { try { if (this.listener == null) start_server(); handler.info("GenericServer.run", "Listening on port " + port); Socket socket = listener.accept(); handler.info("GenericServer.run", "Opened socket on port " + port); OutputStream out = socket.getOutputStream(); HTTPRequest request = null; HTTPReply reply = null; try { @SuppressWarnings("resource") // This will be closed with socket.close() BufferedReader input = new BufferedReader(new InputStreamReader( new BoundedInputStream(socket.getInputStream(), UserFile.MAX_OUTFILE_SIZE))); String input_text = input.readLine(); while (input_text != null && !Thread.currentThread().isInterrupted()) { reply = HTMLReply.invalid_request();// Prove me wrong. handler.info("GenericServer.run", "Client Said: " + input_text); String[] request_tokens = input_text.split(" "); int request_data_len = input_text.length(); if(request_data_len > 0 && request_tokens.length < 2) { handler.debug("GenericServer.run", "Invalid Request String Length: " + input_text); } else if (request_tokens[0].equals("GET") || request_tokens[0].equals("POST")) { handler.debug("GenericServer.run", input_text); request = new HTTPRequest(request_tokens[0], request_tokens[1]); } else if(request != null && request_data_len != 0) { try { request.put_request_data(input_text); } catch(InvalidRequestData ird) { handler.error("GenericServer.run", "Invalid Data from Client: " + ird); handler.traceback(ird); } } out.flush(); if (request_data_len == 0) { if(request != null) { handler.info("GenericServer.run", "Received Request"); handler.info("GenericServer.run", request.toString()); } break; } input_text = input.readLine(); if (input_text == "") handler.debug("GenericServer.run", "Empty string"); } try{ if(request != null && request.get_type() == HTTPRequest.RequestType.POST) { String len_as_str = request.get_request_data("Content-Length"); if(len_as_str != null) { try { int post_len = Integer.parseInt(len_as_str); if(post_len >= UserFile.MAX_OUTFILE_SIZE) { String err = "Too much post data sent. Sent: " + post_len; handler.debug("GenericServer.run", err); reply = new HTMLReply("Error", err, HTTPReply.STATUS_FORBIDDEN); continue; } char[] buffer = new char[post_len]; handler.info("GenericServer.run", "Reading " + post_len + " bytes of post data"); input.read(buffer, 0, post_len); String post_data = new String(buffer); handler.info("GenericServer.run", "POST Data: " + post_data); request.put_post_data(post_data); } catch(NumberFormatException nfe) { handler.error("GenericServer.run", "Invalid Content-Length: " + len_as_str); handler.error("GenericServer.run", nfe.getMessage()); handler.traceback(nfe); } } } reply = process_request(request); - } - catch(HTTPError httperr) - { + } catch (EmptyRequest er) { + handler.debug("GenericServer.run", "Empty Response"); + reply = new HTMLReply("Empty Response", "Empty Response", HTTPReply.STATUS_ERROR); + } catch(HTTPError httperr) { handler.error("GenericServer.run", "HTTP ERROR: " + httperr); handler.traceback(httperr); reply = new HTMLReply("ERROR", "Server Error", HTTPReply.STATUS_ERROR); } } finally { if(reply != null && !socket.isClosed()) { handler.debug("GenericServer.run", "Sending reply"); reply.write(out); } handler.info("GenericServer.run", "Closing socket"); socket.close(); handler.info("GenericServer.run", "Socket closed"); } } catch (SSLException ssle) { handler.error("GenericServer.run", "SSLException: " + ssle.getMessage()); } catch (SocketException se) { if(!se.getMessage().equals("Socket closed") && !se.getMessage().equals("Socket is closed")) { handler.error("GenericServer.run", "Socket closed"); handler.traceback(se); } } catch (IOException ioe) { handler.error("GenericServer.run", "IOException: " + ioe.getMessage()); handler.traceback(ioe); } catch(HTTPError httpe) { handler.error("GenericServer.run", "Server Error"); handler.traceback(httpe); has_fatal_error = true; } }// while not interrupted } protected ServerSocket get_new_socket() throws IOException, HTTPError { handler.debug("GenericServer.get_new_socket", "Creating new Socket"); return new ServerSocket(this.port, 0, this.addr); } protected synchronized void start_server() throws IOException, javax.net.ssl.SSLException, HTTPError { handler.info("GenericServer.start_server", "Server starting " + this.addr.getHostAddress() + ":" + this.port); try { if(listener != null && !listener.isClosed()) listener.close(); handler.info("GenericServer.start_server", "Getting new socket"); listener = get_new_socket(); handler.info("GenericServer.start_server", "Have socket"); } catch(javax.net.ssl.SSLException ssle) { handler.error("GenericServer.start_server", "IOException: " + ssle.getMessage()); handler.traceback(ssle); throw ssle; } catch (IOException ioe) { handler.error("GenericServer.start_server", "IOException: " + ioe.getMessage()); handler.traceback(ioe); } } protected void start_server(InetAddress addr, int port) throws IOException, HTTPError { this.port = port; this.addr = addr; start_server(); } public void stop_server() { if (this.listener != null && !this.listener.isClosed()) { try { handler.info("GenericServer.stop_server", "Closing ServerSocket"); this.listener.close(); handler.info("GenericServer.stop_server", "ServerSocket Closed"); } catch (IOException ioe) { handler.error("GenericServer.stop_server", "Could not close socket listener: " + ioe.getMessage()); handler.traceback(ioe); } } this.listener = null; } public InetAddress get_address() { return this.listener.getInetAddress(); } public void set_address(InetAddress new_address) { addr = new_address; } public String get_port() { if (this.listener == null) { handler.debug("GenericServer.get_port", "Port requested when listener is null"); return ""; } return Integer.toString(this.listener.getLocalPort()); } public void set_port(int new_port) { if (this.listener == null) return; this.port = new_port; } public String getdir() { return userdir; } public String setdir(String dir) { userdir = dir; return dir; } public synchronized boolean is_running() { return (this.listener != null && !this.listener.isClosed()); } protected HTTPReply send_date(ArrayList<String> request){ String date_string = ""; if (request.size() > 1 && request.get(1).equals("unixtime")) { long unixtime = System.currentTimeMillis() / 1000L; date_string = Long.toString(unixtime); } else { date_string = (new Date()).toString(); } if (request.get(request.size() - 1).equals("json")) { HashMap<String, String> map = new HashMap<String, String>(); map.put("date", date_string); return JSONReply.fromHashmap(map); } return new HTMLReply(request.get(0), date_string); } protected HTTPReply process_user_request(ArrayList<String> request) throws HTTPError { if(request == null || request.size() < 2) return HTMLReply.invalid_request(); File requested_file = new File(request.get(1)); for(int i = 2;i<request.size();i++) requested_file = new File(requested_file, request.get(i)); String filename = requested_file.getPath(); String err = ""; if (userdir == null) throw new HTTPError("User directory not defined."); UserFile user_file = new UserFile(new File(userdir, filename)); UserFile.FileType filetype = user_file.get_filetype(); BufferedInputStream file = null; try { file = user_file.get_input_stream(); } catch (SecurityException se) { err = "Cannot read" + filename; file = null; handler.debug("GenericSerer.process_user_request", err + "\n" + se.getMessage()); } catch (FileNotFoundException fnfe) { err = "File not found " + filename; file = null; handler.debug("GenericServer.process_user_request", err + "\n" + fnfe.getMessage()); } if (file == null) { return new HTMLReply("File error", err, "HTTP/1.1 401 Permission Denied"); } FileReply retval = new FileReply(); retval.set_file_type(filetype); retval.set_input_stream(file); return retval; } protected HTTPReply process_echo(HTTPRequest client_request, ArrayList<String> request) { String echo = ""; if (request.size() > 1) echo = request.get(1); if (request.get(request.size() - 1).equals("json")) { HashMap<String, String> content = new HashMap<String, String>(); content.put("data", echo); if(client_request.has_post_data()) { HashMap<String, String> post_data = client_request.get_full_post_data(); content.putAll(post_data); } return JSONReply.fromHashmap(content); } else { if(!client_request.has_post_data()) { return new HTMLReply(echo, echo); } else { String post_string = post_data_as_string(client_request); return new HTMLReply(echo, echo + "\nPOST:\n" + post_string); } } } protected HTTPReply process_file(HTTPRequest client_request, ArrayList<String> request) throws HTTPError, IOException { if(!this.has_write_permission ) throw new FileError("File Writing Not Allowed"); handler.info("GenericServer.process_file", "Processing file."); if(!client_request.has_post_data()) throw new HTTPError("/file requires POST data"); String filename = ""; if(request.size() >= 2) { filename = request.get(1); } else { filename = client_request.get_post_data("filename"); if(filename == null) filename = ""; } String header = "\n--- Begin " + filename + " ---\n"; int header_len = header.length(); String footer = "\n--- End " + filename + " ---\n"; int footer_len = footer.length(); String contents = client_request.get_post_data("content"); if(contents == null) contents = ""; if(userdir == null) throw new HTTPError("User directory not specified"); UserFile outfile = new UserFile(new File(userdir, this.outfile_name)); try { handler.info("GenericServer.process_file", "Opening " + outfile.get_absolute_path()); outfile.init_output(); outfile.write(header.getBytes(), 0, header_len); outfile.write(contents.getBytes(), 0, contents.length()); outfile.write(footer.getBytes(), 0, footer_len); } finally { if(outfile != null) { outfile.flush(); outfile.close(); } } String msg = "Wrote " + contents.length() + " bytes to file."; handler.info("GenericServer.process_file", msg); return new HTMLReply("Wrote to file", msg); } public static String post_data_as_string(HTTPRequest client_request) { HashMap<String, String> post_data = client_request.get_full_post_data(); Iterator<String> it = post_data.keySet().iterator(); String post_string = ""; String key; while(it.hasNext()) { key = it.next(); post_string += key + "=" + post_data.get(key) + "\n"; } return post_string; } public void set_write_permission(boolean can_write) { this.has_write_permission = can_write; handler.debug("GenericServer.set_write_permission", "Setting write permission to " + can_write); } public boolean get_write_permission() { return this.has_write_permission; } public void dump_config(OutputStream output) throws FileNotFoundException, IOException { handler.debug("GenericServer.dump_config", "Saving Configuration"); Properties config = new Properties(); // Server Information output.write("#Server Info\n".getBytes()); output.write("#Have Favicon? ".getBytes()); if(get_favicon() == null) output.write("No\n".getBytes()); else output.write("Yes\n".getBytes()); output.write("#Using SSL? ".getBytes()); if(this instanceof SSLServer) output.write("Yes\n".getBytes()); else output.write("No\n".getBytes()); Properties build_info = new BuildInfo().get_build_properties(); if(build_info != null) { handler.debug("GenericServer.dump_config", "Got Build Info"); Set<Entry<Object, Object>> keys = build_info.entrySet(); Iterator<Entry<Object, Object>> it = keys.iterator(); while(it.hasNext()) { Entry<Object, Object> pair = it.next(); String prop_string = "#" + pair.getKey().toString() + ": " + pair.getValue().toString() + "\n"; //String prop_string = "#" + key + ": " + build_info.getProperty(key) + "\n"; output.write(prop_string.getBytes()); } } output.write("#\n".getBytes()); // Properties config.setProperty("address", addr.getHostAddress()); config.setProperty("port", Integer.toString(port)); if(userdir != null) config.setProperty("userdir", userdir); config.setProperty("has_write_permission", Boolean.toString(has_write_permission)); config.store(output, "Server Config"); } public void dump_config() throws FileNotFoundException, IOException { String conf_filename = "server.conf"; dump_config(new FileOutputStream(conf_filename)); } public void load_config() throws FileNotFoundException, IOException { String conf_filename = "server.conf"; Properties config = new Properties(); config.load(new FileInputStream(conf_filename)); String val = config.getProperty("address", addr.getHostAddress()); addr = InetAddress.getByName(val); val = config.getProperty("port", Integer.toString(port)); port = Integer.parseInt(val); userdir = config.getProperty("userdir", userdir); val = config.getProperty("has_write_permission", Boolean.toString(has_write_permission)); has_write_permission = Boolean.parseBoolean(val); handler.debug("GenericServer.load_config", "Loaded configuration from " + conf_filename); } public InputStream get_favicon() { return this.getClass().getResourceAsStream("favicon.ico"); } public static ArrayList<String> get_ip_list() throws SocketException { ArrayList<String> retval = new ArrayList<String>(); for(Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces(); nics.hasMoreElements();) { NetworkInterface nic = nics.nextElement(); for(Enumeration<InetAddress> addrs = nic.getInetAddresses(); addrs.hasMoreElements();) { InetAddress addr = addrs.nextElement(); retval.add(addr.getHostAddress()); } } return retval; } }
true
true
public void run() { boolean has_fatal_error = false; handler.info("GenericServer.run", "Thread Run Called"); while (!Thread.currentThread().isInterrupted() && !has_fatal_error) { try { if (this.listener == null) start_server(); handler.info("GenericServer.run", "Listening on port " + port); Socket socket = listener.accept(); handler.info("GenericServer.run", "Opened socket on port " + port); OutputStream out = socket.getOutputStream(); HTTPRequest request = null; HTTPReply reply = null; try { @SuppressWarnings("resource") // This will be closed with socket.close() BufferedReader input = new BufferedReader(new InputStreamReader( new BoundedInputStream(socket.getInputStream(), UserFile.MAX_OUTFILE_SIZE))); String input_text = input.readLine(); while (input_text != null && !Thread.currentThread().isInterrupted()) { reply = HTMLReply.invalid_request();// Prove me wrong. handler.info("GenericServer.run", "Client Said: " + input_text); String[] request_tokens = input_text.split(" "); int request_data_len = input_text.length(); if(request_data_len > 0 && request_tokens.length < 2) { handler.debug("GenericServer.run", "Invalid Request String Length: " + input_text); } else if (request_tokens[0].equals("GET") || request_tokens[0].equals("POST")) { handler.debug("GenericServer.run", input_text); request = new HTTPRequest(request_tokens[0], request_tokens[1]); } else if(request != null && request_data_len != 0) { try { request.put_request_data(input_text); } catch(InvalidRequestData ird) { handler.error("GenericServer.run", "Invalid Data from Client: " + ird); handler.traceback(ird); } } out.flush(); if (request_data_len == 0) { if(request != null) { handler.info("GenericServer.run", "Received Request"); handler.info("GenericServer.run", request.toString()); } break; } input_text = input.readLine(); if (input_text == "") handler.debug("GenericServer.run", "Empty string"); } try{ if(request != null && request.get_type() == HTTPRequest.RequestType.POST) { String len_as_str = request.get_request_data("Content-Length"); if(len_as_str != null) { try { int post_len = Integer.parseInt(len_as_str); if(post_len >= UserFile.MAX_OUTFILE_SIZE) { String err = "Too much post data sent. Sent: " + post_len; handler.debug("GenericServer.run", err); reply = new HTMLReply("Error", err, HTTPReply.STATUS_FORBIDDEN); continue; } char[] buffer = new char[post_len]; handler.info("GenericServer.run", "Reading " + post_len + " bytes of post data"); input.read(buffer, 0, post_len); String post_data = new String(buffer); handler.info("GenericServer.run", "POST Data: " + post_data); request.put_post_data(post_data); } catch(NumberFormatException nfe) { handler.error("GenericServer.run", "Invalid Content-Length: " + len_as_str); handler.error("GenericServer.run", nfe.getMessage()); handler.traceback(nfe); } } } reply = process_request(request); } catch(HTTPError httperr) { handler.error("GenericServer.run", "HTTP ERROR: " + httperr); handler.traceback(httperr); reply = new HTMLReply("ERROR", "Server Error", HTTPReply.STATUS_ERROR); } } finally { if(reply != null && !socket.isClosed()) { handler.debug("GenericServer.run", "Sending reply"); reply.write(out); } handler.info("GenericServer.run", "Closing socket"); socket.close(); handler.info("GenericServer.run", "Socket closed"); } } catch (SSLException ssle) { handler.error("GenericServer.run", "SSLException: " + ssle.getMessage()); } catch (SocketException se) { if(!se.getMessage().equals("Socket closed") && !se.getMessage().equals("Socket is closed")) { handler.error("GenericServer.run", "Socket closed"); handler.traceback(se); } } catch (IOException ioe) { handler.error("GenericServer.run", "IOException: " + ioe.getMessage()); handler.traceback(ioe); } catch(HTTPError httpe) { handler.error("GenericServer.run", "Server Error"); handler.traceback(httpe); has_fatal_error = true; } }// while not interrupted }
public void run() { boolean has_fatal_error = false; handler.info("GenericServer.run", "Thread Run Called"); while (!Thread.currentThread().isInterrupted() && !has_fatal_error) { try { if (this.listener == null) start_server(); handler.info("GenericServer.run", "Listening on port " + port); Socket socket = listener.accept(); handler.info("GenericServer.run", "Opened socket on port " + port); OutputStream out = socket.getOutputStream(); HTTPRequest request = null; HTTPReply reply = null; try { @SuppressWarnings("resource") // This will be closed with socket.close() BufferedReader input = new BufferedReader(new InputStreamReader( new BoundedInputStream(socket.getInputStream(), UserFile.MAX_OUTFILE_SIZE))); String input_text = input.readLine(); while (input_text != null && !Thread.currentThread().isInterrupted()) { reply = HTMLReply.invalid_request();// Prove me wrong. handler.info("GenericServer.run", "Client Said: " + input_text); String[] request_tokens = input_text.split(" "); int request_data_len = input_text.length(); if(request_data_len > 0 && request_tokens.length < 2) { handler.debug("GenericServer.run", "Invalid Request String Length: " + input_text); } else if (request_tokens[0].equals("GET") || request_tokens[0].equals("POST")) { handler.debug("GenericServer.run", input_text); request = new HTTPRequest(request_tokens[0], request_tokens[1]); } else if(request != null && request_data_len != 0) { try { request.put_request_data(input_text); } catch(InvalidRequestData ird) { handler.error("GenericServer.run", "Invalid Data from Client: " + ird); handler.traceback(ird); } } out.flush(); if (request_data_len == 0) { if(request != null) { handler.info("GenericServer.run", "Received Request"); handler.info("GenericServer.run", request.toString()); } break; } input_text = input.readLine(); if (input_text == "") handler.debug("GenericServer.run", "Empty string"); } try{ if(request != null && request.get_type() == HTTPRequest.RequestType.POST) { String len_as_str = request.get_request_data("Content-Length"); if(len_as_str != null) { try { int post_len = Integer.parseInt(len_as_str); if(post_len >= UserFile.MAX_OUTFILE_SIZE) { String err = "Too much post data sent. Sent: " + post_len; handler.debug("GenericServer.run", err); reply = new HTMLReply("Error", err, HTTPReply.STATUS_FORBIDDEN); continue; } char[] buffer = new char[post_len]; handler.info("GenericServer.run", "Reading " + post_len + " bytes of post data"); input.read(buffer, 0, post_len); String post_data = new String(buffer); handler.info("GenericServer.run", "POST Data: " + post_data); request.put_post_data(post_data); } catch(NumberFormatException nfe) { handler.error("GenericServer.run", "Invalid Content-Length: " + len_as_str); handler.error("GenericServer.run", nfe.getMessage()); handler.traceback(nfe); } } } reply = process_request(request); } catch (EmptyRequest er) { handler.debug("GenericServer.run", "Empty Response"); reply = new HTMLReply("Empty Response", "Empty Response", HTTPReply.STATUS_ERROR); } catch(HTTPError httperr) { handler.error("GenericServer.run", "HTTP ERROR: " + httperr); handler.traceback(httperr); reply = new HTMLReply("ERROR", "Server Error", HTTPReply.STATUS_ERROR); } } finally { if(reply != null && !socket.isClosed()) { handler.debug("GenericServer.run", "Sending reply"); reply.write(out); } handler.info("GenericServer.run", "Closing socket"); socket.close(); handler.info("GenericServer.run", "Socket closed"); } } catch (SSLException ssle) { handler.error("GenericServer.run", "SSLException: " + ssle.getMessage()); } catch (SocketException se) { if(!se.getMessage().equals("Socket closed") && !se.getMessage().equals("Socket is closed")) { handler.error("GenericServer.run", "Socket closed"); handler.traceback(se); } } catch (IOException ioe) { handler.error("GenericServer.run", "IOException: " + ioe.getMessage()); handler.traceback(ioe); } catch(HTTPError httpe) { handler.error("GenericServer.run", "Server Error"); handler.traceback(httpe); has_fatal_error = true; } }// while not interrupted }
diff --git a/cosmo/src/main/java/org/osaf/cosmo/dao/hibernate/StandardQueryCriteriaBuilder.java b/cosmo/src/main/java/org/osaf/cosmo/dao/hibernate/StandardQueryCriteriaBuilder.java index e782b1d67..bdf1a4c08 100644 --- a/cosmo/src/main/java/org/osaf/cosmo/dao/hibernate/StandardQueryCriteriaBuilder.java +++ b/cosmo/src/main/java/org/osaf/cosmo/dao/hibernate/StandardQueryCriteriaBuilder.java @@ -1,106 +1,107 @@ /* * Copyright 2006 Open Source Applications Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.osaf.cosmo.dao.hibernate; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.Map.Entry; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.criterion.Criterion; import org.hibernate.criterion.MatchMode; import org.hibernate.criterion.Order; import org.hibernate.criterion.Restrictions; import org.osaf.cosmo.util.PageCriteria; /** * Interface for building Hibernate query criteria. * * @see Criteria * @see PageCriteria */ public class StandardQueryCriteriaBuilder<SortType extends Enum> implements QueryCriteriaBuilder<SortType> { private Class clazz; /** * Constructs a <code>StandardQueryCriteriaBuilder</code> that * will query objects of the given class. */ public StandardQueryCriteriaBuilder(Class clazz) { this.clazz = clazz; } /** * Returns a <code>Criteria</code> based on the given * <code>PageCriteria</code> that can be used to query the given * <code>Session</code>. */ public Criteria buildQueryCriteria(Session session, PageCriteria<SortType> pageCriteria) { Criteria crit = session.createCriteria(clazz); // If page size is -1, that means get all users if(pageCriteria.getPageSize()>0) { crit.setMaxResults(pageCriteria.getPageSize()); int firstResult = 0; if (pageCriteria.getPageNumber() > 1) firstResult = ((pageCriteria.getPageNumber() - 1) * pageCriteria.getPageSize()); crit.setFirstResult(firstResult); } for (Order order : buildOrders(pageCriteria)) crit.addOrder(order); Criterion orCriterion = null; for (String[] pair: pageCriteria.getOrCriteria()){ if (orCriterion == null){ orCriterion = Restrictions.ilike(pair[0], pair[1], MatchMode.ANYWHERE); } else { orCriterion = Restrictions.or(orCriterion, - Restrictions.ilike(pair[0], pair[1])); + Restrictions.ilike(pair[0], pair[1], + MatchMode.ANYWHERE)); } } if (orCriterion != null) crit.add(orCriterion); return crit; } /** * Returns a <code>List</code> of <code>Order</code> criteria * based on the sorting attributes of the given * <code>PageCriteria</code>. * * This implementation simply adds one ascending or descending * <code>Order</code> as specified by * {@link PageCriteria#isSortAscending()}, sorting on the * attribute named by {@link PageCriteria#getSortTypeString()}. */ protected List<Order> buildOrders(PageCriteria<SortType> pageCriteria) { List<Order> orders = new ArrayList<Order>(); orders.add(pageCriteria.isSortAscending() ? Order.asc(pageCriteria.getSortTypeString()) : Order.desc(pageCriteria.getSortTypeString())); return orders; } }
true
true
public Criteria buildQueryCriteria(Session session, PageCriteria<SortType> pageCriteria) { Criteria crit = session.createCriteria(clazz); // If page size is -1, that means get all users if(pageCriteria.getPageSize()>0) { crit.setMaxResults(pageCriteria.getPageSize()); int firstResult = 0; if (pageCriteria.getPageNumber() > 1) firstResult = ((pageCriteria.getPageNumber() - 1) * pageCriteria.getPageSize()); crit.setFirstResult(firstResult); } for (Order order : buildOrders(pageCriteria)) crit.addOrder(order); Criterion orCriterion = null; for (String[] pair: pageCriteria.getOrCriteria()){ if (orCriterion == null){ orCriterion = Restrictions.ilike(pair[0], pair[1], MatchMode.ANYWHERE); } else { orCriterion = Restrictions.or(orCriterion, Restrictions.ilike(pair[0], pair[1])); } } if (orCriterion != null) crit.add(orCriterion); return crit; }
public Criteria buildQueryCriteria(Session session, PageCriteria<SortType> pageCriteria) { Criteria crit = session.createCriteria(clazz); // If page size is -1, that means get all users if(pageCriteria.getPageSize()>0) { crit.setMaxResults(pageCriteria.getPageSize()); int firstResult = 0; if (pageCriteria.getPageNumber() > 1) firstResult = ((pageCriteria.getPageNumber() - 1) * pageCriteria.getPageSize()); crit.setFirstResult(firstResult); } for (Order order : buildOrders(pageCriteria)) crit.addOrder(order); Criterion orCriterion = null; for (String[] pair: pageCriteria.getOrCriteria()){ if (orCriterion == null){ orCriterion = Restrictions.ilike(pair[0], pair[1], MatchMode.ANYWHERE); } else { orCriterion = Restrictions.or(orCriterion, Restrictions.ilike(pair[0], pair[1], MatchMode.ANYWHERE)); } } if (orCriterion != null) crit.add(orCriterion); return crit; }
diff --git a/src/main/java/ditl/graphs/NS2Movement.java b/src/main/java/ditl/graphs/NS2Movement.java index 9bf6a0c..3c033e4 100644 --- a/src/main/java/ditl/graphs/NS2Movement.java +++ b/src/main/java/ditl/graphs/NS2Movement.java @@ -1,150 +1,150 @@ /******************************************************************************* * This file is part of DITL. * * * * Copyright (C) 2011-2012 John Whitbeck <[email protected]> * * * * DITL is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * DITL is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * *******************************************************************************/ package ditl.graphs; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.util.Collection; import java.util.HashMap; import java.util.Map; import ditl.Bus; import ditl.IdGenerator; import ditl.Listener; import ditl.Matcher; import ditl.StatefulReader; import ditl.StatefulWriter; import ditl.Trace; import ditl.Units; public class NS2Movement { public static void fromNS2(MovementTrace movement, InputStream in, Long maxTime, double timeMul, long ticsPerSecond, long offset, final boolean fixPauseTimes, IdGenerator idGen) throws IOException { final StatefulWriter<MovementEvent, Movement> movementWriter = movement.getWriter(); final Map<Integer, Movement> positions = new HashMap<Integer, Movement>(); final BufferedReader br = new BufferedReader(new InputStreamReader(in)); final Bus<MovementEvent> buffer = new Bus<MovementEvent>(); String line; long last_time = Long.MIN_VALUE; while ((line = br.readLine()) != null) if (!line.isEmpty()) { Integer id; String id_str; double s; Movement m; long time; final String[] elems = line.split("\\p{Blank}+"); if (line.startsWith("$node")) { id_str = elems[0].split("\\(|\\)")[1]; id = idGen.getInternalId(id_str); final double c = Double.parseDouble(elems[3]); m = positions.get(id); if (m == null) { m = new Movement(id, new Point(0, 0)); positions.put(id, m); } if (elems[2].equals("X_")) m.x = c; else if (elems[2].equals("Y_")) m.y = c; } else if (line.startsWith("$ns")) { time = (long) (Double.parseDouble(elems[2]) * timeMul) + offset; if (time > last_time) last_time = time; id_str = elems[3].split("\\(|\\)")[1]; id = idGen.getInternalId(id_str); final Point dest = new Point(Double.parseDouble(elems[5]), Double.parseDouble(elems[6])); - s = Double.parseDouble(elems[7].substring(0, elems[7].length() - 2)) / timeMul; + s = Double.parseDouble(elems[7].substring(0, elems[7].length() - 1)) / timeMul; buffer.queue(time, new MovementEvent(id, s, dest)); } } br.close(); movementWriter.setInitState(offset, positions.values()); buffer.addListener(new Listener<MovementEvent>() { @Override public void handle(long time, Collection<MovementEvent> events) throws IOException { for (final MovementEvent mev : events) { final Movement m = positions.get(mev.id); // current // movement m.handleEvent(time, mev); movementWriter.removeFromQueueAfterTime(time, new Matcher<MovementEvent>() { @Override public boolean matches(MovementEvent item) { return (item.id == mev.id); } }); movementWriter.queue(time, mev); if (fixPauseTimes) movementWriter.queue(m.arrival, new MovementEvent(mev.id, 0, mev.dest)); // queue // the // waiting // time // as // well } movementWriter.flush(time); } }); buffer.flush(); last_time = (maxTime != null) ? maxTime : last_time; movementWriter.setProperty(Trace.maxTimeKey, last_time); movementWriter.setProperty(Trace.timeUnitKey, Units.toTimeUnit(ticsPerSecond)); idGen.writeTraceInfo(movementWriter); movementWriter.close(); } public static void toNS2(MovementTrace movement, OutputStream out, double timeMul) throws IOException { final StatefulReader<MovementEvent, Movement> movementReader = movement.getReader(); final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out)); movementReader.seek(movement.minTime()); for (final Movement mv : movementReader.referenceState()) bw.write(mv.ns2String()); while (movementReader.hasNext()) for (final MovementEvent mev : movementReader.next()) switch (mev.type) { case NEW_DEST: bw.write(mev.ns2String(movementReader.time(), timeMul)); break; default: System.err.println("IN and OUT movement events are not supported by NS2"); } bw.close(); movementReader.close(); } }
true
true
public static void fromNS2(MovementTrace movement, InputStream in, Long maxTime, double timeMul, long ticsPerSecond, long offset, final boolean fixPauseTimes, IdGenerator idGen) throws IOException { final StatefulWriter<MovementEvent, Movement> movementWriter = movement.getWriter(); final Map<Integer, Movement> positions = new HashMap<Integer, Movement>(); final BufferedReader br = new BufferedReader(new InputStreamReader(in)); final Bus<MovementEvent> buffer = new Bus<MovementEvent>(); String line; long last_time = Long.MIN_VALUE; while ((line = br.readLine()) != null) if (!line.isEmpty()) { Integer id; String id_str; double s; Movement m; long time; final String[] elems = line.split("\\p{Blank}+"); if (line.startsWith("$node")) { id_str = elems[0].split("\\(|\\)")[1]; id = idGen.getInternalId(id_str); final double c = Double.parseDouble(elems[3]); m = positions.get(id); if (m == null) { m = new Movement(id, new Point(0, 0)); positions.put(id, m); } if (elems[2].equals("X_")) m.x = c; else if (elems[2].equals("Y_")) m.y = c; } else if (line.startsWith("$ns")) { time = (long) (Double.parseDouble(elems[2]) * timeMul) + offset; if (time > last_time) last_time = time; id_str = elems[3].split("\\(|\\)")[1]; id = idGen.getInternalId(id_str); final Point dest = new Point(Double.parseDouble(elems[5]), Double.parseDouble(elems[6])); s = Double.parseDouble(elems[7].substring(0, elems[7].length() - 2)) / timeMul; buffer.queue(time, new MovementEvent(id, s, dest)); } } br.close(); movementWriter.setInitState(offset, positions.values()); buffer.addListener(new Listener<MovementEvent>() { @Override public void handle(long time, Collection<MovementEvent> events) throws IOException { for (final MovementEvent mev : events) { final Movement m = positions.get(mev.id); // current // movement m.handleEvent(time, mev); movementWriter.removeFromQueueAfterTime(time, new Matcher<MovementEvent>() { @Override public boolean matches(MovementEvent item) { return (item.id == mev.id); } }); movementWriter.queue(time, mev); if (fixPauseTimes) movementWriter.queue(m.arrival, new MovementEvent(mev.id, 0, mev.dest)); // queue // the // waiting // time // as // well } movementWriter.flush(time); } }); buffer.flush(); last_time = (maxTime != null) ? maxTime : last_time; movementWriter.setProperty(Trace.maxTimeKey, last_time); movementWriter.setProperty(Trace.timeUnitKey, Units.toTimeUnit(ticsPerSecond)); idGen.writeTraceInfo(movementWriter); movementWriter.close(); }
public static void fromNS2(MovementTrace movement, InputStream in, Long maxTime, double timeMul, long ticsPerSecond, long offset, final boolean fixPauseTimes, IdGenerator idGen) throws IOException { final StatefulWriter<MovementEvent, Movement> movementWriter = movement.getWriter(); final Map<Integer, Movement> positions = new HashMap<Integer, Movement>(); final BufferedReader br = new BufferedReader(new InputStreamReader(in)); final Bus<MovementEvent> buffer = new Bus<MovementEvent>(); String line; long last_time = Long.MIN_VALUE; while ((line = br.readLine()) != null) if (!line.isEmpty()) { Integer id; String id_str; double s; Movement m; long time; final String[] elems = line.split("\\p{Blank}+"); if (line.startsWith("$node")) { id_str = elems[0].split("\\(|\\)")[1]; id = idGen.getInternalId(id_str); final double c = Double.parseDouble(elems[3]); m = positions.get(id); if (m == null) { m = new Movement(id, new Point(0, 0)); positions.put(id, m); } if (elems[2].equals("X_")) m.x = c; else if (elems[2].equals("Y_")) m.y = c; } else if (line.startsWith("$ns")) { time = (long) (Double.parseDouble(elems[2]) * timeMul) + offset; if (time > last_time) last_time = time; id_str = elems[3].split("\\(|\\)")[1]; id = idGen.getInternalId(id_str); final Point dest = new Point(Double.parseDouble(elems[5]), Double.parseDouble(elems[6])); s = Double.parseDouble(elems[7].substring(0, elems[7].length() - 1)) / timeMul; buffer.queue(time, new MovementEvent(id, s, dest)); } } br.close(); movementWriter.setInitState(offset, positions.values()); buffer.addListener(new Listener<MovementEvent>() { @Override public void handle(long time, Collection<MovementEvent> events) throws IOException { for (final MovementEvent mev : events) { final Movement m = positions.get(mev.id); // current // movement m.handleEvent(time, mev); movementWriter.removeFromQueueAfterTime(time, new Matcher<MovementEvent>() { @Override public boolean matches(MovementEvent item) { return (item.id == mev.id); } }); movementWriter.queue(time, mev); if (fixPauseTimes) movementWriter.queue(m.arrival, new MovementEvent(mev.id, 0, mev.dest)); // queue // the // waiting // time // as // well } movementWriter.flush(time); } }); buffer.flush(); last_time = (maxTime != null) ? maxTime : last_time; movementWriter.setProperty(Trace.maxTimeKey, last_time); movementWriter.setProperty(Trace.timeUnitKey, Units.toTimeUnit(ticsPerSecond)); idGen.writeTraceInfo(movementWriter); movementWriter.close(); }
diff --git a/src/main/java/com/dianping/wizard/widget/concurrent/Executor.java b/src/main/java/com/dianping/wizard/widget/concurrent/Executor.java index 2c09a23..4927449 100644 --- a/src/main/java/com/dianping/wizard/widget/concurrent/Executor.java +++ b/src/main/java/com/dianping/wizard/widget/concurrent/Executor.java @@ -1,68 +1,68 @@ package com.dianping.wizard.widget.concurrent; import com.dianping.wizard.config.Configuration; import org.apache.log4j.Logger; import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * @author ltebean */ public class Executor { private ThreadPoolExecutor executorService; private Status status; private Logger logger = Logger.getLogger(Executor.class); enum Status { ALIVE, SHUTDOWN }; private Executor() { init(); } private static final Executor instance= new Executor(); public static ExecutorService getInstance(){ return instance.executorService; } public void init() { int corePoolSize= Configuration.get("concurrent.threadPool.corePoolSize",50,Integer.class); int maximumPoolSize= Configuration.get("concurrent.threadPool.maximumPoolSize",50,Integer.class); - int keepAliveTime= Configuration.get("concurrent.threadPool.keepAliveTime",00,Integer.class); - int blockingQueueCapacity= Configuration.get("concurrent.threadPool.blockingQueueCapacity",500,Integer.class); + int keepAliveTime= Configuration.get("concurrent.threadPool.keepAliveTime",0,Integer.class); + int blockingQueueCapacity= Configuration.get("concurrent.threadPool.blockingQueueCapacity",1000,Integer.class); if (executorService == null) { executorService = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(blockingQueueCapacity), new ThreadPoolExecutor.CallerRunsPolicy()); logger.info("executorService has been initialized"); // adds a shutdown hook to shut down the executorService Thread shutdownHook = new Thread() { @Override public void run() { synchronized (this) { if (status == Status.ALIVE) { executorService.shutdown(); status = Status.SHUTDOWN; logger.info("excecutorService has been shut down"); } } } }; Runtime.getRuntime().addShutdownHook(shutdownHook); logger.info("successfully add shutdown hook"); } } }
true
true
public void init() { int corePoolSize= Configuration.get("concurrent.threadPool.corePoolSize",50,Integer.class); int maximumPoolSize= Configuration.get("concurrent.threadPool.maximumPoolSize",50,Integer.class); int keepAliveTime= Configuration.get("concurrent.threadPool.keepAliveTime",00,Integer.class); int blockingQueueCapacity= Configuration.get("concurrent.threadPool.blockingQueueCapacity",500,Integer.class); if (executorService == null) { executorService = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(blockingQueueCapacity), new ThreadPoolExecutor.CallerRunsPolicy()); logger.info("executorService has been initialized"); // adds a shutdown hook to shut down the executorService Thread shutdownHook = new Thread() { @Override public void run() { synchronized (this) { if (status == Status.ALIVE) { executorService.shutdown(); status = Status.SHUTDOWN; logger.info("excecutorService has been shut down"); } } } }; Runtime.getRuntime().addShutdownHook(shutdownHook); logger.info("successfully add shutdown hook"); } }
public void init() { int corePoolSize= Configuration.get("concurrent.threadPool.corePoolSize",50,Integer.class); int maximumPoolSize= Configuration.get("concurrent.threadPool.maximumPoolSize",50,Integer.class); int keepAliveTime= Configuration.get("concurrent.threadPool.keepAliveTime",0,Integer.class); int blockingQueueCapacity= Configuration.get("concurrent.threadPool.blockingQueueCapacity",1000,Integer.class); if (executorService == null) { executorService = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(blockingQueueCapacity), new ThreadPoolExecutor.CallerRunsPolicy()); logger.info("executorService has been initialized"); // adds a shutdown hook to shut down the executorService Thread shutdownHook = new Thread() { @Override public void run() { synchronized (this) { if (status == Status.ALIVE) { executorService.shutdown(); status = Status.SHUTDOWN; logger.info("excecutorService has been shut down"); } } } }; Runtime.getRuntime().addShutdownHook(shutdownHook); logger.info("successfully add shutdown hook"); } }
diff --git a/src/com/jme/image/Texture.java b/src/com/jme/image/Texture.java index 878e764e6..42747e13f 100644 --- a/src/com/jme/image/Texture.java +++ b/src/com/jme/image/Texture.java @@ -1,1598 +1,1600 @@ /* * Copyright (c) 2003-2009 jMonkeyEngine * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of 'jMonkeyEngine' nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.jme.image; import java.io.IOException; import com.jme.math.FastMath; import com.jme.math.Matrix4f; import com.jme.math.Quaternion; import com.jme.math.Vector3f; import com.jme.renderer.ColorRGBA; import com.jme.util.TextureKey; import com.jme.util.TextureManager; import com.jme.util.export.InputCapsule; import com.jme.util.export.JMEExporter; import com.jme.util.export.JMEImporter; import com.jme.util.export.OutputCapsule; import com.jme.util.export.Savable; /** * <code>Texture</code> defines a texture object to be used to display an * image on a piece of geometry. The image to be displayed is defined by the * <code>Image</code> class. All attributes required for texture mapping are * contained within this class. This includes mipmapping if desired, * magnificationFilter options, apply options and correction options. Default * values are as follows: minificationFilter - NearestNeighborNoMipMaps, * magnificationFilter - NearestNeighbor, wrap - EdgeClamp on S,T and R, apply - * Modulate, enivoronment - None. * * @see com.jme.image.Image * @author Mark Powell * @author Joshua Slack * @version $Id$ */ public abstract class Texture implements Savable { private static final long serialVersionUID = -3642148179543729674L; public static boolean DEFAULT_STORE_TEXTURE = false; public enum Type { /** * One dimensional texture. (basically a line) */ OneDimensional, /** * Two dimensional texture (default). A rectangle. */ TwoDimensional, /** * Three dimensional texture. (A cube) */ ThreeDimensional, /** * A set of 6 TwoDimensional textures arranged as faces of a cube facing * inwards. */ CubeMap; } public enum MinificationFilter { /** * Nearest neighbor interpolation is the fastest and crudest filtering * method - it simply uses the color of the texel closest to the pixel * center for the pixel color. While fast, this results in aliasing and * shimmering during minification. (GL equivalent: GL_NEAREST) */ NearestNeighborNoMipMaps(false), /** * In this method the four nearest texels to the pixel center are * sampled (at texture level 0), and their colors are combined by * weighted averages. Though smoother, without mipmaps it suffers the * same aliasing and shimmering problems as nearest * NearestNeighborNoMipMaps. (GL equivalent: GL_LINEAR) */ BilinearNoMipMaps(false), /** * Same as NearestNeighborNoMipMaps except that instead of using samples * from texture level 0, the closest mipmap level is chosen based on * distance. This reduces the aliasing and shimmering significantly, but * does not help with blockiness. (GL equivalent: * GL_NEAREST_MIPMAP_NEAREST) */ NearestNeighborNearestMipMap(true), /** * Same as BilinearNoMipMaps except that instead of using samples from * texture level 0, the closest mipmap level is chosen based on * distance. By using mipmapping we avoid the aliasing and shimmering * problems of BilinearNoMipMaps. (GL equivalent: * GL_LINEAR_MIPMAP_NEAREST) */ BilinearNearestMipMap(true), /** * Similar to NearestNeighborNoMipMaps except that instead of using * samples from texture level 0, a sample is chosen from each of the * closest (by distance) two mipmap levels. A weighted average of these * two samples is returned. (GL equivalent: GL_NEAREST_MIPMAP_LINEAR) */ NearestNeighborLinearMipMap(true), /** * Trilinear filtering is a remedy to a common artifact seen in * mipmapped bilinearly filtered images: an abrupt and very noticeable * change in quality at boundaries where the renderer switches from one * mipmap level to the next. Trilinear filtering solves this by doing a * texture lookup and bilinear filtering on the two closest mipmap * levels (one higher and one lower quality), and then linearly * interpolating the results. This results in a smooth degradation of * texture quality as distance from the viewer increases, rather than a * series of sudden drops. Of course, closer than Level 0 there is only * one mipmap level available, and the algorithm reverts to bilinear * filtering (GL equivalent: GL_LINEAR_MIPMAP_LINEAR) */ Trilinear(true); private boolean usesMipMapLevels; private MinificationFilter(boolean usesMipMapLevels) { this.usesMipMapLevels = usesMipMapLevels; } public boolean usesMipMapLevels() { return usesMipMapLevels; } } public enum MagnificationFilter { /** * Nearest neighbor interpolation is the fastest and crudest filtering * mode - it simply uses the color of the texel closest to the pixel * center for the pixel color. While fast, this results in texture * 'blockiness' during magnification. (GL equivalent: GL_NEAREST) */ NearestNeighbor, /** * In this mode the four nearest texels to the pixel center are sampled * (at the closest mipmap level), and their colors are combined by * weighted average according to distance. This removes the 'blockiness' * seen during magnification, as there is now a smooth gradient of color * change from one texel to the next, instead of an abrupt jump as the * pixel center crosses the texel boundary. (GL equivalent: GL_LINEAR) */ Bilinear; } public enum WrapMode { /** * Only the fractional portion of the coordinate is considered. */ Repeat, /** * Only the fractional portion of the coordinate is considered, but if * the integer portion is odd, we'll use 1 - the fractional portion. * (Introduced around OpenGL1.4) Falls back on Repeat if not supported. */ MirroredRepeat, /** * coordinate will be clamped to [0,1] */ Clamp, /** * mirrors and clamps the texture coordinate, where mirroring and * clamping a value f computes: * <code>mirrorClamp(f) = min(1, max(1/(2*N), * abs(f)))</code> where N * is the size of the one-, two-, or three-dimensional texture image in * the direction of wrapping. (Introduced after OpenGL1.4) Falls back on * Clamp if not supported. */ MirrorClamp, /** * coordinate will be clamped to the range [-1/(2N), 1 + 1/(2N)] where N * is the size of the texture in the direction of clamping. Falls back * on Clamp if not supported. */ BorderClamp, /** * Wrap mode MIRROR_CLAMP_TO_BORDER_EXT mirrors and clamps to border the * texture coordinate, where mirroring and clamping to border a value f * computes: * <code>mirrorClampToBorder(f) = min(1+1/(2*N), max(1/(2*N), abs(f)))</code> * where N is the size of the one-, two-, or three-dimensional texture * image in the direction of wrapping." (Introduced after OpenGL1.4) * Falls back on BorderClamp if not supported. */ MirrorBorderClamp, /** * coordinate will be clamped to the range [1/(2N), 1 - 1/(2N)] where N * is the size of the texture in the direction of clamping. Falls back * on Clamp if not supported. */ EdgeClamp, /** * mirrors and clamps to edge the texture coordinate, where mirroring * and clamping to edge a value f computes: * <code>mirrorClampToEdge(f) = min(1-1/(2*N), max(1/(2*N), abs(f)))</code> * where N is the size of the one-, two-, or three-dimensional texture * image in the direction of wrapping. (Introduced after OpenGL1.4) * Falls back on EdgeClamp if not supported. */ MirrorEdgeClamp; } public enum WrapAxis { /** * S wrapping (u or "horizontal" wrap) */ S, /** * T wrapping (v or "vertical" wrap) */ T, /** * R wrapping (w or "depth" wrap) */ R; } public enum ApplyMode { /** * Apply modifier that replaces the previous pixel color with the * texture color. */ Replace, /** * Apply modifier that replaces the color values of the pixel but makes * use of the alpha values. */ Decal, /** * Apply modifier multiples the color of the pixel with the texture * color. */ Modulate, /** * Apply modifier that interpolates the color of the pixel with a blend * color using the texture color, such that the final color value is Cv = * (1 - Ct) * Cf + BlendColor * Ct Where Ct is the color of the texture * and Cf is the initial pixel color. */ Blend, /** * Apply modifier combines two textures based on the combine parameters * set on this texture. */ Combine, /** * Apply modifier adds two textures. */ Add; } public enum EnvironmentalMapMode { /** * Use texture coordinates as they are. (Do not do texture coordinate * generation.) */ None, /** * TODO: add documentation */ EyeLinear, /** * TODO: add documentation */ ObjectLinear, /** * TODO: add documentation */ SphereMap, /** * TODO: add documentation */ NormalMap, /** * TODO: add documentation */ ReflectionMap; } public enum CombinerFunctionRGB { /** Arg0 */ Replace, /** Arg0 * Arg1 */ Modulate, /** Arg0 + Arg1 */ Add, /** Arg0 + Arg1 - 0.5 */ AddSigned, /** Arg0 * Arg2 + Arg1 * (1 - Arg2) */ Interpolate, /** Arg0 - Arg1 */ Subtract, /** * 4 * ((Arg0r - 0.5) * (Arg1r - 0.5) + (Arg0g - 0.5) * (Arg1g - 0.5) + * (Arg0b - 0.5) * (Arg1b - 0.5)) [ result placed in R,G,B ] */ Dot3RGB, /** * 4 * ((Arg0r - 0.5) * (Arg1r - 0.5) + (Arg0g - 0.5) * (Arg1g - 0.5) + * (Arg0b - 0.5) * (Arg1b - 0.5)) [ result placed in R,G,B,A ] */ Dot3RGBA; } public enum CombinerFunctionAlpha { /** Arg0 */ Replace, /** Arg0 * Arg1 */ Modulate, /** Arg0 + Arg1 */ Add, /** Arg0 + Arg1 - 0.5 */ AddSigned, /** Arg0 * Arg2 + Arg1 * (1 - Arg2) */ Interpolate, /** Arg0 - Arg1 */ Subtract; } public enum CombinerSource { /** * The incoming fragment color from the previous texture unit. When used * on texture unit 0, this is the same as using PrimaryColor. */ Previous, /** The blend color set on this texture. */ Constant, /** The incoming fragment color before any texturing is applied. */ PrimaryColor, /** The current texture unit's bound texture. */ CurrentTexture, /** The texture bound on texture unit 0. */ TextureUnit0, /** The texture bound on texture unit 1. */ TextureUnit1, /** The texture bound on texture unit 2. */ TextureUnit2, /** The texture bound on texture unit 3. */ TextureUnit3, /** The texture bound on texture unit 4. */ TextureUnit4, /** The texture bound on texture unit 5. */ TextureUnit5, /** The texture bound on texture unit 6. */ TextureUnit6, /** The texture bound on texture unit 7. */ TextureUnit7, /** The texture bound on texture unit 8. */ TextureUnit8, /** The texture bound on texture unit 9. */ TextureUnit9, /** The texture bound on texture unit 10. */ TextureUnit10, /** The texture bound on texture unit 11. */ TextureUnit11, /** The texture bound on texture unit 12. */ TextureUnit12, /** The texture bound on texture unit 13. */ TextureUnit13, /** The texture bound on texture unit 14. */ TextureUnit14, /** The texture bound on texture unit 15. */ TextureUnit15, /** The texture bound on texture unit 16. */ TextureUnit16, /** The texture bound on texture unit 17. */ TextureUnit17, /** The texture bound on texture unit 18. */ TextureUnit18, /** The texture bound on texture unit 19. */ TextureUnit19, /** The texture bound on texture unit 20. */ TextureUnit20, /** The texture bound on texture unit 21. */ TextureUnit21, /** The texture bound on texture unit 22. */ TextureUnit22, /** The texture bound on texture unit 23. */ TextureUnit23, /** The texture bound on texture unit 24. */ TextureUnit24, /** The texture bound on texture unit 25. */ TextureUnit25, /** The texture bound on texture unit 26. */ TextureUnit26, /** The texture bound on texture unit 27. */ TextureUnit27, /** The texture bound on texture unit 28. */ TextureUnit28, /** The texture bound on texture unit 29. */ TextureUnit29, /** The texture bound on texture unit 30. */ TextureUnit30, /** The texture bound on texture unit 31. */ TextureUnit31; } public enum CombinerOperandRGB { SourceColor, OneMinusSourceColor, SourceAlpha, OneMinusSourceAlpha; } public enum CombinerOperandAlpha { SourceAlpha, OneMinusSourceAlpha; } public enum CombinerScale { /** No scale (1.0x) */ One(1.0f), /** 2.0x */ Two(2.0f), /** 4.0x */ Four(4.0f); private float scale; private CombinerScale(float scale) { this.scale = scale; } public float floatValue() { return scale; } } /** * When doing RenderToTexture operations with this texture, this value * indicates what content to render into this texture. */ public enum RenderToTextureType { /** *Each element is an RGB triple. OpenGL converts it to fixed-point or floating-point and assembles it into an RGBA element by attaching 1 for alpha. *Each component is then clamped to the range [0,1]. */ RGB, /** * Each element contains all four components. OpenGL converts it to fixed-point or floating-point. * Each component is then clamped to the range [0,1]. */ RGBA, /** * Each element is a single depth component clamped to the range [0, 1]. * Each component is then clamped to the range [0,1]. */ Depth, /** * Each element is a luminance/alpha pair. OpenGL converts it to fixed-point or floating point, then assembles it into an RGBA element by replicating the luminance value three times for red, green, and blue. * Each component is then clamped to the range [0,1]. */ Alpha, /** * Each element is a single luminance value. OpenGL converts it to fixed-point or floating-point, then assembles it into an RGBA element by replicating the luminance value three times for red, green, and blue and attaching 1 for alpha. * Each component is then clamped to the range [0,1]. */ Luminance, /** * Each element is a luminance/alpha pair. OpenGL converts it to fixed-point or floating point, then assembles it into an RGBA element by replicating the luminance value three times for red, green, and blue. * Each component is then clamped to the range [0,1]. */ LuminanceAlpha, /** * Each element has both luminance (grayness) and alpha (transparency) information, but the luminance and alpha values at every texel are the same. * Each component is then clamped to the range [0,1]. */ Intensity, Alpha4, Alpha8, Alpha12, Alpha16, Depth16, Depth24, Depth32, Luminance4, Luminance8, Luminance12, Luminance16, Luminance4Alpha4,Luminance6Alpha2, Luminance8Alpha8,Luminance12Alpha4, Luminance12Alpha12, Luminance16Alpha16, Intensity4, Intensity8, Intensity12, Intensity16, R3_G3_B2, RGB4, RGB5, RGB8, RGB10, RGB12, RGB16, RGBA2, RGBA4, RGB5_A1, RGBA8, RGB10_A2, RGBA12, RGBA16, //floats RGBA32F, RGB32F, Alpha32F, Intensity32F, Luminance32F, LuminanceAlpha32F, RGBA16F, RGB16F, Alpha16F, Intensity16F, Luminance16F, LuminanceAlpha16F; } /** * The shadowing texture compare mode */ public enum DepthTextureCompareMode { /** Perform no shadow based comparsion */ None, /** Perform a comparison between source depth and texture depth */ RtoTexture, } /** * The shadowing texture compare function */ public enum DepthTextureCompareFunc { /** Outputs if the source depth is less than the texture depth */ LessThanEqual, /** Outputs if the source depth is greater than the texture depth */ GreaterThanEqual } /** * The type of depth texture translation to output */ public enum DepthTextureMode { /** Output luminance values based on the depth comparison */ Luminance, /** Output alpha values based on the depth comparison */ Alpha, /** Output intensity values based on the depth comparison */ Intensity } // Optional String to point to where this texture is located private String imageLocation = null; // texture attributes. private Image image = null; private ColorRGBA blendColor = null; // If null, black (gl's default) // will be used private ColorRGBA borderColor = null; // If null, black (gl's default) // will be used private Vector3f translation = null; private Vector3f scale = null; private Quaternion rotation = null; private Matrix4f matrix = null; private float anisotropicFilterPercent = 0.0f; private transient int textureId; private ApplyMode apply = ApplyMode.Modulate; private MinificationFilter minificationFilter = MinificationFilter.NearestNeighborNoMipMaps; private MagnificationFilter magnificationFilter = MagnificationFilter.NearestNeighbor; private EnvironmentalMapMode envMapMode = EnvironmentalMapMode.None; private RenderToTextureType rttSource = RenderToTextureType.RGBA; private int memReq = 0; private boolean hasBorder = false; // The following will only used if apply is set to ApplyMode.Combine private CombinerFunctionRGB combineFuncRGB = CombinerFunctionRGB.Modulate; private CombinerSource combineSrc0RGB = CombinerSource.CurrentTexture; private CombinerSource combineSrc1RGB = CombinerSource.Previous; private CombinerSource combineSrc2RGB = CombinerSource.Constant; private CombinerOperandRGB combineOp0RGB = CombinerOperandRGB.SourceColor; private CombinerOperandRGB combineOp1RGB = CombinerOperandRGB.SourceColor; private CombinerOperandRGB combineOp2RGB = CombinerOperandRGB.SourceAlpha; private CombinerScale combineScaleRGB = CombinerScale.One; private CombinerFunctionAlpha combineFuncAlpha = CombinerFunctionAlpha.Modulate; private CombinerSource combineSrc0Alpha = CombinerSource.CurrentTexture; private CombinerSource combineSrc1Alpha = CombinerSource.Previous; private CombinerSource combineSrc2Alpha = CombinerSource.Constant; private CombinerOperandAlpha combineOp0Alpha = CombinerOperandAlpha.SourceAlpha; private CombinerOperandAlpha combineOp1Alpha = CombinerOperandAlpha.SourceAlpha; private CombinerOperandAlpha combineOp2Alpha = CombinerOperandAlpha.SourceAlpha; private CombinerScale combineScaleAlpha = CombinerScale.One; private TextureKey key = null; private transient boolean storeTexture = DEFAULT_STORE_TEXTURE; private DepthTextureCompareMode depthCompareMode = DepthTextureCompareMode.None; private DepthTextureCompareFunc depthCompareFunc = DepthTextureCompareFunc.GreaterThanEqual; private DepthTextureMode depthMode = DepthTextureMode.Intensity; /** * Constructor instantiates a new <code>Texture</code> object with default * attributes. */ public Texture() { memReq = 0; } /** * <code>setBlendColor</code> sets a color that is used with * CombinerSource.Constant * * @param color * the new blend color - or null for the default (black) */ public void setBlendColor(ColorRGBA color) { this.blendColor = color != null ? color.clone() : null; } /** * <code>setBorderColor</code> sets the color used when texture operations * encounter the border of a texture. * * @param color * the new border color - or null for the default (black) */ public void setBorderColor(ColorRGBA color) { this.borderColor = color != null ? color.clone() : null; } /** * @return the MinificationFilterMode of this texture. */ public MinificationFilter getMinificationFilter() { return minificationFilter; } /** * @param minificationFilter * the new MinificationFilterMode for this texture. * @throws IllegalArgumentException * if minificationFilter is null */ public void setMinificationFilter(MinificationFilter minificationFilter) { if (minificationFilter == null) { throw new IllegalArgumentException( "minificationFilter can not be null."); } this.minificationFilter = minificationFilter; } /** * @return the MagnificationFilterMode of this texture. */ public MagnificationFilter getMagnificationFilter() { return magnificationFilter; } /** * @param magnificationFilter * the new MagnificationFilter for this texture. * @throws IllegalArgumentException * if magnificationFilter is null */ public void setMagnificationFilter(MagnificationFilter magnificationFilter) { if (magnificationFilter == null) { throw new IllegalArgumentException( "magnificationFilter can not be null."); } this.magnificationFilter = magnificationFilter; } /** * <code>setApply</code> sets the apply mode for this texture. * * @param apply * the apply mode for this texture. * @throws IllegalArgumentException * if apply is null */ public void setApply(ApplyMode apply) { if (apply == null) { throw new IllegalArgumentException("apply can not be null."); } this.apply = apply; } /** * <code>setImage</code> sets the image object that defines the texture. * * @param image * the image that defines the texture. */ public void setImage(Image image) { this.image = image; updateMemoryReq(); } /** * <code>getTextureId</code> returns the texture id of this texture. This * id is required to be unique to any other texture objects running in the * same JVM. However, no guarantees are made that it will be unique, and as * such, the user is responsible for this. * * @return the id of the texture. */ public int getTextureId() { return textureId; } /** * <code>setTextureId</code> sets the texture id for this texture. Zero * means no id is set. * * @param textureId * the texture id of this texture. */ public void setTextureId(int textureId) { this.textureId = textureId; } /** * <code>getImage</code> returns the image data that makes up this * texture. If no image data has been set, this will return null. * * @return the image data that makes up the texture. */ public Image getImage() { return image; } /** * <code>getApply</code> returns the apply mode for the texture. * * @return the apply mode of the texture. */ public ApplyMode getApply() { return apply; } /** * <code>getBlendColor</code> returns the color set to be used with * CombinerSource.Constant for this texture (as applicable) If null, black * is assumed. * * @return the blend color. */ public ColorRGBA getBlendColor() { return blendColor; } /** * <code>getBorderColor</code> returns the color to be used for border * operations. If null, black is assumed. * * @return the border color. */ public ColorRGBA getBorderColor() { return borderColor; } /** * <code>setWrap</code> sets the wrap mode of this texture for a * particular axis. * * @param axis * the texture axis to define a wrapmode on. * @param mode * the wrap mode for the given axis of the texture. * @throws IllegalArgumentException * if axis or mode are null or invalid for this type of texture */ public abstract void setWrap(WrapAxis axis, WrapMode mode); /** * <code>setWrap</code> sets the wrap mode of this texture for all axis. * * @param mode * the wrap mode for the given axis of the texture. * @throws IllegalArgumentException * if mode is null or invalid for this type of texture */ public abstract void setWrap(WrapMode mode); /** * <code>getWrap</code> returns the wrap mode for a given coordinate axis * on this texture. * * @param axis * the axis to return for * @return the wrap mode of the texture. * @throws IllegalArgumentException * if axis is null or invalid for this type of texture */ public abstract WrapMode getWrap(WrapAxis axis); public abstract Type getType(); /** * @return Returns the combineFuncRGB. */ public CombinerFunctionRGB getCombineFuncRGB() { return combineFuncRGB; } /** * @param combineFuncRGB * The combineFuncRGB to set. * @throws IllegalArgumentException * if combineFuncRGB is null */ public void setCombineFuncRGB(CombinerFunctionRGB combineFuncRGB) { if (combineFuncRGB == null) { throw new IllegalArgumentException("invalid CombinerFunctionRGB: null"); } this.combineFuncRGB = combineFuncRGB; } /** * @return Returns the combineOp0Alpha. */ public CombinerOperandAlpha getCombineOp0Alpha() { return combineOp0Alpha; } /** * @param combineOp0Alpha * The combineOp0Alpha to set. * @throws IllegalArgumentException * if combineOp0Alpha is null */ public void setCombineOp0Alpha(CombinerOperandAlpha combineOp0Alpha) { if (combineOp0Alpha == null) { throw new IllegalArgumentException("invalid CombinerOperandAlpha: null"); } this.combineOp0Alpha = combineOp0Alpha; } /** * @return Returns the combineOp0RGB. */ public CombinerOperandRGB getCombineOp0RGB() { return combineOp0RGB; } /** * @param combineOp0RGB * The combineOp0RGB to set. * @throws IllegalArgumentException * if combineOp0RGB is null */ public void setCombineOp0RGB(CombinerOperandRGB combineOp0RGB) { if (combineOp0RGB == null) { throw new IllegalArgumentException("invalid CombinerOperandRGB: null"); } this.combineOp0RGB = combineOp0RGB; } /** * @return Returns the combineOp1Alpha. */ public CombinerOperandAlpha getCombineOp1Alpha() { return combineOp1Alpha; } /** * @param combineOp1Alpha * The combineOp1Alpha to set. * @throws IllegalArgumentException * if combineOp1Alpha is null */ public void setCombineOp1Alpha(CombinerOperandAlpha combineOp1Alpha) { if (combineOp1Alpha == null) { throw new IllegalArgumentException("invalid CombinerOperandAlpha: null"); } this.combineOp1Alpha = combineOp1Alpha; } /** * @return Returns the combineOp1RGB. */ public CombinerOperandRGB getCombineOp1RGB() { return combineOp1RGB; } /** * @param combineOp1RGB * The combineOp1RGB to set. * @throws IllegalArgumentException * if combineOp1RGB is null */ public void setCombineOp1RGB(CombinerOperandRGB combineOp1RGB) { if (combineOp1RGB == null) { throw new IllegalArgumentException("invalid CombinerOperandRGB: null"); } this.combineOp1RGB = combineOp1RGB; } /** * @return Returns the combineOp2Alpha. */ public CombinerOperandAlpha getCombineOp2Alpha() { return combineOp2Alpha; } /** * @param combineOp2Alpha * The combineOp2Alpha to set. * @throws IllegalArgumentException * if combineOp2Alpha is null */ public void setCombineOp2Alpha(CombinerOperandAlpha combineOp2Alpha) { if (combineOp2Alpha == null) { throw new IllegalArgumentException("invalid CombinerOperandAlpha: null"); } this.combineOp2Alpha = combineOp2Alpha; } /** * @return Returns the combineOp2RGB. */ public CombinerOperandRGB getCombineOp2RGB() { return combineOp2RGB; } /** * @param combineOp2RGB * The combineOp2RGB to set. * @throws IllegalArgumentException * if combineOp2RGB is null */ public void setCombineOp2RGB(CombinerOperandRGB combineOp2RGB) { if (combineOp2RGB == null) { throw new IllegalArgumentException("invalid CombinerOperandRGB: null"); } this.combineOp2RGB = combineOp2RGB; } /** * @return Returns the combineScaleAlpha. */ public CombinerScale getCombineScaleAlpha() { return combineScaleAlpha; } /** * @param combineScaleAlpha * The combineScaleAlpha to set. * @throws IllegalArgumentException * if combineScaleAlpha is null */ public void setCombineScaleAlpha(CombinerScale combineScaleAlpha) { if (combineScaleAlpha == null) { throw new IllegalArgumentException("invalid CombinerScale: null"); } this.combineScaleAlpha = combineScaleAlpha; } /** * @return Returns the combineScaleRGB. */ public CombinerScale getCombineScaleRGB() { return combineScaleRGB; } /** * @param combineScaleRGB * The combineScaleRGB to set. * @throws IllegalArgumentException * if combineScaleRGB is null */ public void setCombineScaleRGB(CombinerScale combineScaleRGB) { if (combineScaleRGB == null) { throw new IllegalArgumentException("invalid CombinerScale: null"); } this.combineScaleRGB = combineScaleRGB; } /** * @return Returns the combineSrc0Alpha. */ public CombinerSource getCombineSrc0Alpha() { return combineSrc0Alpha; } /** * @param combineSrc0Alpha * The combineSrc0Alpha to set. * @throws IllegalArgumentException * if combineSrc0Alpha is null */ public void setCombineSrc0Alpha(CombinerSource combineSrc0Alpha) { if (combineSrc0Alpha == null) { throw new IllegalArgumentException("invalid CombinerSource: null"); } this.combineSrc0Alpha = combineSrc0Alpha; } /** * @return Returns the combineSrc0RGB. */ public CombinerSource getCombineSrc0RGB() { return combineSrc0RGB; } /** * @param combineSrc0RGB * The combineSrc0RGB to set. * @throws IllegalArgumentException * if combineSrc0RGB is null */ public void setCombineSrc0RGB(CombinerSource combineSrc0RGB) { if (combineSrc0RGB == null) { throw new IllegalArgumentException("invalid CombinerSource: null"); } this.combineSrc0RGB = combineSrc0RGB; } /** * @return Returns the combineSrc1Alpha. */ public CombinerSource getCombineSrc1Alpha() { return combineSrc1Alpha; } /** * @param combineSrc1Alpha * The combineSrc1Alpha to set. * @throws IllegalArgumentException * if combineSrc1Alpha is null */ public void setCombineSrc1Alpha(CombinerSource combineSrc1Alpha) { if (combineSrc1Alpha == null) { throw new IllegalArgumentException("invalid CombinerSource: null"); } this.combineSrc1Alpha = combineSrc1Alpha; } /** * @return Returns the combineSrc1RGB. */ public CombinerSource getCombineSrc1RGB() { return combineSrc1RGB; } /** * @param combineSrc1RGB * The combineSrc1RGB to set. * @throws IllegalArgumentException * if combineSrc1RGB is null */ public void setCombineSrc1RGB(CombinerSource combineSrc1RGB) { if (combineSrc1RGB == null) { throw new IllegalArgumentException("invalid CombinerSource: null"); } this.combineSrc1RGB = combineSrc1RGB; } /** * @return Returns the combineSrc2Alpha. */ public CombinerSource getCombineSrc2Alpha() { return combineSrc2Alpha; } /** * @param combineSrc2Alpha * The combineSrc2Alpha to set. * @throws IllegalArgumentException * if combineSrc2Alpha is null */ public void setCombineSrc2Alpha(CombinerSource combineSrc2Alpha) { if (combineSrc2Alpha == null) { throw new IllegalArgumentException("invalid CombinerSource: null"); } this.combineSrc2Alpha = combineSrc2Alpha; } /** * @return Returns the combineSrc2RGB. */ public CombinerSource getCombineSrc2RGB() { return combineSrc2RGB; } /** * @param combineSrc2RGB * The combineSrc2RGB to set. * @throws IllegalArgumentException * if combineSrc2RGB is null */ public void setCombineSrc2RGB(CombinerSource combineSrc2RGB) { if (combineSrc2RGB == null) { throw new IllegalArgumentException("invalid CombinerSource: null"); } this.combineSrc2RGB = combineSrc2RGB; } /** * @return Returns the combineFuncAlpha. */ public CombinerFunctionAlpha getCombineFuncAlpha() { return combineFuncAlpha; } /** * @param combineFuncAlpha * The combineFuncAlpha to set. * @throws IllegalArgumentException * if combineFuncAlpha is null */ public void setCombineFuncAlpha(CombinerFunctionAlpha combineFuncAlpha) { if (combineFuncAlpha == null) { throw new IllegalArgumentException("invalid CombinerFunctionAlpha: null"); } this.combineFuncAlpha = combineFuncAlpha; } /** * @param envMapMode * @throws IllegalArgumentException * if envMapMode is null */ public void setEnvironmentalMapMode(EnvironmentalMapMode envMapMode) { if (envMapMode == null) { throw new IllegalArgumentException("invalid EnvironmentalMapMode: null"); } this.envMapMode = envMapMode; } public EnvironmentalMapMode getEnvironmentalMapMode() { return envMapMode; } public String getImageLocation() { return imageLocation; } public void setImageLocation(String imageLocation) { this.imageLocation = imageLocation; } /** * @return the anisotropic filtering level for this texture as a percentage * (0.0 - 1.0) */ public float getAnisotropicFilterPercent() { return anisotropicFilterPercent; } /** * @param percent * the anisotropic filtering level for this texture as a * percentage (0.0 - 1.0) */ public void setAnisotropicFilterPercent(float percent) { if (percent > 1.0f) percent = 1.0f; else if (percent < 0.0f) percent = 0.0f; this.anisotropicFilterPercent = percent; } public boolean equals(Object other) { if (other == this) { return true; } if (!(other instanceof Texture)) { return false; } Texture that = (Texture) other; if (this.textureId != that.textureId) return false; if (this.textureId == 0) { + if (this.key != null && !this.key.equals(that.key)) + return false; if (this.getImage() != null && !this.getImage().equals(that.getImage())) return false; if (this.getImage() == null && that.getImage() != null) return false; if (this.getAnisotropicFilterPercent() != that .getAnisotropicFilterPercent()) return false; if (this.getApply() != that.getApply()) return false; if (this.getCombineFuncAlpha() != that.getCombineFuncAlpha()) return false; if (this.getCombineFuncRGB() != that.getCombineFuncRGB()) return false; if (this.getCombineOp0Alpha() != that.getCombineOp0Alpha()) return false; if (this.getCombineOp1RGB() != that.getCombineOp1RGB()) return false; if (this.getCombineOp2Alpha() != that.getCombineOp2Alpha()) return false; if (this.getCombineOp2RGB() != that.getCombineOp2RGB()) return false; if (this.getCombineScaleAlpha() != that.getCombineScaleAlpha()) return false; if (this.getCombineScaleRGB() != that.getCombineScaleRGB()) return false; if (this.getCombineSrc0Alpha() != that.getCombineSrc0Alpha()) return false; if (this.getCombineSrc0RGB() != that.getCombineSrc0RGB()) return false; if (this.getCombineSrc1Alpha() != that.getCombineSrc1Alpha()) return false; if (this.getCombineSrc1RGB() != that.getCombineSrc1RGB()) return false; if (this.getCombineSrc2Alpha() != that.getCombineSrc2Alpha()) return false; if (this.getCombineSrc2RGB() != that.getCombineSrc2RGB()) return false; if (this.getEnvironmentalMapMode() != that .getEnvironmentalMapMode()) return false; if (this.getMagnificationFilter() != that.getMagnificationFilter()) return false; if (this.getMinificationFilter() != that.getMinificationFilter()) return false; if (this.getBlendColor() != null && !this.getBlendColor().equals(that.getBlendColor())) return false; if (this.getBlendColor() == null && that.getBlendColor() != null) return false; } return true; } public abstract Texture createSimpleClone(); /** * Retreive a basic clone of this Texture (ie, clone everything but the * image data, which is shared) * * @return Texture */ public Texture createSimpleClone(Texture rVal) { rVal.setApply(apply); rVal.setCombineFuncAlpha(combineFuncAlpha); rVal.setCombineFuncRGB(combineFuncRGB); rVal.setCombineOp0Alpha(combineOp0Alpha); rVal.setCombineOp0RGB(combineOp0RGB); rVal.setCombineOp1Alpha(combineOp1Alpha); rVal.setCombineOp1RGB(combineOp1RGB); rVal.setCombineOp2Alpha(combineOp2Alpha); rVal.setCombineOp2RGB(combineOp2RGB); rVal.setCombineScaleAlpha(combineScaleAlpha); rVal.setCombineScaleRGB(combineScaleRGB); rVal.setCombineSrc0Alpha(combineSrc0Alpha); rVal.setCombineSrc0RGB(combineSrc0RGB); rVal.setCombineSrc1Alpha(combineSrc1Alpha); rVal.setCombineSrc1RGB(combineSrc1RGB); rVal.setCombineSrc2Alpha(combineSrc2Alpha); rVal.setCombineSrc2RGB(combineSrc2RGB); rVal.setEnvironmentalMapMode(envMapMode); rVal.setMinificationFilter(minificationFilter); rVal.setMagnificationFilter(magnificationFilter); rVal.setHasBorder(hasBorder); rVal.setAnisotropicFilterPercent(anisotropicFilterPercent); rVal.setImage(image); // NOT CLONED. rVal.memReq = memReq; rVal.setImageLocation(imageLocation); rVal.setTextureId(textureId); rVal.setBlendColor(blendColor != null ? blendColor.clone() : null); if (scale != null) rVal.setScale(scale); if (translation != null) rVal.setTranslation(translation); if (rotation != null) rVal.setRotation(rotation); if (matrix != null) rVal.setMatrix(matrix); if (getTextureKey() != null) { rVal.setTextureKey(getTextureKey()); } return rVal; } /** * @return Returns the rotation. */ public Quaternion getRotation() { return rotation; } /** * @param rotation * The rotation to set. */ public void setRotation(Quaternion rotation) { this.rotation = rotation; } /** * @return the texture matrix set on this texture or null if none is set. */ public Matrix4f getMatrix() { return matrix; } /** * @param matrix * The matrix to set on this Texture. If null, rotation, scale * and/or translation will be used. */ public void setMatrix(Matrix4f matrix) { this.matrix = matrix; } /** * @return Returns the scale. */ public Vector3f getScale() { return scale; } /** * @param scale * The scale to set. */ public void setScale(Vector3f scale) { this.scale = scale; } /** * @return Returns the translation. */ public Vector3f getTranslation() { return translation; } /** * @param translation * The translation to set. */ public void setTranslation(Vector3f translation) { this.translation = translation; } /** * @return Returns the rttSource. */ public RenderToTextureType getRTTSource() { return rttSource; } /** * @param rttSource * The rttSource to set. * @throws IllegalArgumentException * if rttSource is null */ public void setRenderToTextureType(RenderToTextureType rttSource) { if (rttSource == null) { throw new IllegalArgumentException("invalid RenderToTextureType: null"); } this.rttSource = rttSource; } /** * @return the estimated footprint of this texture in bytes */ public int getMemoryReq() { return memReq; } public void updateMemoryReq() { if (image != null) { int width = image.getWidth(), height = image.getHeight(); memReq = width * height; int bpp = Image.getEstimatedByteSize(image.getFormat()); memReq *= bpp; if (this.getMinificationFilter().usesMipMapLevels() || image.hasMipmaps()) { if (FastMath.isPowerOfTwo(image.getWidth()) && FastMath.isPowerOfTwo(image.getHeight())) memReq *= 1.33333f; else memReq *= 2.0f; // XXX: Is this right? } } } public void write(JMEExporter e) throws IOException { OutputCapsule capsule = e.getCapsule(this); capsule.write(imageLocation, "imageLocation", null); if (storeTexture) { capsule.write(image, "image", null); } capsule.write(blendColor, "blendColor", null); capsule.write(borderColor, "borderColor", null); capsule.write(translation, "translation", null); capsule.write(scale, "scale", null); capsule.write(rotation, "rotation", null); capsule.write(matrix, "matrix", null); capsule.write(hasBorder, "hasBorder", false); capsule.write(anisotropicFilterPercent, "anisotropicFilterPercent", 0.0f); capsule.write(minificationFilter, "minificationFilter", MinificationFilter.NearestNeighborNoMipMaps); capsule.write(magnificationFilter, "magnificationFilter", MagnificationFilter.NearestNeighbor); capsule.write(apply, "apply", ApplyMode.Modulate); capsule.write(envMapMode, "envMapMode", EnvironmentalMapMode.None); capsule.write(rttSource, "rttSource", RenderToTextureType.RGBA); capsule.write(memReq, "memReq", 0); capsule.write(combineFuncRGB, "combineFuncRGB", CombinerFunctionRGB.Replace); capsule.write(combineFuncAlpha, "combineFuncAlpha", CombinerFunctionAlpha.Replace); capsule.write(combineSrc0RGB, "combineSrc0RGB", CombinerSource.CurrentTexture); capsule .write(combineSrc1RGB, "combineSrc1RGB", CombinerSource.Previous); capsule .write(combineSrc2RGB, "combineSrc2RGB", CombinerSource.Constant); capsule.write(combineSrc0Alpha, "combineSrc0Alpha", CombinerSource.CurrentTexture); capsule.write(combineSrc1Alpha, "combineSrc1Alpha", CombinerSource.Previous); capsule.write(combineSrc2Alpha, "combineSrc2Alpha", CombinerSource.Constant); capsule.write(combineOp0RGB, "combineOp0RGB", CombinerOperandRGB.SourceColor); capsule.write(combineOp1RGB, "combineOp1RGB", CombinerOperandRGB.SourceColor); capsule.write(combineOp2RGB, "combineOp2RGB", CombinerOperandRGB.SourceAlpha); capsule.write(combineOp0Alpha, "combineOp0Alpha", CombinerOperandAlpha.SourceAlpha); capsule.write(combineOp1Alpha, "combineOp1Alpha", CombinerOperandAlpha.SourceAlpha); capsule.write(combineOp2Alpha, "combineOp2Alpha", CombinerOperandAlpha.SourceAlpha); capsule.write(combineScaleRGB, "combineScaleRGB", CombinerScale.One); capsule .write(combineScaleAlpha, "combineScaleAlpha", CombinerScale.One); if (!storeTexture) { capsule.write(key, "textureKey", null); } } public void read(JMEImporter e) throws IOException { InputCapsule capsule = e.getCapsule(this); imageLocation = capsule.readString("imageLocation", null); image = (Image) capsule.readSavable("image", null); if (image == null) { key = (TextureKey) capsule.readSavable("textureKey", null); if (key != null && key.getLocation() != null) { TextureManager.loadTexture(this, key); } } blendColor = (ColorRGBA) capsule.readSavable("blendColor", null); borderColor = (ColorRGBA) capsule.readSavable("borderColor", null); translation = (Vector3f) capsule.readSavable("translation", null); scale = (Vector3f) capsule.readSavable("scale", null); rotation = (Quaternion) capsule.readSavable("rotation", null); matrix = (Matrix4f) capsule.readSavable("matrix", null); hasBorder = capsule.readBoolean("hasBorder", false); anisotropicFilterPercent = capsule.readFloat( "anisotropicFilterPercent", 0.0f); minificationFilter = capsule.readEnum("minificationFilter", MinificationFilter.class, MinificationFilter.NearestNeighborNoMipMaps); magnificationFilter = capsule.readEnum("magnificationFilter", MagnificationFilter.class, MagnificationFilter.NearestNeighbor); apply = capsule.readEnum("apply", ApplyMode.class, ApplyMode.Modulate); envMapMode = capsule.readEnum("envMapMode", EnvironmentalMapMode.class, EnvironmentalMapMode.None); rttSource = capsule.readEnum("rttSource", RenderToTextureType.class, RenderToTextureType.RGBA); memReq = capsule.readInt("memReq", 0); combineFuncRGB = capsule.readEnum("combineFuncRGB", CombinerFunctionRGB.class, CombinerFunctionRGB.Replace); combineFuncAlpha = capsule.readEnum("combineFuncAlpha", CombinerFunctionAlpha.class, CombinerFunctionAlpha.Replace); combineSrc0RGB = capsule.readEnum("combineSrc0RGB", CombinerSource.class, CombinerSource.CurrentTexture); combineSrc1RGB = capsule.readEnum("combineSrc1RGB", CombinerSource.class, CombinerSource.Previous); combineSrc2RGB = capsule.readEnum("combineSrc2RGB", CombinerSource.class, CombinerSource.Constant); combineSrc0Alpha = capsule.readEnum("combineSrc0Alpha", CombinerSource.class, CombinerSource.CurrentTexture); combineSrc1Alpha = capsule.readEnum("combineSrc1Alpha", CombinerSource.class, CombinerSource.Previous); combineSrc2Alpha = capsule.readEnum("combineSrc2Alpha", CombinerSource.class, CombinerSource.Constant); combineOp0RGB = capsule.readEnum("combineOp0RGB", CombinerOperandRGB.class, CombinerOperandRGB.SourceColor); combineOp1RGB = capsule.readEnum("combineOp1RGB", CombinerOperandRGB.class, CombinerOperandRGB.SourceColor); combineOp2RGB = capsule.readEnum("combineOp2RGB", CombinerOperandRGB.class, CombinerOperandRGB.SourceAlpha); combineOp0Alpha = capsule.readEnum("combineOp0Alpha", CombinerOperandAlpha.class, CombinerOperandAlpha.SourceAlpha); combineOp1Alpha = capsule.readEnum("combineOp1Alpha", CombinerOperandAlpha.class, CombinerOperandAlpha.SourceAlpha); combineOp2Alpha = capsule.readEnum("combineOp2Alpha", CombinerOperandAlpha.class, CombinerOperandAlpha.SourceAlpha); combineScaleRGB = capsule.readEnum("combineScaleRGB", CombinerScale.class, CombinerScale.One); combineScaleAlpha = capsule.readEnum("combineScaleAlpha", CombinerScale.class, CombinerScale.One); } public Class<? extends Texture> getClassTag() { return this.getClass(); } public void setTextureKey(TextureKey tkey) { this.key = tkey; } public TextureKey getTextureKey() { return key; } public boolean isStoreTexture() { return storeTexture; } public void setStoreTexture(boolean storeTexture) { this.storeTexture = storeTexture; } public boolean hasBorder() { return hasBorder; } public void setHasBorder(boolean hasBorder) { this.hasBorder = hasBorder; } /** * Get the depth texture compare function * * @return The depth texture compare function */ public DepthTextureCompareFunc getDepthCompareFunc() { return depthCompareFunc; } /** * Set the depth texture compare function * * param depthCompareFunc The depth texture compare function */ public void setDepthCompareFunc(DepthTextureCompareFunc depthCompareFunc) { this.depthCompareFunc = depthCompareFunc; } /** * Get the depth texture apply mode * * @return The depth texture apply mode */ public DepthTextureMode getDepthMode() { return depthMode; } /** * Set the depth texture apply mode * * param depthMode The depth texture apply mode */ public void setDepthMode(DepthTextureMode depthMode) { this.depthMode = depthMode; } /** * Get the depth texture compare mode * * @return The depth texture compare mode */ public DepthTextureCompareMode getDepthCompareMode() { return depthCompareMode; } /** * Set the depth texture compare mode * * @param depthCompareMode The depth texture compare mode */ public void setDepthCompareMode(DepthTextureCompareMode depthCompareMode) { this.depthCompareMode = depthCompareMode; } }
true
true
public boolean equals(Object other) { if (other == this) { return true; } if (!(other instanceof Texture)) { return false; } Texture that = (Texture) other; if (this.textureId != that.textureId) return false; if (this.textureId == 0) { if (this.getImage() != null && !this.getImage().equals(that.getImage())) return false; if (this.getImage() == null && that.getImage() != null) return false; if (this.getAnisotropicFilterPercent() != that .getAnisotropicFilterPercent()) return false; if (this.getApply() != that.getApply()) return false; if (this.getCombineFuncAlpha() != that.getCombineFuncAlpha()) return false; if (this.getCombineFuncRGB() != that.getCombineFuncRGB()) return false; if (this.getCombineOp0Alpha() != that.getCombineOp0Alpha()) return false; if (this.getCombineOp1RGB() != that.getCombineOp1RGB()) return false; if (this.getCombineOp2Alpha() != that.getCombineOp2Alpha()) return false; if (this.getCombineOp2RGB() != that.getCombineOp2RGB()) return false; if (this.getCombineScaleAlpha() != that.getCombineScaleAlpha()) return false; if (this.getCombineScaleRGB() != that.getCombineScaleRGB()) return false; if (this.getCombineSrc0Alpha() != that.getCombineSrc0Alpha()) return false; if (this.getCombineSrc0RGB() != that.getCombineSrc0RGB()) return false; if (this.getCombineSrc1Alpha() != that.getCombineSrc1Alpha()) return false; if (this.getCombineSrc1RGB() != that.getCombineSrc1RGB()) return false; if (this.getCombineSrc2Alpha() != that.getCombineSrc2Alpha()) return false; if (this.getCombineSrc2RGB() != that.getCombineSrc2RGB()) return false; if (this.getEnvironmentalMapMode() != that .getEnvironmentalMapMode()) return false; if (this.getMagnificationFilter() != that.getMagnificationFilter()) return false; if (this.getMinificationFilter() != that.getMinificationFilter()) return false; if (this.getBlendColor() != null && !this.getBlendColor().equals(that.getBlendColor())) return false; if (this.getBlendColor() == null && that.getBlendColor() != null) return false; } return true; }
public boolean equals(Object other) { if (other == this) { return true; } if (!(other instanceof Texture)) { return false; } Texture that = (Texture) other; if (this.textureId != that.textureId) return false; if (this.textureId == 0) { if (this.key != null && !this.key.equals(that.key)) return false; if (this.getImage() != null && !this.getImage().equals(that.getImage())) return false; if (this.getImage() == null && that.getImage() != null) return false; if (this.getAnisotropicFilterPercent() != that .getAnisotropicFilterPercent()) return false; if (this.getApply() != that.getApply()) return false; if (this.getCombineFuncAlpha() != that.getCombineFuncAlpha()) return false; if (this.getCombineFuncRGB() != that.getCombineFuncRGB()) return false; if (this.getCombineOp0Alpha() != that.getCombineOp0Alpha()) return false; if (this.getCombineOp1RGB() != that.getCombineOp1RGB()) return false; if (this.getCombineOp2Alpha() != that.getCombineOp2Alpha()) return false; if (this.getCombineOp2RGB() != that.getCombineOp2RGB()) return false; if (this.getCombineScaleAlpha() != that.getCombineScaleAlpha()) return false; if (this.getCombineScaleRGB() != that.getCombineScaleRGB()) return false; if (this.getCombineSrc0Alpha() != that.getCombineSrc0Alpha()) return false; if (this.getCombineSrc0RGB() != that.getCombineSrc0RGB()) return false; if (this.getCombineSrc1Alpha() != that.getCombineSrc1Alpha()) return false; if (this.getCombineSrc1RGB() != that.getCombineSrc1RGB()) return false; if (this.getCombineSrc2Alpha() != that.getCombineSrc2Alpha()) return false; if (this.getCombineSrc2RGB() != that.getCombineSrc2RGB()) return false; if (this.getEnvironmentalMapMode() != that .getEnvironmentalMapMode()) return false; if (this.getMagnificationFilter() != that.getMagnificationFilter()) return false; if (this.getMinificationFilter() != that.getMinificationFilter()) return false; if (this.getBlendColor() != null && !this.getBlendColor().equals(that.getBlendColor())) return false; if (this.getBlendColor() == null && that.getBlendColor() != null) return false; } return true; }
diff --git a/modules/dar/src/main/java/org/cipango/dar/DefaultApplicationRouter.java b/modules/dar/src/main/java/org/cipango/dar/DefaultApplicationRouter.java index 03255a2..ab38eab 100644 --- a/modules/dar/src/main/java/org/cipango/dar/DefaultApplicationRouter.java +++ b/modules/dar/src/main/java/org/cipango/dar/DefaultApplicationRouter.java @@ -1,212 +1,221 @@ // ======================================================================== // Copyright 2008-2009 NEXCOM Systems // ------------------------------------------------------------------------ // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ======================================================================== package org.cipango.dar; import java.io.File; import java.io.Serializable; import java.net.URI; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.SortedSet; import java.util.TreeSet; import javax.servlet.sip.SipServletRequest; import javax.servlet.sip.ar.SipApplicationRouter; import javax.servlet.sip.ar.SipApplicationRouterInfo; import javax.servlet.sip.ar.SipApplicationRoutingDirective; import javax.servlet.sip.ar.SipApplicationRoutingRegion; import javax.servlet.sip.ar.SipRouteModifier; import javax.servlet.sip.ar.SipTargetedRequestInfo; import org.mortbay.log.Log; /** * Default Application Router. * Looks for its configuration from the property javax.servlet.sip.ar.dar.configuration * or etc/dar.properties if not defined. */ public class DefaultApplicationRouter implements SipApplicationRouter { public static final String __J_S_DAR_CONFIGURATION = "javax.servlet.sip.ar.dar.configuration"; public static final String MATCH_ON_NEW_OUTGOING_REQUESTS = "org.cipango.dar.matchOnNewOutgoingRequests"; public static final String DEFAULT_CONFIGURATION = "etc/dar.properties"; private Map<String, RouterInfo[]> _routerInfoMap; private String _configuration; private SortedSet<String> _applicationNames = new TreeSet<String>(); private boolean _matchOnNewOutgoingRequests; public void applicationDeployed(List<String> newlyDeployedApplicationNames) { _applicationNames.addAll(newlyDeployedApplicationNames); init(); } public void applicationUndeployed(List<String> toRemove) { _applicationNames.removeAll(toRemove); init(); } public void destroy() { } public SipApplicationRouterInfo getNextApplication(SipServletRequest initialRequest, SipApplicationRoutingRegion region, SipApplicationRoutingDirective directive, SipTargetedRequestInfo toto, Serializable stateInfo) { if (!_matchOnNewOutgoingRequests && initialRequest.getInitialRemoteAddr() == null) return null; if (_routerInfoMap == null || _routerInfoMap.isEmpty()) { if (stateInfo != null || _applicationNames.isEmpty() || directive != SipApplicationRoutingDirective.NEW) return null; return new SipApplicationRouterInfo(_applicationNames.first(), SipApplicationRoutingRegion.NEUTRAL_REGION, - initialRequest.getFrom().toString(), + initialRequest.getFrom().getURI().toString(), null, SipRouteModifier.NO_ROUTE, 1); } String method = initialRequest.getMethod(); RouterInfo[] infos = _routerInfoMap.get(method.toUpperCase()); if (infos == null) return null; int index = 0; if (stateInfo != null) index = (Integer) stateInfo; if (index >= 0 && index < infos.length) { RouterInfo info = infos[index]; String identity = info.getIdentity(); if (identity.startsWith("DAR:")) - identity = initialRequest.getHeader(identity.substring("DAR:".length())); + { + try + { + identity = initialRequest.getAddressHeader(identity.substring("DAR:".length())).getURI().toString(); + } + catch (Exception e) + { + Log.debug("Failed to parse router info identity: " + info.getIdentity(), e); + } + } return new SipApplicationRouterInfo(info.getName(), info.getRegion(), identity, null, SipRouteModifier.NO_ROUTE, index + 1); } return null; } public void setRouterInfos(Map<String, RouterInfo[]> infoMap) { _routerInfoMap = infoMap; } public Map<String, RouterInfo[]> getRouterInfos() { return _routerInfoMap; } public void init() { _matchOnNewOutgoingRequests = !System.getProperty(MATCH_ON_NEW_OUTGOING_REQUESTS, "true").equalsIgnoreCase("false"); if (_configuration == null) { String configuration = System.getProperty(__J_S_DAR_CONFIGURATION); if (configuration != null) { _configuration = configuration; } else if (System.getProperty("jetty.home") != null) { File home = new File(System.getProperty("jetty.home")); _configuration = new File(home, DEFAULT_CONFIGURATION).toURI().toString(); } if (_configuration == null) _configuration = DEFAULT_CONFIGURATION; } try { DARConfiguration config = new DARConfiguration(new URI(_configuration)); config.configure(this); } catch (Exception e) { Log.debug("DAR configuration error: " + e); } if ((_routerInfoMap == null || _routerInfoMap.isEmpty()) && !_applicationNames.isEmpty()) Log.info("No DAR configuration. Using application: " + _applicationNames.first()); } public void setConfiguration(String configuration) { _configuration = configuration; } public void init(Properties properties) { init(); } static class RouterInfo { private String _name; private String _identity; private SipApplicationRoutingRegion _region; private String _uri; private SipRouteModifier _routeModifier; public RouterInfo(String name, String identity, SipApplicationRoutingRegion region, String uri, SipRouteModifier routeModifier) { _name = name; _identity = identity; _region = region; _uri = uri; _routeModifier = routeModifier; } public String getUri() { return _uri; } public SipRouteModifier getRouteModifier() { return _routeModifier; } public String getName() { return _name; } public String getIdentity() { return _identity; } public SipApplicationRoutingRegion getRegion() { return _region; } } }
false
true
public SipApplicationRouterInfo getNextApplication(SipServletRequest initialRequest, SipApplicationRoutingRegion region, SipApplicationRoutingDirective directive, SipTargetedRequestInfo toto, Serializable stateInfo) { if (!_matchOnNewOutgoingRequests && initialRequest.getInitialRemoteAddr() == null) return null; if (_routerInfoMap == null || _routerInfoMap.isEmpty()) { if (stateInfo != null || _applicationNames.isEmpty() || directive != SipApplicationRoutingDirective.NEW) return null; return new SipApplicationRouterInfo(_applicationNames.first(), SipApplicationRoutingRegion.NEUTRAL_REGION, initialRequest.getFrom().toString(), null, SipRouteModifier.NO_ROUTE, 1); } String method = initialRequest.getMethod(); RouterInfo[] infos = _routerInfoMap.get(method.toUpperCase()); if (infos == null) return null; int index = 0; if (stateInfo != null) index = (Integer) stateInfo; if (index >= 0 && index < infos.length) { RouterInfo info = infos[index]; String identity = info.getIdentity(); if (identity.startsWith("DAR:")) identity = initialRequest.getHeader(identity.substring("DAR:".length())); return new SipApplicationRouterInfo(info.getName(), info.getRegion(), identity, null, SipRouteModifier.NO_ROUTE, index + 1); } return null; }
public SipApplicationRouterInfo getNextApplication(SipServletRequest initialRequest, SipApplicationRoutingRegion region, SipApplicationRoutingDirective directive, SipTargetedRequestInfo toto, Serializable stateInfo) { if (!_matchOnNewOutgoingRequests && initialRequest.getInitialRemoteAddr() == null) return null; if (_routerInfoMap == null || _routerInfoMap.isEmpty()) { if (stateInfo != null || _applicationNames.isEmpty() || directive != SipApplicationRoutingDirective.NEW) return null; return new SipApplicationRouterInfo(_applicationNames.first(), SipApplicationRoutingRegion.NEUTRAL_REGION, initialRequest.getFrom().getURI().toString(), null, SipRouteModifier.NO_ROUTE, 1); } String method = initialRequest.getMethod(); RouterInfo[] infos = _routerInfoMap.get(method.toUpperCase()); if (infos == null) return null; int index = 0; if (stateInfo != null) index = (Integer) stateInfo; if (index >= 0 && index < infos.length) { RouterInfo info = infos[index]; String identity = info.getIdentity(); if (identity.startsWith("DAR:")) { try { identity = initialRequest.getAddressHeader(identity.substring("DAR:".length())).getURI().toString(); } catch (Exception e) { Log.debug("Failed to parse router info identity: " + info.getIdentity(), e); } } return new SipApplicationRouterInfo(info.getName(), info.getRegion(), identity, null, SipRouteModifier.NO_ROUTE, index + 1); } return null; }
diff --git a/maven-project/src/main/java/org/apache/maven/project/builder/ArtifactModelContainerFactory.java b/maven-project/src/main/java/org/apache/maven/project/builder/ArtifactModelContainerFactory.java index 31c1a7d73..6eca64094 100644 --- a/maven-project/src/main/java/org/apache/maven/project/builder/ArtifactModelContainerFactory.java +++ b/maven-project/src/main/java/org/apache/maven/project/builder/ArtifactModelContainerFactory.java @@ -1,224 +1,224 @@ package org.apache.maven.project.builder; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.shared.model.ModelContainer; import org.apache.maven.shared.model.ModelContainerAction; import org.apache.maven.shared.model.ModelContainerFactory; import org.apache.maven.shared.model.ModelProperty; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; public final class ArtifactModelContainerFactory implements ModelContainerFactory { private static final Collection<String> uris = Collections.unmodifiableList( Arrays.asList( ProjectUri.DependencyManagement.Dependencies.Dependency.xUri, ProjectUri.Dependencies.Dependency.xUri, ProjectUri.Reporting.Plugins.Plugin.xUri, ProjectUri.Build.PluginManagement.Plugins.Plugin.xUri, ProjectUri.Build.PluginManagement.Plugins.Plugin.Dependencies.Dependency.xUri, ProjectUri.Build.Plugins.Plugin.xUri, ProjectUri.Build.Plugins.Plugin.Dependencies.Dependency.xUri, ProjectUri.Build.Plugins.Plugin.Dependencies.Dependency.Exclusions.Exclusion.xUri, ProjectUri.Build.Extensions.Extension.xUri ) ); public Collection<String> getUris() { return uris; } public ModelContainer create( List<ModelProperty> modelProperties ) { if ( modelProperties == null || modelProperties.size() == 0 ) { throw new IllegalArgumentException( "modelProperties: null or empty" ); } return new ArtifactModelContainer( modelProperties ); } private static class ArtifactModelContainer implements ModelContainer { private String groupId; private String artifactId; private String version; private String type; private String scope; private List<ModelProperty> properties; private static String findBaseUriFrom( List<ModelProperty> modelProperties ) { String baseUri = null; for ( ModelProperty mp : modelProperties ) { if ( baseUri == null || mp.getUri().length() < baseUri.length() ) { baseUri = mp.getUri(); } } return baseUri; } private ArtifactModelContainer( List<ModelProperty> properties ) { this.properties = new ArrayList<ModelProperty>( properties ); this.properties = Collections.unmodifiableList( this.properties ); String uri = findBaseUriFrom( this.properties ); for ( ModelProperty mp : this.properties ) { if ( version == null && mp.getUri().equals( uri + "/version" ) ) { this.version = mp.getResolvedValue(); } else if ( artifactId == null && mp.getUri().equals( uri + "/artifactId" ) ) { this.artifactId = mp.getResolvedValue(); } else if ( groupId == null && mp.getUri().equals( uri + "/groupId" ) ) { this.groupId = mp.getResolvedValue(); } else if ( scope == null && mp.getUri().equals( uri + "/scope" ) ) { this.scope = mp.getResolvedValue(); } else if ( type == null && mp.getUri().equals( ProjectUri.Dependencies.Dependency.type ) || mp.getUri().equals(ProjectUri.DependencyManagement.Dependencies.Dependency.type) || mp.getUri().equals(ProjectUri.Build.PluginManagement.Plugins.Plugin.Dependencies.Dependency.type) || mp.getUri().equals(ProjectUri.Build.Plugins.Plugin.Dependencies.Dependency.type)) { this.type = mp.getResolvedValue(); } } if ( groupId == null ) { groupId = "org.apache.maven.plugins"; // throw new IllegalArgumentException("properties does not contain group id. Artifact ID = " // + artifactId + ", Version = " + version); } if ( artifactId == null ) { StringBuffer sb = new StringBuffer(); for ( ModelProperty mp : properties ) { sb.append( mp ).append( "\r\n" ); } throw new IllegalArgumentException( "Properties does not contain artifact id. Group ID = " + groupId + ", Version = " + version + ", Base = " + uri + ":\r\n" + sb ); } if ( version == null ) { version = ""; } if ( type == null ) { - type = ""; + type = "jar"; } if ( scope == null ) { - scope = ""; + scope = "compile"; } } public ModelContainerAction containerAction( ModelContainer modelContainer ) { if ( modelContainer == null ) { throw new IllegalArgumentException( "modelContainer: null" ); } if ( !( modelContainer instanceof ArtifactModelContainer ) ) { throw new IllegalArgumentException( "modelContainer: wrong type" ); } ArtifactModelContainer c = (ArtifactModelContainer) modelContainer; if ( c.groupId.equals( groupId ) && c.artifactId.equals( artifactId ) ) { if ( c.version.equals( version ) ) { if ( c.type.equals( type ) ) { return ModelContainerAction.JOIN; } else { return ModelContainerAction.NOP; } } else { if ( c.type.equals( type ) ) { return ModelContainerAction.DELETE; } else { return ModelContainerAction.NOP; } } } else { return ModelContainerAction.NOP; } } public ModelContainer createNewInstance( List<ModelProperty> modelProperties ) { return new ArtifactModelContainer( modelProperties ); } public List<ModelProperty> getProperties() { return properties; } public String toString() { StringBuffer sb = new StringBuffer(); sb.append( "Group ID = " ).append( groupId ).append( ", Artifact ID = " ).append( artifactId ) .append( ", Version" ).append( version ).append( "\r\n" ); for ( ModelProperty mp : properties ) { sb.append( mp ).append( "\r\n" ); } return sb.toString(); } } }
false
true
private ArtifactModelContainer( List<ModelProperty> properties ) { this.properties = new ArrayList<ModelProperty>( properties ); this.properties = Collections.unmodifiableList( this.properties ); String uri = findBaseUriFrom( this.properties ); for ( ModelProperty mp : this.properties ) { if ( version == null && mp.getUri().equals( uri + "/version" ) ) { this.version = mp.getResolvedValue(); } else if ( artifactId == null && mp.getUri().equals( uri + "/artifactId" ) ) { this.artifactId = mp.getResolvedValue(); } else if ( groupId == null && mp.getUri().equals( uri + "/groupId" ) ) { this.groupId = mp.getResolvedValue(); } else if ( scope == null && mp.getUri().equals( uri + "/scope" ) ) { this.scope = mp.getResolvedValue(); } else if ( type == null && mp.getUri().equals( ProjectUri.Dependencies.Dependency.type ) || mp.getUri().equals(ProjectUri.DependencyManagement.Dependencies.Dependency.type) || mp.getUri().equals(ProjectUri.Build.PluginManagement.Plugins.Plugin.Dependencies.Dependency.type) || mp.getUri().equals(ProjectUri.Build.Plugins.Plugin.Dependencies.Dependency.type)) { this.type = mp.getResolvedValue(); } } if ( groupId == null ) { groupId = "org.apache.maven.plugins"; // throw new IllegalArgumentException("properties does not contain group id. Artifact ID = " // + artifactId + ", Version = " + version); } if ( artifactId == null ) { StringBuffer sb = new StringBuffer(); for ( ModelProperty mp : properties ) { sb.append( mp ).append( "\r\n" ); } throw new IllegalArgumentException( "Properties does not contain artifact id. Group ID = " + groupId + ", Version = " + version + ", Base = " + uri + ":\r\n" + sb ); } if ( version == null ) { version = ""; } if ( type == null ) { type = ""; } if ( scope == null ) { scope = ""; } }
private ArtifactModelContainer( List<ModelProperty> properties ) { this.properties = new ArrayList<ModelProperty>( properties ); this.properties = Collections.unmodifiableList( this.properties ); String uri = findBaseUriFrom( this.properties ); for ( ModelProperty mp : this.properties ) { if ( version == null && mp.getUri().equals( uri + "/version" ) ) { this.version = mp.getResolvedValue(); } else if ( artifactId == null && mp.getUri().equals( uri + "/artifactId" ) ) { this.artifactId = mp.getResolvedValue(); } else if ( groupId == null && mp.getUri().equals( uri + "/groupId" ) ) { this.groupId = mp.getResolvedValue(); } else if ( scope == null && mp.getUri().equals( uri + "/scope" ) ) { this.scope = mp.getResolvedValue(); } else if ( type == null && mp.getUri().equals( ProjectUri.Dependencies.Dependency.type ) || mp.getUri().equals(ProjectUri.DependencyManagement.Dependencies.Dependency.type) || mp.getUri().equals(ProjectUri.Build.PluginManagement.Plugins.Plugin.Dependencies.Dependency.type) || mp.getUri().equals(ProjectUri.Build.Plugins.Plugin.Dependencies.Dependency.type)) { this.type = mp.getResolvedValue(); } } if ( groupId == null ) { groupId = "org.apache.maven.plugins"; // throw new IllegalArgumentException("properties does not contain group id. Artifact ID = " // + artifactId + ", Version = " + version); } if ( artifactId == null ) { StringBuffer sb = new StringBuffer(); for ( ModelProperty mp : properties ) { sb.append( mp ).append( "\r\n" ); } throw new IllegalArgumentException( "Properties does not contain artifact id. Group ID = " + groupId + ", Version = " + version + ", Base = " + uri + ":\r\n" + sb ); } if ( version == null ) { version = ""; } if ( type == null ) { type = "jar"; } if ( scope == null ) { scope = "compile"; } }
diff --git a/editor/src/main/java/com/nebula2d/editor/ui/MainFrame.java b/editor/src/main/java/com/nebula2d/editor/ui/MainFrame.java index 21e7dbe..6aab365 100644 --- a/editor/src/main/java/com/nebula2d/editor/ui/MainFrame.java +++ b/editor/src/main/java/com/nebula2d/editor/ui/MainFrame.java @@ -1,107 +1,107 @@ /* * Nebula2D is a cross-platform, 2D game engine for PC, Mac, & Linux * Copyright (c) 2014 Jon Bonazza * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.nebula2d.editor.ui; import com.badlogic.gdx.Gdx; import com.nebula2d.editor.framework.Project; import javax.swing.*; import java.awt.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class MainFrame extends JFrame { private static MainFrame instance; private static RenderCanvas renderCanvas = new RenderCanvas(new RenderAdapter()); private static SceneGraph sceneGraph = new SceneGraph(); private static N2DToolbar toolbar = new N2DToolbar(); private static N2DMenuBar menuBar; private static Project project; public MainFrame() { super("Nebula2D"); instance = this; - setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); + setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); JScrollPane sp = new JScrollPane(sceneGraph); sp.setPreferredSize(new Dimension(300, 600)); getContentPane().add(toolbar, BorderLayout.NORTH); getContentPane().add(sp, BorderLayout.WEST); getContentPane().add(renderCanvas.getCanvas()); sceneGraph.setEnabled(false); renderCanvas.setEnabled(false); menuBar = new N2DMenuBar(); setJMenuBar(menuBar); setSize(1200, 768); validate(); setLocationRelativeTo(null); setVisible(true); renderCanvas.initCamera(renderCanvas.getCanvas().getWidth(), renderCanvas.getCanvas().getHeight()); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { if (JOptionPane.showConfirmDialog(getParent(), "Are you sure you want to exit?", "Are you sure?", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { + System.out.println("exit"); Gdx.app.exit(); - dispose(); } } }); } public static RenderCanvas getRenderCanvas() { return renderCanvas; } public static SceneGraph getSceneGraph() { return sceneGraph; } public static Project getProject() { return project; } public static N2DMenuBar getN2DMenuBar() { return menuBar; } public static N2DToolbar getToolbar() { return toolbar; } public static void setProject(Project project) { MainFrame.project = project; sceneGraph.setEnabled(project != null); renderCanvas.setEnabled(project != null); menuBar.getSceneMenu().setEnabled(project != null); toolbar.setRendererWidgetsEnabled(project != null); menuBar.getSaveMenuItem().setEnabled(project != null); if (project != null) { sceneGraph.init(); instance.setTitle("Nebula2D - " + project.getNameWithoutExt()); } else { instance.setTitle("Nebual2D"); } } }
false
true
public MainFrame() { super("Nebula2D"); instance = this; setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); JScrollPane sp = new JScrollPane(sceneGraph); sp.setPreferredSize(new Dimension(300, 600)); getContentPane().add(toolbar, BorderLayout.NORTH); getContentPane().add(sp, BorderLayout.WEST); getContentPane().add(renderCanvas.getCanvas()); sceneGraph.setEnabled(false); renderCanvas.setEnabled(false); menuBar = new N2DMenuBar(); setJMenuBar(menuBar); setSize(1200, 768); validate(); setLocationRelativeTo(null); setVisible(true); renderCanvas.initCamera(renderCanvas.getCanvas().getWidth(), renderCanvas.getCanvas().getHeight()); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { if (JOptionPane.showConfirmDialog(getParent(), "Are you sure you want to exit?", "Are you sure?", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { Gdx.app.exit(); dispose(); } } }); }
public MainFrame() { super("Nebula2D"); instance = this; setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); JScrollPane sp = new JScrollPane(sceneGraph); sp.setPreferredSize(new Dimension(300, 600)); getContentPane().add(toolbar, BorderLayout.NORTH); getContentPane().add(sp, BorderLayout.WEST); getContentPane().add(renderCanvas.getCanvas()); sceneGraph.setEnabled(false); renderCanvas.setEnabled(false); menuBar = new N2DMenuBar(); setJMenuBar(menuBar); setSize(1200, 768); validate(); setLocationRelativeTo(null); setVisible(true); renderCanvas.initCamera(renderCanvas.getCanvas().getWidth(), renderCanvas.getCanvas().getHeight()); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { if (JOptionPane.showConfirmDialog(getParent(), "Are you sure you want to exit?", "Are you sure?", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { System.out.println("exit"); Gdx.app.exit(); } } }); }
diff --git a/org.eclipse.mylyn.context.ui/src/org/eclipse/mylyn/internal/ui/actions/AbstractApplyMylarAction.java b/org.eclipse.mylyn.context.ui/src/org/eclipse/mylyn/internal/ui/actions/AbstractApplyMylarAction.java index 68d0f2280..f70db02f0 100644 --- a/org.eclipse.mylyn.context.ui/src/org/eclipse/mylyn/internal/ui/actions/AbstractApplyMylarAction.java +++ b/org.eclipse.mylyn.context.ui/src/org/eclipse/mylyn/internal/ui/actions/AbstractApplyMylarAction.java @@ -1,200 +1,201 @@ /******************************************************************************* * Copyright (c) 2004 - 2006 University Of British Columbia and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * University Of British Columbia - initial API and implementation *******************************************************************************/ package org.eclipse.mylar.internal.ui.actions; import java.util.List; import org.eclipse.core.runtime.Preferences.IPropertyChangeListener; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IAction; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.StructuredViewer; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.mylar.internal.core.util.MylarStatusHandler; import org.eclipse.mylar.internal.ui.MylarImages; import org.eclipse.mylar.provisional.core.MylarPlugin; import org.eclipse.mylar.provisional.ui.InterestFilter; import org.eclipse.mylar.provisional.ui.MylarUiPlugin; import org.eclipse.swt.widgets.Event; import org.eclipse.ui.IActionDelegate2; import org.eclipse.ui.IViewActionDelegate; import org.eclipse.ui.IViewPart; /** * Extending this class makes it possible to apply Mylar management to a * structured view (e.g. to provide interest-based filtering). * * @author Mik Kersten */ public abstract class AbstractApplyMylarAction extends Action implements IViewActionDelegate, IActionDelegate2, IPropertyChangeListener { private static final String ACTION_LABEL = "Apply Mylar"; public static final String PREF_ID_PREFIX = "org.eclipse.mylar.ui.interest.filter."; protected String prefId; protected IAction initAction = null; protected InterestFilter interestFilter; protected IViewPart viewPart; public AbstractApplyMylarAction(InterestFilter interestFilter) { super(); this.interestFilter = interestFilter; setText(ACTION_LABEL); setToolTipText(ACTION_LABEL); setImageDescriptor(MylarImages.INTEREST_FILTERING); } public void init(IAction action) { initAction = action; setChecked(action.isChecked()); } public void init(IViewPart view) { String id = view.getSite().getId(); prefId = PREF_ID_PREFIX + id; viewPart = view; } public void run(IAction action) { setChecked(action.isChecked()); valueChanged(action, action.isChecked(), true); } /** * Don't update if the preference has not been initialized. */ public void update() { if (prefId != null) { update(MylarPlugin.getDefault().getPreferenceStore().getBoolean(prefId)); } } /** * This operation is expensive. */ public void update(boolean on) { valueChanged(initAction, on, false); } protected void valueChanged(IAction action, final boolean on, boolean store) { try { MylarPlugin.getContextManager().setContextCapturePaused(true); setChecked(on); action.setChecked(on); if (store && MylarPlugin.getDefault() != null) MylarPlugin.getDefault().getPreferenceStore().setValue(prefId, on); for (StructuredViewer viewer : getViewers()) { MylarUiPlugin.getDefault().getViewerManager().addManagedViewer(viewer, viewPart); installInterestFilter(on, viewer); } } catch (Throwable t) { MylarStatusHandler.fail(t, "Could not install viewer manager on: " + prefId, false); } finally { MylarPlugin.getContextManager().setContextCapturePaused(false); } } /** * Public for testing */ public void installInterestFilter(final boolean on, StructuredViewer viewer) { if (viewer != null) { boolean installed = false; if (on) { installed = installInterestFilter(viewer); MylarUiPlugin.getDefault().getViewerManager().addFilteredViewer(viewer); } else { uninstallInterestFilter(viewer); MylarUiPlugin.getDefault().getViewerManager().removeFilteredViewer(viewer); } if (installed && on && viewer instanceof TreeViewer) { ((TreeViewer) viewer).expandAll(); } } } /** * Public for testing */ public abstract List<StructuredViewer> getViewers(); protected boolean installInterestFilter(StructuredViewer viewer) { try { if (viewer != null) { boolean found = false; for (int i = 0; i < viewer.getFilters().length; i++) { ViewerFilter viewerFilter = viewer.getFilters()[i]; - if (viewerFilter instanceof InterestFilter) + if (viewerFilter instanceof InterestFilter) { found = true; + } } if (!found) { viewer.getControl().setRedraw(false); viewer.addFilter(interestFilter); viewer.getControl().setRedraw(true); return true; } } else { MylarStatusHandler.log("Could not install interest filter", this); } } catch (Throwable t) { MylarStatusHandler.fail(t, "Could not install viewer fitler on: " + prefId, false); } return false; } protected void uninstallInterestFilter(StructuredViewer viewer) { if (viewer != null) { for (int i = 0; i < viewer.getFilters().length; i++) { ViewerFilter filter = viewer.getFilters()[i]; if (filter instanceof InterestFilter) { viewer.getControl().setRedraw(false); viewer.removeFilter(filter); viewer.getControl().setRedraw(true); } } } else { MylarStatusHandler.log("Could not uninstall interest filter", this); } } public void selectionChanged(IAction action, ISelection selection) { // ignore } public void dispose() { for (StructuredViewer viewer : getViewers()) { MylarUiPlugin.getDefault().getViewerManager().removeManagedViewer(viewer, viewPart); } } public void runWithEvent(IAction action, Event event) { run(action); } public String getPrefId() { return prefId; } /** * For testing. */ public InterestFilter getInterestFilter() { return interestFilter; } }
false
true
protected boolean installInterestFilter(StructuredViewer viewer) { try { if (viewer != null) { boolean found = false; for (int i = 0; i < viewer.getFilters().length; i++) { ViewerFilter viewerFilter = viewer.getFilters()[i]; if (viewerFilter instanceof InterestFilter) found = true; } if (!found) { viewer.getControl().setRedraw(false); viewer.addFilter(interestFilter); viewer.getControl().setRedraw(true); return true; } } else { MylarStatusHandler.log("Could not install interest filter", this); } } catch (Throwable t) { MylarStatusHandler.fail(t, "Could not install viewer fitler on: " + prefId, false); } return false; }
protected boolean installInterestFilter(StructuredViewer viewer) { try { if (viewer != null) { boolean found = false; for (int i = 0; i < viewer.getFilters().length; i++) { ViewerFilter viewerFilter = viewer.getFilters()[i]; if (viewerFilter instanceof InterestFilter) { found = true; } } if (!found) { viewer.getControl().setRedraw(false); viewer.addFilter(interestFilter); viewer.getControl().setRedraw(true); return true; } } else { MylarStatusHandler.log("Could not install interest filter", this); } } catch (Throwable t) { MylarStatusHandler.fail(t, "Could not install viewer fitler on: " + prefId, false); } return false; }
diff --git a/src/main/java/views/gui/components/LimitedDocument.java b/src/main/java/views/gui/components/LimitedDocument.java index eb6d59a..c247e3b 100644 --- a/src/main/java/views/gui/components/LimitedDocument.java +++ b/src/main/java/views/gui/components/LimitedDocument.java @@ -1,21 +1,23 @@ package views.gui.components; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.PlainDocument; public class LimitedDocument extends PlainDocument { private static final long serialVersionUID = -3792500384846017205L; int limit; public LimitedDocument(int limit) { this.limit = limit; } @Override public void insertString(int offs, String str, AttributeSet attr) throws BadLocationException { - if(str == null || getLength() + str.length() > limit) + if(str == null) return; + if(getLength() + str.length() > limit) + str = str.substring(0, limit-getLength()); super.insertString(offs, str, attr); } }
false
true
public void insertString(int offs, String str, AttributeSet attr) throws BadLocationException { if(str == null || getLength() + str.length() > limit) return; super.insertString(offs, str, attr); }
public void insertString(int offs, String str, AttributeSet attr) throws BadLocationException { if(str == null) return; if(getLength() + str.length() > limit) str = str.substring(0, limit-getLength()); super.insertString(offs, str, attr); }
diff --git a/lucene/contrib/highlighter/src/java/org/apache/lucene/search/highlight/TokenSources.java b/lucene/contrib/highlighter/src/java/org/apache/lucene/search/highlight/TokenSources.java index f1392b4cb..1043b7cb2 100644 --- a/lucene/contrib/highlighter/src/java/org/apache/lucene/search/highlight/TokenSources.java +++ b/lucene/contrib/highlighter/src/java/org/apache/lucene/search/highlight/TokenSources.java @@ -1,296 +1,296 @@ /* * Created on 28-Oct-2004 */ package org.apache.lucene.search.highlight; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.IOException; import java.io.StringReader; import java.util.ArrayList; import java.util.Comparator; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.Token; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.analysis.tokenattributes.CharTermAttribute; import org.apache.lucene.analysis.tokenattributes.OffsetAttribute; import org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute; import org.apache.lucene.document.Document; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.TermFreqVector; import org.apache.lucene.index.TermPositionVector; import org.apache.lucene.index.TermVectorOffsetInfo; import org.apache.lucene.util.ArrayUtil; import org.apache.lucene.util.BytesRef; /** * Hides implementation issues associated with obtaining a TokenStream for use * with the higlighter - can obtain from TermFreqVectors with offsets and * (optionally) positions or from Analyzer class reparsing the stored content. */ public class TokenSources { /** * A convenience method that tries to first get a TermPositionVector for the * specified docId, then, falls back to using the passed in * {@link org.apache.lucene.document.Document} to retrieve the TokenStream. * This is useful when you already have the document, but would prefer to use * the vector first. * * @param reader The {@link org.apache.lucene.index.IndexReader} to use to try * and get the vector from * @param docId The docId to retrieve. * @param field The field to retrieve on the document * @param doc The document to fall back on * @param analyzer The analyzer to use for creating the TokenStream if the * vector doesn't exist * @return The {@link org.apache.lucene.analysis.TokenStream} for the * {@link org.apache.lucene.document.Fieldable} on the * {@link org.apache.lucene.document.Document} * @throws IOException if there was an error loading */ public static TokenStream getAnyTokenStream(IndexReader reader, int docId, String field, Document doc, Analyzer analyzer) throws IOException { TokenStream ts = null; TermFreqVector tfv = reader.getTermFreqVector(docId, field); if (tfv != null) { if (tfv instanceof TermPositionVector) { ts = getTokenStream((TermPositionVector) tfv); } } // No token info stored so fall back to analyzing raw content if (ts == null) { ts = getTokenStream(doc, field, analyzer); } return ts; } /** * A convenience method that tries a number of approaches to getting a token * stream. The cost of finding there are no termVectors in the index is * minimal (1000 invocations still registers 0 ms). So this "lazy" (flexible?) * approach to coding is probably acceptable * * @param reader * @param docId * @param field * @param analyzer * @return null if field not stored correctly * @throws IOException */ public static TokenStream getAnyTokenStream(IndexReader reader, int docId, String field, Analyzer analyzer) throws IOException { TokenStream ts = null; TermFreqVector tfv = reader.getTermFreqVector(docId, field); if (tfv != null) { if (tfv instanceof TermPositionVector) { ts = getTokenStream((TermPositionVector) tfv); } } // No token info stored so fall back to analyzing raw content if (ts == null) { ts = getTokenStream(reader, docId, field, analyzer); } return ts; } public static TokenStream getTokenStream(TermPositionVector tpv) { // assumes the worst and makes no assumptions about token position // sequences. return getTokenStream(tpv, false); } /** * Low level api. Returns a token stream or null if no offset info available * in index. This can be used to feed the highlighter with a pre-parsed token * stream * * In my tests the speeds to recreate 1000 token streams using this method * are: - with TermVector offset only data stored - 420 milliseconds - with * TermVector offset AND position data stored - 271 milliseconds (nb timings * for TermVector with position data are based on a tokenizer with contiguous * positions - no overlaps or gaps) The cost of not using TermPositionVector * to store pre-parsed content and using an analyzer to re-parse the original * content: - reanalyzing the original content - 980 milliseconds * * The re-analyze timings will typically vary depending on - 1) The complexity * of the analyzer code (timings above were using a * stemmer/lowercaser/stopword combo) 2) The number of other fields (Lucene * reads ALL fields off the disk when accessing just one document field - can * cost dear!) 3) Use of compression on field storage - could be faster due to * compression (less disk IO) or slower (more CPU burn) depending on the * content. * * @param tpv * @param tokenPositionsGuaranteedContiguous true if the token position * numbers have no overlaps or gaps. If looking to eek out the last * drops of performance, set to true. If in doubt, set to false. */ public static TokenStream getTokenStream(TermPositionVector tpv, boolean tokenPositionsGuaranteedContiguous) { if (!tokenPositionsGuaranteedContiguous && tpv.getTermPositions(0) != null) { return new TokenStreamFromTermPositionVector(tpv); } // an object used to iterate across an array of tokens final class StoredTokenStream extends TokenStream { Token tokens[]; int currentToken = 0; CharTermAttribute termAtt; OffsetAttribute offsetAtt; PositionIncrementAttribute posincAtt; StoredTokenStream(Token tokens[]) { this.tokens = tokens; termAtt = addAttribute(CharTermAttribute.class); offsetAtt = addAttribute(OffsetAttribute.class); - posincAtt = (PositionIncrementAttribute) addAttribute(PositionIncrementAttribute.class); + posincAtt = addAttribute(PositionIncrementAttribute.class); } @Override public boolean incrementToken() throws IOException { if (currentToken >= tokens.length) { return false; } Token token = tokens[currentToken++]; clearAttributes(); termAtt.setEmpty().append(token); offsetAtt.setOffset(token.startOffset(), token.endOffset()); posincAtt .setPositionIncrement(currentToken <= 1 || tokens[currentToken - 1].startOffset() > tokens[currentToken - 2] .startOffset() ? 1 : 0); return true; } } // code to reconstruct the original sequence of Tokens BytesRef[] terms = tpv.getTerms(); int[] freq = tpv.getTermFrequencies(); int totalTokens = 0; for (int t = 0; t < freq.length; t++) { totalTokens += freq[t]; } Token tokensInOriginalOrder[] = new Token[totalTokens]; ArrayList<Token> unsortedTokens = null; for (int t = 0; t < freq.length; t++) { TermVectorOffsetInfo[] offsets = tpv.getOffsets(t); if (offsets == null) { throw new IllegalArgumentException( "Required TermVector Offset information was not found"); } int[] pos = null; if (tokenPositionsGuaranteedContiguous) { // try get the token position info to speed up assembly of tokens into // sorted sequence pos = tpv.getTermPositions(t); } if (pos == null) { // tokens NOT stored with positions or not guaranteed contiguous - must // add to list and sort later if (unsortedTokens == null) { unsortedTokens = new ArrayList<Token>(); } for (int tp = 0; tp < offsets.length; tp++) { Token token = new Token(terms[t].utf8ToString(), offsets[tp].getStartOffset(), offsets[tp].getEndOffset()); unsortedTokens.add(token); } } else { // We have positions stored and a guarantee that the token position // information is contiguous // This may be fast BUT wont work if Tokenizers used which create >1 // token in same position or // creates jumps in position numbers - this code would fail under those // circumstances // tokens stored with positions - can use this to index straight into // sorted array for (int tp = 0; tp < pos.length; tp++) { Token token = new Token(terms[t].utf8ToString(), offsets[tp].getStartOffset(), offsets[tp].getEndOffset()); tokensInOriginalOrder[pos[tp]] = token; } } } // If the field has been stored without position data we must perform a sort if (unsortedTokens != null) { tokensInOriginalOrder = unsortedTokens.toArray(new Token[unsortedTokens .size()]); ArrayUtil.mergeSort(tokensInOriginalOrder, new Comparator<Token>() { public int compare(Token t1, Token t2) { if (t1.startOffset() == t2.startOffset()) return t1.endOffset() - t2.endOffset(); else return t1.startOffset() - t2.startOffset(); } }); } return new StoredTokenStream(tokensInOriginalOrder); } public static TokenStream getTokenStream(IndexReader reader, int docId, String field) throws IOException { TermFreqVector tfv = reader.getTermFreqVector(docId, field); if (tfv == null) { throw new IllegalArgumentException(field + " in doc #" + docId + "does not have any term position data stored"); } if (tfv instanceof TermPositionVector) { TermPositionVector tpv = (TermPositionVector) reader.getTermFreqVector( docId, field); return getTokenStream(tpv); } throw new IllegalArgumentException(field + " in doc #" + docId + "does not have any term position data stored"); } // convenience method public static TokenStream getTokenStream(IndexReader reader, int docId, String field, Analyzer analyzer) throws IOException { Document doc = reader.document(docId); return getTokenStream(doc, field, analyzer); } public static TokenStream getTokenStream(Document doc, String field, Analyzer analyzer) { String contents = doc.get(field); if (contents == null) { throw new IllegalArgumentException("Field " + field + " in document is not stored and cannot be analyzed"); } return getTokenStream(field, contents, analyzer); } // convenience method public static TokenStream getTokenStream(String field, String contents, Analyzer analyzer) { try { return analyzer.reusableTokenStream(field, new StringReader(contents)); } catch (IOException ex) { throw new RuntimeException(ex); } } }
true
true
public static TokenStream getTokenStream(TermPositionVector tpv, boolean tokenPositionsGuaranteedContiguous) { if (!tokenPositionsGuaranteedContiguous && tpv.getTermPositions(0) != null) { return new TokenStreamFromTermPositionVector(tpv); } // an object used to iterate across an array of tokens final class StoredTokenStream extends TokenStream { Token tokens[]; int currentToken = 0; CharTermAttribute termAtt; OffsetAttribute offsetAtt; PositionIncrementAttribute posincAtt; StoredTokenStream(Token tokens[]) { this.tokens = tokens; termAtt = addAttribute(CharTermAttribute.class); offsetAtt = addAttribute(OffsetAttribute.class); posincAtt = (PositionIncrementAttribute) addAttribute(PositionIncrementAttribute.class); } @Override public boolean incrementToken() throws IOException { if (currentToken >= tokens.length) { return false; } Token token = tokens[currentToken++]; clearAttributes(); termAtt.setEmpty().append(token); offsetAtt.setOffset(token.startOffset(), token.endOffset()); posincAtt .setPositionIncrement(currentToken <= 1 || tokens[currentToken - 1].startOffset() > tokens[currentToken - 2] .startOffset() ? 1 : 0); return true; } } // code to reconstruct the original sequence of Tokens BytesRef[] terms = tpv.getTerms(); int[] freq = tpv.getTermFrequencies(); int totalTokens = 0; for (int t = 0; t < freq.length; t++) { totalTokens += freq[t]; } Token tokensInOriginalOrder[] = new Token[totalTokens]; ArrayList<Token> unsortedTokens = null; for (int t = 0; t < freq.length; t++) { TermVectorOffsetInfo[] offsets = tpv.getOffsets(t); if (offsets == null) { throw new IllegalArgumentException( "Required TermVector Offset information was not found"); } int[] pos = null; if (tokenPositionsGuaranteedContiguous) { // try get the token position info to speed up assembly of tokens into // sorted sequence pos = tpv.getTermPositions(t); } if (pos == null) { // tokens NOT stored with positions or not guaranteed contiguous - must // add to list and sort later if (unsortedTokens == null) { unsortedTokens = new ArrayList<Token>(); } for (int tp = 0; tp < offsets.length; tp++) { Token token = new Token(terms[t].utf8ToString(), offsets[tp].getStartOffset(), offsets[tp].getEndOffset()); unsortedTokens.add(token); } } else { // We have positions stored and a guarantee that the token position // information is contiguous // This may be fast BUT wont work if Tokenizers used which create >1 // token in same position or // creates jumps in position numbers - this code would fail under those // circumstances // tokens stored with positions - can use this to index straight into // sorted array for (int tp = 0; tp < pos.length; tp++) { Token token = new Token(terms[t].utf8ToString(), offsets[tp].getStartOffset(), offsets[tp].getEndOffset()); tokensInOriginalOrder[pos[tp]] = token; } } } // If the field has been stored without position data we must perform a sort if (unsortedTokens != null) { tokensInOriginalOrder = unsortedTokens.toArray(new Token[unsortedTokens .size()]); ArrayUtil.mergeSort(tokensInOriginalOrder, new Comparator<Token>() { public int compare(Token t1, Token t2) { if (t1.startOffset() == t2.startOffset()) return t1.endOffset() - t2.endOffset(); else return t1.startOffset() - t2.startOffset(); } }); } return new StoredTokenStream(tokensInOriginalOrder); }
public static TokenStream getTokenStream(TermPositionVector tpv, boolean tokenPositionsGuaranteedContiguous) { if (!tokenPositionsGuaranteedContiguous && tpv.getTermPositions(0) != null) { return new TokenStreamFromTermPositionVector(tpv); } // an object used to iterate across an array of tokens final class StoredTokenStream extends TokenStream { Token tokens[]; int currentToken = 0; CharTermAttribute termAtt; OffsetAttribute offsetAtt; PositionIncrementAttribute posincAtt; StoredTokenStream(Token tokens[]) { this.tokens = tokens; termAtt = addAttribute(CharTermAttribute.class); offsetAtt = addAttribute(OffsetAttribute.class); posincAtt = addAttribute(PositionIncrementAttribute.class); } @Override public boolean incrementToken() throws IOException { if (currentToken >= tokens.length) { return false; } Token token = tokens[currentToken++]; clearAttributes(); termAtt.setEmpty().append(token); offsetAtt.setOffset(token.startOffset(), token.endOffset()); posincAtt .setPositionIncrement(currentToken <= 1 || tokens[currentToken - 1].startOffset() > tokens[currentToken - 2] .startOffset() ? 1 : 0); return true; } } // code to reconstruct the original sequence of Tokens BytesRef[] terms = tpv.getTerms(); int[] freq = tpv.getTermFrequencies(); int totalTokens = 0; for (int t = 0; t < freq.length; t++) { totalTokens += freq[t]; } Token tokensInOriginalOrder[] = new Token[totalTokens]; ArrayList<Token> unsortedTokens = null; for (int t = 0; t < freq.length; t++) { TermVectorOffsetInfo[] offsets = tpv.getOffsets(t); if (offsets == null) { throw new IllegalArgumentException( "Required TermVector Offset information was not found"); } int[] pos = null; if (tokenPositionsGuaranteedContiguous) { // try get the token position info to speed up assembly of tokens into // sorted sequence pos = tpv.getTermPositions(t); } if (pos == null) { // tokens NOT stored with positions or not guaranteed contiguous - must // add to list and sort later if (unsortedTokens == null) { unsortedTokens = new ArrayList<Token>(); } for (int tp = 0; tp < offsets.length; tp++) { Token token = new Token(terms[t].utf8ToString(), offsets[tp].getStartOffset(), offsets[tp].getEndOffset()); unsortedTokens.add(token); } } else { // We have positions stored and a guarantee that the token position // information is contiguous // This may be fast BUT wont work if Tokenizers used which create >1 // token in same position or // creates jumps in position numbers - this code would fail under those // circumstances // tokens stored with positions - can use this to index straight into // sorted array for (int tp = 0; tp < pos.length; tp++) { Token token = new Token(terms[t].utf8ToString(), offsets[tp].getStartOffset(), offsets[tp].getEndOffset()); tokensInOriginalOrder[pos[tp]] = token; } } } // If the field has been stored without position data we must perform a sort if (unsortedTokens != null) { tokensInOriginalOrder = unsortedTokens.toArray(new Token[unsortedTokens .size()]); ArrayUtil.mergeSort(tokensInOriginalOrder, new Comparator<Token>() { public int compare(Token t1, Token t2) { if (t1.startOffset() == t2.startOffset()) return t1.endOffset() - t2.endOffset(); else return t1.startOffset() - t2.startOffset(); } }); } return new StoredTokenStream(tokensInOriginalOrder); }
diff --git a/common/src/main/java/com/redhat/qe/jon/common/util/AS7SSHClient.java b/common/src/main/java/com/redhat/qe/jon/common/util/AS7SSHClient.java index 8b21e30d..abc06ec6 100644 --- a/common/src/main/java/com/redhat/qe/jon/common/util/AS7SSHClient.java +++ b/common/src/main/java/com/redhat/qe/jon/common/util/AS7SSHClient.java @@ -1,160 +1,160 @@ package com.redhat.qe.jon.common.util; import com.redhat.qe.tools.SSHCommandResult; import java.io.File; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class AS7SSHClient extends SSHClient { private String serverConfig; // allows to recognize the correct AS7 server process private final String asHome; private static final SimpleDateFormat sdfServerLog = new SimpleDateFormat("HH:mm:ss"); public AS7SSHClient(String asHome) { super(); this.asHome = asHome; } public AS7SSHClient(String asHome, String user,String host, String pass) { super(user,host,pass); this.asHome = asHome; } public AS7SSHClient(String asHome, String user,String host, File keyFile, String pass) { super(user,host,keyFile,pass); this.asHome = asHome; } public AS7SSHClient(String asHome, String serverConfig, String user,String host, File keyFile, String pass) { super(user,host,keyFile,pass); this.asHome = asHome; this.serverConfig = serverConfig; } /** * gets AS7/EAP home dir * @return AS7/EAP home dir */ public String getAsHome() { return asHome; } /** * restarts server by killing it and starting using given script * @param script name of startup script located in {@link AS7SSHClient#getAsHome()} / bin */ public void restart(String script) { stop(); try { Thread.currentThread().join(10*1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } start(script); } /** * starts server * @param script name of startup script located in {@link AS7SSHClient#getAsHome()} / bin */ public void start(String script) { run("cd "+asHome+"/bin && nohup ./"+script+" &"); } /** * stops server by killing it */ public void stop() { String pids = null; String grepFiltering = getGrepFiltering(); if (isJpsSupported()) { pids = runAndWait(getJpsCommand() + " | " + grepFiltering + " | awk '{print $1}'").getStdout(); } else { pids = runAndWait("ps -ef | " + grepFiltering + " | awk '{print $2}'").getStdout(); } if (pids!=null && pids.length()>0) { for (String pid : pids.split("\n")) { runAndWait("kill -9 "+pid); } } } private String getGrepFiltering() { String grepFiltering = ""; if (serverConfig != null) { grepFiltering = "grep "+asHome+" | grep "+serverConfig+" | grep java | grep -v bash | grep -v -w grep"; } else { grepFiltering = "grep "+asHome+" | grep java | grep -v bash | grep -v -w grep"; } return grepFiltering; } /** * checks if jps is supported on the remote machine * @return true if jps command is available on the remote machine, false otherwise */ public boolean isJpsSupported() { SSHCommandResult res = runAndWait("jps &>/dev/null || $JAVA_HOME/bin/jps &>/dev/null || "+getJavaHome()+"/bin/jps -mlvV &>/dev/null"); return res.getExitCode().intValue() == 0; } /** * * @return value of JAVA_HOME sys environment, if not set, empty string is returned */ public String getJavaHome() { // there is great chance, that the path to JAVA_HOME on this machine would be also valid in the other machine String javaHome = System.getenv("JAVA_HOME"); if (javaHome == null) { javaHome = ""; } return javaHome; } /** * @return jps command which takes into account JAVA_HOME env variable */ public String getJpsCommand() { return "{ jps -mlvV || $JAVA_HOME/bin/jps -mlvV || "+getJavaHome()+"/bin/jps -mlvV; }"; } /** * check whether EAP server is running * @return true if server process is running */ public boolean isRunning() { String grepFiltering = getGrepFiltering(); if (isJpsSupported()) { return runAndWait(getJpsCommand() + " | " + grepFiltering).getStdout().contains(asHome); } else { return runAndWait("ps -ef | " + grepFiltering).getStdout().contains(asHome); } } /** * @param logFile relative path located in {@link AS7SSHClient#getAsHome()} to server's log with boot information (for 6.0.x it is boot.log, for 6.1.x standalone mode it is server.log) logFile * @return server startup time by parsing 1st line of it's log file */ public Date getStartupTime(String logFile) { String dateStringFilteringCommand = ""; if (logFile.endsWith("server.log")) { - dateStringFilteringCommand += "grep '\\[org\\.jboss\\.modules\\]' " +asHome+"/"+logFile +" | tail -n -1 | awk -F , '{print $1}'"; + dateStringFilteringCommand += "grep '\\[org\\.jboss\\.modules\\]' " +asHome+"/"+logFile +" | tail -1 | awk -F , '{print $1}'"; } else { dateStringFilteringCommand += "head -n1 "+asHome+"/"+logFile+" | awk -F, '{print $1}' "; } String dateStr = runAndWait(dateStringFilteringCommand).getStdout().trim(); try { if (dateStr.isEmpty() && logFile.endsWith("boot.log")) { // done for managing that boot.log information are put in server.log since EAP 6.1 and boot.log no longer exists return getStartupTime(logFile.replace("boot.log", "server.log")); } else { return sdfServerLog.parse(dateStr); } } catch (ParseException e) { throw new RuntimeException("Unable to determine server startup time", e); } } }
true
true
public Date getStartupTime(String logFile) { String dateStringFilteringCommand = ""; if (logFile.endsWith("server.log")) { dateStringFilteringCommand += "grep '\\[org\\.jboss\\.modules\\]' " +asHome+"/"+logFile +" | tail -n -1 | awk -F , '{print $1}'"; } else { dateStringFilteringCommand += "head -n1 "+asHome+"/"+logFile+" | awk -F, '{print $1}' "; } String dateStr = runAndWait(dateStringFilteringCommand).getStdout().trim(); try { if (dateStr.isEmpty() && logFile.endsWith("boot.log")) { // done for managing that boot.log information are put in server.log since EAP 6.1 and boot.log no longer exists return getStartupTime(logFile.replace("boot.log", "server.log")); } else { return sdfServerLog.parse(dateStr); } } catch (ParseException e) { throw new RuntimeException("Unable to determine server startup time", e); } }
public Date getStartupTime(String logFile) { String dateStringFilteringCommand = ""; if (logFile.endsWith("server.log")) { dateStringFilteringCommand += "grep '\\[org\\.jboss\\.modules\\]' " +asHome+"/"+logFile +" | tail -1 | awk -F , '{print $1}'"; } else { dateStringFilteringCommand += "head -n1 "+asHome+"/"+logFile+" | awk -F, '{print $1}' "; } String dateStr = runAndWait(dateStringFilteringCommand).getStdout().trim(); try { if (dateStr.isEmpty() && logFile.endsWith("boot.log")) { // done for managing that boot.log information are put in server.log since EAP 6.1 and boot.log no longer exists return getStartupTime(logFile.replace("boot.log", "server.log")); } else { return sdfServerLog.parse(dateStr); } } catch (ParseException e) { throw new RuntimeException("Unable to determine server startup time", e); } }
diff --git a/src/main/java/hu/sztaki/ilab/longneck/dns/ReverseDns.java b/src/main/java/hu/sztaki/ilab/longneck/dns/ReverseDns.java index 14f631a..b0c7dd3 100644 --- a/src/main/java/hu/sztaki/ilab/longneck/dns/ReverseDns.java +++ b/src/main/java/hu/sztaki/ilab/longneck/dns/ReverseDns.java @@ -1,151 +1,151 @@ package hu.sztaki.ilab.longneck.dns; import hu.sztaki.ilab.longneck.Record; import hu.sztaki.ilab.longneck.dns.db.DnsCache; import hu.sztaki.ilab.longneck.dns.db.LookupResult; import hu.sztaki.ilab.longneck.dns.db.ReverseData; import hu.sztaki.ilab.longneck.process.AbstractSourceInfoContainer; import hu.sztaki.ilab.longneck.process.CheckError; import hu.sztaki.ilab.longneck.process.VariableSpace; import hu.sztaki.ilab.longneck.process.block.Block; import hu.sztaki.ilab.longneck.process.block.BlockUtils; import hu.sztaki.ilab.longneck.process.constraint.CheckResult; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import org.apache.log4j.Logger; /** * Reverse DNS lookup block. * * @author Bendig Loránd <[email protected]> * @author Molnár Péter <[email protected]> * */ public class ReverseDns extends AbstractSourceInfoContainer implements Block { /** The log. */ private final Logger LOG = Logger.getLogger(ReverseDns.class); /** field names */ private static String IPFIELD = "ipAddress" ; private static String HOSTNAMEFIELD = "domainName" ; private static String EXPIRYFIELD = "lookupExpiry" ; /** The date format used to output expiration date. */ private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z", Locale.ENGLISH); /** The ip address field in dotted-quad format. */ private String ipAddress; /** The domain name which is resolved to an ip address. */ private String domainTo; /** The expiration date of the resolved ip address. */ private String expirationDateTo; /** Lookup service factory. */ private LookupServiceFactory lookupServiceFactory; /** Lookup service for dns queries. */ private LookupService lookupService = null; /** Cache of dns query results. */ private DnsCache dnsCache; @Override public void apply(final Record record, VariableSpace variables) throws CheckError { // Get thread-local lookup service if (lookupService == null) { lookupService = lookupServiceFactory.getLookupService(); } try { String ipAddr = BlockUtils.getValue(IPFIELD, record, variables); if (ipAddr == null || "".equals(ipAddr)) { LOG.warn("IP address (to be reverse resolved) is null or empty."); throw new CheckError(new CheckResult(this, false, ipAddress, ipAddr, "Cannot resolve empty ip address.")); } // Query from cache ReverseData reverseData = dnsCache.getReverse(ipAddr); // Check result and do a dns lookup if necessary if (reverseData == null || Calendar.getInstance().getTimeInMillis() > reverseData.getExpirationDate()) { reverseData = lookupService.getReverseDns(ipAddr); // Check returned value if (reverseData != null) { dnsCache.add(reverseData); } } if (reverseData != null && LookupResult.OK.equals(reverseData.getResult())) { BlockUtils.setValue(HOSTNAMEFIELD, reverseData.getDomain(), record, variables); BlockUtils.setValue(EXPIRYFIELD, dateFormat.format(new Date(reverseData.getExpirationDate())), record, variables); } // it is considered to be normal, if reverse lookup fails (no hostname) } catch (RuntimeException ex) { - LOG.error("Critical dns lookup error.", ex); + LOG.error("DNS lookup failed.", ex); } } @Override public ReverseDns clone() { return (ReverseDns) super.clone(); } public String getIpAddress() { return ipAddress; } public void setIpAddress(String ipAddress) { this.ipAddress = ipAddress; } public String getDomainTo() { return domainTo; } public void setDomainTo(String domainTo) { this.domainTo = domainTo; } public String getExpirationDateTo() { return expirationDateTo; } public void setExpirationDateTo(String expirationDateTo) { this.expirationDateTo = expirationDateTo; } public LookupServiceFactory getLookupServiceFactory() { return lookupServiceFactory; } public void setLookupServiceFactory(LookupServiceFactory lookupServiceFactory) { this.lookupServiceFactory = lookupServiceFactory; } public LookupService getLookupService() { return lookupService; } public void setLookupService(LookupService lookupService) { this.lookupService = lookupService; } public DnsCache getDnsCache() { return dnsCache; } public void setDnsCache(DnsCache dnsCache) { this.dnsCache = dnsCache; } }
true
true
public void apply(final Record record, VariableSpace variables) throws CheckError { // Get thread-local lookup service if (lookupService == null) { lookupService = lookupServiceFactory.getLookupService(); } try { String ipAddr = BlockUtils.getValue(IPFIELD, record, variables); if (ipAddr == null || "".equals(ipAddr)) { LOG.warn("IP address (to be reverse resolved) is null or empty."); throw new CheckError(new CheckResult(this, false, ipAddress, ipAddr, "Cannot resolve empty ip address.")); } // Query from cache ReverseData reverseData = dnsCache.getReverse(ipAddr); // Check result and do a dns lookup if necessary if (reverseData == null || Calendar.getInstance().getTimeInMillis() > reverseData.getExpirationDate()) { reverseData = lookupService.getReverseDns(ipAddr); // Check returned value if (reverseData != null) { dnsCache.add(reverseData); } } if (reverseData != null && LookupResult.OK.equals(reverseData.getResult())) { BlockUtils.setValue(HOSTNAMEFIELD, reverseData.getDomain(), record, variables); BlockUtils.setValue(EXPIRYFIELD, dateFormat.format(new Date(reverseData.getExpirationDate())), record, variables); } // it is considered to be normal, if reverse lookup fails (no hostname) } catch (RuntimeException ex) { LOG.error("Critical dns lookup error.", ex); } }
public void apply(final Record record, VariableSpace variables) throws CheckError { // Get thread-local lookup service if (lookupService == null) { lookupService = lookupServiceFactory.getLookupService(); } try { String ipAddr = BlockUtils.getValue(IPFIELD, record, variables); if (ipAddr == null || "".equals(ipAddr)) { LOG.warn("IP address (to be reverse resolved) is null or empty."); throw new CheckError(new CheckResult(this, false, ipAddress, ipAddr, "Cannot resolve empty ip address.")); } // Query from cache ReverseData reverseData = dnsCache.getReverse(ipAddr); // Check result and do a dns lookup if necessary if (reverseData == null || Calendar.getInstance().getTimeInMillis() > reverseData.getExpirationDate()) { reverseData = lookupService.getReverseDns(ipAddr); // Check returned value if (reverseData != null) { dnsCache.add(reverseData); } } if (reverseData != null && LookupResult.OK.equals(reverseData.getResult())) { BlockUtils.setValue(HOSTNAMEFIELD, reverseData.getDomain(), record, variables); BlockUtils.setValue(EXPIRYFIELD, dateFormat.format(new Date(reverseData.getExpirationDate())), record, variables); } // it is considered to be normal, if reverse lookup fails (no hostname) } catch (RuntimeException ex) { LOG.error("DNS lookup failed.", ex); } }
diff --git a/src/main/java/edu/uci/ics/crawler4j/fetcher/PageFetcher.java b/src/main/java/edu/uci/ics/crawler4j/fetcher/PageFetcher.java index 5f43f4b..d3866ec 100644 --- a/src/main/java/edu/uci/ics/crawler4j/fetcher/PageFetcher.java +++ b/src/main/java/edu/uci/ics/crawler4j/fetcher/PageFetcher.java @@ -1,295 +1,295 @@ /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.crawler4j.fetcher; import edu.uci.ics.crawler4j.crawler.Configurable; import edu.uci.ics.crawler4j.crawler.CrawlConfig; import edu.uci.ics.crawler4j.url.URLCanonicalizer; import edu.uci.ics.crawler4j.url.WebURL; import org.apache.http.*; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CookieStore; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.params.ClientPNames; import org.apache.http.client.params.CookiePolicy; import org.apache.http.client.protocol.ClientContext; import org.apache.http.conn.params.ConnRoutePNames; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.entity.HttpEntityWrapper; import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.PoolingClientConnectionManager; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.CoreConnectionPNames; import org.apache.http.params.CoreProtocolPNames; import org.apache.http.params.HttpParams; import org.apache.http.params.HttpProtocolParamBean; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HttpContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.util.Date; import java.util.zip.GZIPInputStream; /** * @author Yasser Ganjisaffar <lastname at gmail dot com> */ public class PageFetcher extends Configurable { protected static final Logger logger = LoggerFactory.getLogger(PageFetcher.class); protected PoolingClientConnectionManager connectionManager; protected DefaultHttpClient httpClient; protected final Object mutex = new Object(); protected long lastFetchTime = 0; protected IdleConnectionMonitorThread connectionMonitorThread = null; public PageFetcher(CrawlConfig config) { super(config); HttpParams params = new BasicHttpParams(); HttpProtocolParamBean paramsBean = new HttpProtocolParamBean(params); paramsBean.setVersion(HttpVersion.HTTP_1_1); paramsBean.setContentCharset("UTF-8"); paramsBean.setUseExpectContinue(false); params.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); params.setParameter(CoreProtocolPNames.USER_AGENT, config.getUserAgentString()); params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, config.getSocketTimeout()); params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, config.getConnectionTimeout()); // FIX for #136 - JVM crash while running crawler on Cent OS 6.2 - http://code.google.com/p/crawler4j/issues/detail?id=136 params.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); params.setBooleanParameter("http.protocol.handle-redirects", false); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); if (config.isIncludeHttpsPages()) { schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory())); } connectionManager = new PoolingClientConnectionManager(schemeRegistry); connectionManager.setMaxTotal(config.getMaxTotalConnections()); connectionManager.setDefaultMaxPerRoute(config.getMaxConnectionsPerHost()); httpClient = new DefaultHttpClient(connectionManager, params); if (config.getProxyHost() != null) { if (config.getProxyUsername() != null) { httpClient.getCredentialsProvider().setCredentials( new AuthScope(config.getProxyHost(), config.getProxyPort()), new UsernamePasswordCredentials(config.getProxyUsername(), config.getProxyPassword())); } HttpHost proxy = new HttpHost(config.getProxyHost(), config.getProxyPort()); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } httpClient.addResponseInterceptor(new HttpResponseInterceptor() { @Override public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { HttpEntity entity = response.getEntity(); if (entity == null) return; Header contentEncoding = entity.getContentEncoding(); if (contentEncoding != null) { HeaderElement[] codecs = contentEncoding.getElements(); for (HeaderElement codec : codecs) { if (codec.getName().equalsIgnoreCase("gzip")) { response.setEntity(new GzipDecompressingEntity(response.getEntity())); return; } } } } }); if (connectionMonitorThread == null) { connectionMonitorThread = new IdleConnectionMonitorThread(connectionManager); } connectionMonitorThread.start(); } public PageFetchResult fetchHeader(WebURL webUrl) { PageFetchResult fetchResult = new PageFetchResult(); String toFetchURL = webUrl.getURL(); HttpGet get = null; try { get = new HttpGet(toFetchURL); synchronized (mutex) { long now = (new Date()).getTime(); if (now - lastFetchTime < config.getPolitenessDelay()) { Thread.sleep(config.getPolitenessDelay() - (now - lastFetchTime)); } lastFetchTime = (new Date()).getTime(); } get.addHeader("Accept-Encoding", "gzip"); get.addHeader("Accept", "*/*"); for (final String header: config.getCustomHeaders()) { String name = header.split(":")[0]; String value = header.split(":")[1]; get.addHeader(name, value); } // Create a local instance of cookie store, and bind to local context // Without this we get killed w/lots of threads, due to sync() on single cookie store. HttpContext localContext = new BasicHttpContext(); CookieStore cookieStore = new BasicCookieStore(); localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); HttpResponse response = httpClient.execute(get); fetchResult.setEntity(response.getEntity()); fetchResult.setResponseHeaders(response.getAllHeaders()); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { if (statusCode != HttpStatus.SC_NOT_FOUND) { if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) { Header header = response.getFirstHeader("Location"); if (header != null) { String movedToUrl = header.getValue(); movedToUrl = URLCanonicalizer.getCanonicalURL(movedToUrl, toFetchURL); fetchResult.setMovedToUrl(movedToUrl); } fetchResult.setStatusCode(statusCode); return fetchResult; } logger.info("Failed: " + response.getStatusLine().toString() + ", while fetching " + toFetchURL); } fetchResult.setStatusCode(response.getStatusLine().getStatusCode()); return fetchResult; } fetchResult.setFetchedUrl(toFetchURL); String uri = get.getURI().toString(); if (!uri.equals(toFetchURL)) { if (!URLCanonicalizer.getCanonicalURL(uri).equals(toFetchURL)) { fetchResult.setFetchedUrl(uri); } } if (fetchResult.getEntity() != null) { long size = fetchResult.getEntity().getContentLength(); if (size == -1) { Header length = response.getLastHeader("Content-Length"); if (length == null) { length = response.getLastHeader("Content-length"); } if (length != null) { size = Integer.parseInt(length.getValue()); } else { size = -1; } } if (size > config.getMaxDownloadSize()) { fetchResult.setStatusCode(CustomFetchStatus.PageTooBig); get.abort(); logger.error("Failed: Page Size (" + size + ") exceeded max-download-size (" + config.getMaxDownloadSize() + ")"); return fetchResult; } fetchResult.setStatusCode(HttpStatus.SC_OK); return fetchResult; } get.abort(); } catch (IOException e) { logger.error("Fatal transport error: " + e.getMessage() + " while fetching " + toFetchURL + " (link found in doc #" + webUrl.getParentDocid() + ")"); fetchResult.setStatusCode(CustomFetchStatus.FatalTransportError); return fetchResult; } catch (IllegalStateException e) { // ignoring exceptions that occur because of not registering https // and other schemes } catch (Exception e) { if (e.getMessage() == null) { logger.error("Error while fetching " + webUrl.getURL(), e); } else { logger.error(e.getMessage() + " while fetching " + webUrl.getURL()); } } finally { try { if (fetchResult.getEntity() == null && get != null) { get.abort(); + logger.error("Failed: To extract HTTP entity, from the fetched page result " + webUrl.getURL()); } - logger.error("Failed: To extract HTTP entity, from the fetched page result " + webUrl.getURL()); } catch (Exception e) { e.printStackTrace(); } } fetchResult.setStatusCode(CustomFetchStatus.UnknownError); logger.error("Failed: Unknown error occurred., while fetching " + webUrl.getURL()); return fetchResult; } public synchronized void shutDown() { if (connectionMonitorThread != null) { connectionManager.shutdown(); connectionMonitorThread.shutdown(); } } public HttpClient getHttpClient() { return httpClient; } private static class GzipDecompressingEntity extends HttpEntityWrapper { public GzipDecompressingEntity(final HttpEntity entity) { super(entity); } @Override public InputStream getContent() throws IOException, IllegalStateException { // the wrapped entity's getContent() decides about repeatability InputStream wrappedin = wrappedEntity.getContent(); return new GZIPInputStream(wrappedin); } @Override public long getContentLength() { // length of ungzipped content is not known return -1; } } }
false
true
public PageFetchResult fetchHeader(WebURL webUrl) { PageFetchResult fetchResult = new PageFetchResult(); String toFetchURL = webUrl.getURL(); HttpGet get = null; try { get = new HttpGet(toFetchURL); synchronized (mutex) { long now = (new Date()).getTime(); if (now - lastFetchTime < config.getPolitenessDelay()) { Thread.sleep(config.getPolitenessDelay() - (now - lastFetchTime)); } lastFetchTime = (new Date()).getTime(); } get.addHeader("Accept-Encoding", "gzip"); get.addHeader("Accept", "*/*"); for (final String header: config.getCustomHeaders()) { String name = header.split(":")[0]; String value = header.split(":")[1]; get.addHeader(name, value); } // Create a local instance of cookie store, and bind to local context // Without this we get killed w/lots of threads, due to sync() on single cookie store. HttpContext localContext = new BasicHttpContext(); CookieStore cookieStore = new BasicCookieStore(); localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); HttpResponse response = httpClient.execute(get); fetchResult.setEntity(response.getEntity()); fetchResult.setResponseHeaders(response.getAllHeaders()); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { if (statusCode != HttpStatus.SC_NOT_FOUND) { if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) { Header header = response.getFirstHeader("Location"); if (header != null) { String movedToUrl = header.getValue(); movedToUrl = URLCanonicalizer.getCanonicalURL(movedToUrl, toFetchURL); fetchResult.setMovedToUrl(movedToUrl); } fetchResult.setStatusCode(statusCode); return fetchResult; } logger.info("Failed: " + response.getStatusLine().toString() + ", while fetching " + toFetchURL); } fetchResult.setStatusCode(response.getStatusLine().getStatusCode()); return fetchResult; } fetchResult.setFetchedUrl(toFetchURL); String uri = get.getURI().toString(); if (!uri.equals(toFetchURL)) { if (!URLCanonicalizer.getCanonicalURL(uri).equals(toFetchURL)) { fetchResult.setFetchedUrl(uri); } } if (fetchResult.getEntity() != null) { long size = fetchResult.getEntity().getContentLength(); if (size == -1) { Header length = response.getLastHeader("Content-Length"); if (length == null) { length = response.getLastHeader("Content-length"); } if (length != null) { size = Integer.parseInt(length.getValue()); } else { size = -1; } } if (size > config.getMaxDownloadSize()) { fetchResult.setStatusCode(CustomFetchStatus.PageTooBig); get.abort(); logger.error("Failed: Page Size (" + size + ") exceeded max-download-size (" + config.getMaxDownloadSize() + ")"); return fetchResult; } fetchResult.setStatusCode(HttpStatus.SC_OK); return fetchResult; } get.abort(); } catch (IOException e) { logger.error("Fatal transport error: " + e.getMessage() + " while fetching " + toFetchURL + " (link found in doc #" + webUrl.getParentDocid() + ")"); fetchResult.setStatusCode(CustomFetchStatus.FatalTransportError); return fetchResult; } catch (IllegalStateException e) { // ignoring exceptions that occur because of not registering https // and other schemes } catch (Exception e) { if (e.getMessage() == null) { logger.error("Error while fetching " + webUrl.getURL(), e); } else { logger.error(e.getMessage() + " while fetching " + webUrl.getURL()); } } finally { try { if (fetchResult.getEntity() == null && get != null) { get.abort(); } logger.error("Failed: To extract HTTP entity, from the fetched page result " + webUrl.getURL()); } catch (Exception e) { e.printStackTrace(); } } fetchResult.setStatusCode(CustomFetchStatus.UnknownError); logger.error("Failed: Unknown error occurred., while fetching " + webUrl.getURL()); return fetchResult; }
public PageFetchResult fetchHeader(WebURL webUrl) { PageFetchResult fetchResult = new PageFetchResult(); String toFetchURL = webUrl.getURL(); HttpGet get = null; try { get = new HttpGet(toFetchURL); synchronized (mutex) { long now = (new Date()).getTime(); if (now - lastFetchTime < config.getPolitenessDelay()) { Thread.sleep(config.getPolitenessDelay() - (now - lastFetchTime)); } lastFetchTime = (new Date()).getTime(); } get.addHeader("Accept-Encoding", "gzip"); get.addHeader("Accept", "*/*"); for (final String header: config.getCustomHeaders()) { String name = header.split(":")[0]; String value = header.split(":")[1]; get.addHeader(name, value); } // Create a local instance of cookie store, and bind to local context // Without this we get killed w/lots of threads, due to sync() on single cookie store. HttpContext localContext = new BasicHttpContext(); CookieStore cookieStore = new BasicCookieStore(); localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); HttpResponse response = httpClient.execute(get); fetchResult.setEntity(response.getEntity()); fetchResult.setResponseHeaders(response.getAllHeaders()); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { if (statusCode != HttpStatus.SC_NOT_FOUND) { if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) { Header header = response.getFirstHeader("Location"); if (header != null) { String movedToUrl = header.getValue(); movedToUrl = URLCanonicalizer.getCanonicalURL(movedToUrl, toFetchURL); fetchResult.setMovedToUrl(movedToUrl); } fetchResult.setStatusCode(statusCode); return fetchResult; } logger.info("Failed: " + response.getStatusLine().toString() + ", while fetching " + toFetchURL); } fetchResult.setStatusCode(response.getStatusLine().getStatusCode()); return fetchResult; } fetchResult.setFetchedUrl(toFetchURL); String uri = get.getURI().toString(); if (!uri.equals(toFetchURL)) { if (!URLCanonicalizer.getCanonicalURL(uri).equals(toFetchURL)) { fetchResult.setFetchedUrl(uri); } } if (fetchResult.getEntity() != null) { long size = fetchResult.getEntity().getContentLength(); if (size == -1) { Header length = response.getLastHeader("Content-Length"); if (length == null) { length = response.getLastHeader("Content-length"); } if (length != null) { size = Integer.parseInt(length.getValue()); } else { size = -1; } } if (size > config.getMaxDownloadSize()) { fetchResult.setStatusCode(CustomFetchStatus.PageTooBig); get.abort(); logger.error("Failed: Page Size (" + size + ") exceeded max-download-size (" + config.getMaxDownloadSize() + ")"); return fetchResult; } fetchResult.setStatusCode(HttpStatus.SC_OK); return fetchResult; } get.abort(); } catch (IOException e) { logger.error("Fatal transport error: " + e.getMessage() + " while fetching " + toFetchURL + " (link found in doc #" + webUrl.getParentDocid() + ")"); fetchResult.setStatusCode(CustomFetchStatus.FatalTransportError); return fetchResult; } catch (IllegalStateException e) { // ignoring exceptions that occur because of not registering https // and other schemes } catch (Exception e) { if (e.getMessage() == null) { logger.error("Error while fetching " + webUrl.getURL(), e); } else { logger.error(e.getMessage() + " while fetching " + webUrl.getURL()); } } finally { try { if (fetchResult.getEntity() == null && get != null) { get.abort(); logger.error("Failed: To extract HTTP entity, from the fetched page result " + webUrl.getURL()); } } catch (Exception e) { e.printStackTrace(); } } fetchResult.setStatusCode(CustomFetchStatus.UnknownError); logger.error("Failed: Unknown error occurred., while fetching " + webUrl.getURL()); return fetchResult; }
diff --git a/src/main/java/Commands/regalowl/hyperconomy/Browseshop.java b/src/main/java/Commands/regalowl/hyperconomy/Browseshop.java index e781357..34aca56 100644 --- a/src/main/java/Commands/regalowl/hyperconomy/Browseshop.java +++ b/src/main/java/Commands/regalowl/hyperconomy/Browseshop.java @@ -1,129 +1,129 @@ package regalowl.hyperconomy; import java.util.ArrayList; import java.util.Collections; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class Browseshop { Browseshop(String args[], CommandSender sender, Player player, String playerecon) { HyperConomy hc = HyperConomy.hc; ShopFactory s = hc.getShopFactory(); DataHandler sf = hc.getDataFunctions(); Calculation calc = hc.getCalculation(); LanguageFile L = hc.getLanguageFile(); ArrayList<String> aargs = new ArrayList<String>(); for (int i = 0; i < args.length; i++) { aargs.add(args[i]); } //try { boolean requireShop = hc.getConfig().getBoolean("config.limit-info-commands-to-shops"); if (player != null) { - if ((requireShop && s.inAnyShop(player)) && !player.hasPermission("hyperconomy.admin")) { + if ((requireShop && !s.inAnyShop(player)) && !player.hasPermission("hyperconomy.admin")) { sender.sendMessage(L.get("REQUIRE_SHOP_FOR_INFO")); return; } } if (aargs.size() > 3) { sender.sendMessage(L.get("BROWSE_SHOP_INVALID")); return; } boolean alphabetic = false; if (aargs.contains("-a") && aargs.size() >= 2) { alphabetic = true; aargs.remove("-a"); } int page; if (aargs.size() <= 2) { try { page = Integer.parseInt(aargs.get(0)); aargs.remove(0); } catch (Exception e) { try { page = Integer.parseInt(aargs.get(1)); aargs.remove(1); } catch (Exception f) { page = 1; } } } else { sender.sendMessage(L.get("BROWSE_SHOP_INVALID")); return; } String input = ""; if (aargs.size() == 1) { input = aargs.get(0); } else { sender.sendMessage(L.get("BROWSE_SHOP_INVALID")); return; } String nameshop = null; if (player != null) { - if (s.inAnyShop(player)) { + if (!s.inAnyShop(player)) { nameshop = null; } else { nameshop = s.getShop(player).getName(); } } ArrayList<String> names = sf.getNames(); ArrayList<String> rnames = new ArrayList<String>(); int i = 0; while(i < names.size()) { String cname = names.get(i); if (alphabetic) { if (cname.startsWith(input)) { String itemname = cname; if (nameshop == null || s.getShop(nameshop).has(itemname)) { rnames.add(cname); } } } else { if (cname.contains(input)) { String itemname = cname; if (nameshop == null || s.getShop(nameshop).has(itemname)) { rnames.add(cname); } } } i++; } Collections.sort(rnames, String.CASE_INSENSITIVE_ORDER); int numberpage = page * 10; int count = 0; int rsize = rnames.size(); double maxpages = rsize/10; maxpages = Math.ceil(maxpages); int maxpi = (int)maxpages + 1; sender.sendMessage(ChatColor.RED + L.get("PAGE") + " " + ChatColor.WHITE + "(" + ChatColor.RED + "" + page + ChatColor.WHITE + "/" + ChatColor.RED + "" + maxpi + ChatColor.WHITE + ")"); while (count < numberpage) { if (count > ((page * 10) - 11)) { if (count < rsize) { String iname = sf.fixName(rnames.get(count)); Double cost = 0.0; double stock = 0; HyperObject ho = sf.getHyperObject(iname, playerecon); if (sf.itemTest(iname)) { cost = ho.getCost(1); double taxpaid = ho.getPurchaseTax(cost); cost = calc.twoDecimals(cost + taxpaid); stock = sf.getHyperObject(iname, playerecon).getStock(); } else if (sf.enchantTest(iname)) { cost = ho.getCost(EnchantmentClass.DIAMOND); cost = cost + ho.getPurchaseTax(cost); stock = sf.getHyperObject(iname, playerecon).getStock(); } sender.sendMessage("\u00A7b" + iname + " \u00A79[\u00A7a" + stock + " \u00A79" + L.get("AVAILABLE") + ": \u00A7a" + L.get("CURRENCY") + cost + " \u00A79" + L.get("EACH") + ".]"); } else { sender.sendMessage(L.get("REACHED_END")); break; } } count++; } //} catch (Exception e) { // sender.sendMessage(L.get("BROWSE_SHOP_INVALID")); //} } }
false
true
Browseshop(String args[], CommandSender sender, Player player, String playerecon) { HyperConomy hc = HyperConomy.hc; ShopFactory s = hc.getShopFactory(); DataHandler sf = hc.getDataFunctions(); Calculation calc = hc.getCalculation(); LanguageFile L = hc.getLanguageFile(); ArrayList<String> aargs = new ArrayList<String>(); for (int i = 0; i < args.length; i++) { aargs.add(args[i]); } //try { boolean requireShop = hc.getConfig().getBoolean("config.limit-info-commands-to-shops"); if (player != null) { if ((requireShop && s.inAnyShop(player)) && !player.hasPermission("hyperconomy.admin")) { sender.sendMessage(L.get("REQUIRE_SHOP_FOR_INFO")); return; } } if (aargs.size() > 3) { sender.sendMessage(L.get("BROWSE_SHOP_INVALID")); return; } boolean alphabetic = false; if (aargs.contains("-a") && aargs.size() >= 2) { alphabetic = true; aargs.remove("-a"); } int page; if (aargs.size() <= 2) { try { page = Integer.parseInt(aargs.get(0)); aargs.remove(0); } catch (Exception e) { try { page = Integer.parseInt(aargs.get(1)); aargs.remove(1); } catch (Exception f) { page = 1; } } } else { sender.sendMessage(L.get("BROWSE_SHOP_INVALID")); return; } String input = ""; if (aargs.size() == 1) { input = aargs.get(0); } else { sender.sendMessage(L.get("BROWSE_SHOP_INVALID")); return; } String nameshop = null; if (player != null) { if (s.inAnyShop(player)) { nameshop = null; } else { nameshop = s.getShop(player).getName(); } } ArrayList<String> names = sf.getNames(); ArrayList<String> rnames = new ArrayList<String>(); int i = 0; while(i < names.size()) { String cname = names.get(i); if (alphabetic) { if (cname.startsWith(input)) { String itemname = cname; if (nameshop == null || s.getShop(nameshop).has(itemname)) { rnames.add(cname); } } } else { if (cname.contains(input)) { String itemname = cname; if (nameshop == null || s.getShop(nameshop).has(itemname)) { rnames.add(cname); } } } i++; } Collections.sort(rnames, String.CASE_INSENSITIVE_ORDER); int numberpage = page * 10; int count = 0; int rsize = rnames.size(); double maxpages = rsize/10; maxpages = Math.ceil(maxpages); int maxpi = (int)maxpages + 1; sender.sendMessage(ChatColor.RED + L.get("PAGE") + " " + ChatColor.WHITE + "(" + ChatColor.RED + "" + page + ChatColor.WHITE + "/" + ChatColor.RED + "" + maxpi + ChatColor.WHITE + ")"); while (count < numberpage) { if (count > ((page * 10) - 11)) { if (count < rsize) { String iname = sf.fixName(rnames.get(count)); Double cost = 0.0; double stock = 0; HyperObject ho = sf.getHyperObject(iname, playerecon); if (sf.itemTest(iname)) { cost = ho.getCost(1); double taxpaid = ho.getPurchaseTax(cost); cost = calc.twoDecimals(cost + taxpaid); stock = sf.getHyperObject(iname, playerecon).getStock(); } else if (sf.enchantTest(iname)) { cost = ho.getCost(EnchantmentClass.DIAMOND); cost = cost + ho.getPurchaseTax(cost); stock = sf.getHyperObject(iname, playerecon).getStock(); } sender.sendMessage("\u00A7b" + iname + " \u00A79[\u00A7a" + stock + " \u00A79" + L.get("AVAILABLE") + ": \u00A7a" + L.get("CURRENCY") + cost + " \u00A79" + L.get("EACH") + ".]"); } else { sender.sendMessage(L.get("REACHED_END")); break; } } count++; } //} catch (Exception e) { // sender.sendMessage(L.get("BROWSE_SHOP_INVALID")); //} }
Browseshop(String args[], CommandSender sender, Player player, String playerecon) { HyperConomy hc = HyperConomy.hc; ShopFactory s = hc.getShopFactory(); DataHandler sf = hc.getDataFunctions(); Calculation calc = hc.getCalculation(); LanguageFile L = hc.getLanguageFile(); ArrayList<String> aargs = new ArrayList<String>(); for (int i = 0; i < args.length; i++) { aargs.add(args[i]); } //try { boolean requireShop = hc.getConfig().getBoolean("config.limit-info-commands-to-shops"); if (player != null) { if ((requireShop && !s.inAnyShop(player)) && !player.hasPermission("hyperconomy.admin")) { sender.sendMessage(L.get("REQUIRE_SHOP_FOR_INFO")); return; } } if (aargs.size() > 3) { sender.sendMessage(L.get("BROWSE_SHOP_INVALID")); return; } boolean alphabetic = false; if (aargs.contains("-a") && aargs.size() >= 2) { alphabetic = true; aargs.remove("-a"); } int page; if (aargs.size() <= 2) { try { page = Integer.parseInt(aargs.get(0)); aargs.remove(0); } catch (Exception e) { try { page = Integer.parseInt(aargs.get(1)); aargs.remove(1); } catch (Exception f) { page = 1; } } } else { sender.sendMessage(L.get("BROWSE_SHOP_INVALID")); return; } String input = ""; if (aargs.size() == 1) { input = aargs.get(0); } else { sender.sendMessage(L.get("BROWSE_SHOP_INVALID")); return; } String nameshop = null; if (player != null) { if (!s.inAnyShop(player)) { nameshop = null; } else { nameshop = s.getShop(player).getName(); } } ArrayList<String> names = sf.getNames(); ArrayList<String> rnames = new ArrayList<String>(); int i = 0; while(i < names.size()) { String cname = names.get(i); if (alphabetic) { if (cname.startsWith(input)) { String itemname = cname; if (nameshop == null || s.getShop(nameshop).has(itemname)) { rnames.add(cname); } } } else { if (cname.contains(input)) { String itemname = cname; if (nameshop == null || s.getShop(nameshop).has(itemname)) { rnames.add(cname); } } } i++; } Collections.sort(rnames, String.CASE_INSENSITIVE_ORDER); int numberpage = page * 10; int count = 0; int rsize = rnames.size(); double maxpages = rsize/10; maxpages = Math.ceil(maxpages); int maxpi = (int)maxpages + 1; sender.sendMessage(ChatColor.RED + L.get("PAGE") + " " + ChatColor.WHITE + "(" + ChatColor.RED + "" + page + ChatColor.WHITE + "/" + ChatColor.RED + "" + maxpi + ChatColor.WHITE + ")"); while (count < numberpage) { if (count > ((page * 10) - 11)) { if (count < rsize) { String iname = sf.fixName(rnames.get(count)); Double cost = 0.0; double stock = 0; HyperObject ho = sf.getHyperObject(iname, playerecon); if (sf.itemTest(iname)) { cost = ho.getCost(1); double taxpaid = ho.getPurchaseTax(cost); cost = calc.twoDecimals(cost + taxpaid); stock = sf.getHyperObject(iname, playerecon).getStock(); } else if (sf.enchantTest(iname)) { cost = ho.getCost(EnchantmentClass.DIAMOND); cost = cost + ho.getPurchaseTax(cost); stock = sf.getHyperObject(iname, playerecon).getStock(); } sender.sendMessage("\u00A7b" + iname + " \u00A79[\u00A7a" + stock + " \u00A79" + L.get("AVAILABLE") + ": \u00A7a" + L.get("CURRENCY") + cost + " \u00A79" + L.get("EACH") + ".]"); } else { sender.sendMessage(L.get("REACHED_END")); break; } } count++; } //} catch (Exception e) { // sender.sendMessage(L.get("BROWSE_SHOP_INVALID")); //} }
diff --git a/src/java/org/jdesktop/swingx/graphics/BlendComposite.java b/src/java/org/jdesktop/swingx/graphics/BlendComposite.java index f78286a9..c33859dd 100644 --- a/src/java/org/jdesktop/swingx/graphics/BlendComposite.java +++ b/src/java/org/jdesktop/swingx/graphics/BlendComposite.java @@ -1,818 +1,818 @@ /* * $Id$ * * Dual-licensed under LGPL (Sun and Romain Guy) and BSD (Romain Guy). * * Copyright 2005 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * Copyright (c) 2006 Romain Guy <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jdesktop.swingx.graphics; import java.awt.Composite; import java.awt.CompositeContext; import java.awt.RenderingHints; import java.awt.image.ColorModel; import java.awt.image.DataBuffer; import java.awt.image.DirectColorModel; import java.awt.image.Raster; import java.awt.image.WritableRaster; import java.awt.image.RasterFormatException; /** * <p>A blend composite defines the rule according to which a drawing primitive * (known as the source) is mixed with existing graphics (know as the * destination.)</p> * <p><code>BlendComposite</code> is an implementation of the * {@link java.awt.Composite} interface and must therefore be set as a state on * a {@link java.awt.Graphics2D} surface.</p> * <p>Please refer to {@link java.awt.Graphics2D#setComposite(java.awt.Composite)} * for more information on how to use this class with a graphics surface.</p> * <h2>Blending Modes</h2> * <p>This class offers a certain number of blending modes, or compositing * rules. These rules are inspired from graphics editing software packages, * like <em>Adobe Photoshop</em> or <em>The GIMP</em>.</p> * <p>Given the wide variety of implemented blending modes and the difficulty * to describe them with words, please refer to those tools to visually see * the result of these blending modes.</p> * <h2>Opacity</h2> * <p>Each blending mode has an associated opacity, defined as a float value * between 0.0 and 1.0. Changing the opacity controls the force with which the * compositing operation is applied. For instance, a composite with an opacity * of 0.0 will not draw the source onto the destination. With an opacity of * 1.0, the source will be fully drawn onto the destination, according to the * selected blending mode rule.</p> * <p>The opacity, or alpha value, is used by the composite instance to mutiply * the alpha value of each pixel of the source when being composited over the * destination.</p> * <h2>Creating a Blend Composite</h2> * <p>Blend composites can be created in various manners:</p> * <ul> * <li>Use one of the pre-defined instance. Example: * <code>BlendComposite.Average</code>.</li> * <li>Derive one of the pre-defined instances by calling * {@link #derive(float)} or {@link #derive(BlendingMode)}. Deriving allows * you to change either the opacity or the blending mode. Example: * <code>BlendComposite.Average.derive(0.5f)</code>.</li> * <li>Use a factory method: {@link #getInstance(BlendingMode)} or * {@link #getInstance(BlendingMode, float)}.</li> * </ul> * <h2>Implementation Caveat</h2> * <p>TThe blending mode <em>SoftLight</em> has not been implemented yet.</p> * * @see org.jdesktop.swingx.graphics.BlendComposite.BlendingMode * @see java.awt.Graphics2D * @see java.awt.Composite * @see java.awt.AlphaComposite * @author Romain Guy <[email protected]> */ public final class BlendComposite implements Composite { /** * <p>A blending mode defines the compositing rule of a * {@link org.jdesktop.swingx.graphics.BlendComposite}.</p> * * @author Romain Guy <[email protected]> */ public enum BlendingMode { AVERAGE, MULTIPLY, SCREEN, DARKEN, LIGHTEN, OVERLAY, HARD_LIGHT, SOFT_LIGHT, DIFFERENCE, NEGATION, EXCLUSION, COLOR_DODGE, INVERSE_COLOR_DODGE, SOFT_DODGE, COLOR_BURN, INVERSE_COLOR_BURN, SOFT_BURN, REFLECT, GLOW, FREEZE, HEAT, ADD, SUBTRACT, STAMP, RED, GREEN, BLUE, HUE, SATURATION, COLOR, LUMINOSITY } public static final BlendComposite Average = new BlendComposite(BlendingMode.AVERAGE); public static final BlendComposite Multiply = new BlendComposite(BlendingMode.MULTIPLY); public static final BlendComposite Screen = new BlendComposite(BlendingMode.SCREEN); public static final BlendComposite Darken = new BlendComposite(BlendingMode.DARKEN); public static final BlendComposite Lighten = new BlendComposite(BlendingMode.LIGHTEN); public static final BlendComposite Overlay = new BlendComposite(BlendingMode.OVERLAY); public static final BlendComposite HardLight = new BlendComposite(BlendingMode.HARD_LIGHT); public static final BlendComposite SoftLight = new BlendComposite(BlendingMode.SOFT_LIGHT); public static final BlendComposite Difference = new BlendComposite(BlendingMode.DIFFERENCE); public static final BlendComposite Negation = new BlendComposite(BlendingMode.NEGATION); public static final BlendComposite Exclusion = new BlendComposite(BlendingMode.EXCLUSION); public static final BlendComposite ColorDodge = new BlendComposite(BlendingMode.COLOR_DODGE); public static final BlendComposite InverseColorDodge = new BlendComposite(BlendingMode.INVERSE_COLOR_DODGE); public static final BlendComposite SoftDodge = new BlendComposite(BlendingMode.SOFT_DODGE); public static final BlendComposite ColorBurn = new BlendComposite(BlendingMode.COLOR_BURN); public static final BlendComposite InverseColorBurn = new BlendComposite(BlendingMode.INVERSE_COLOR_BURN); public static final BlendComposite SoftBurn = new BlendComposite(BlendingMode.SOFT_BURN); public static final BlendComposite Reflect = new BlendComposite(BlendingMode.REFLECT); public static final BlendComposite Glow = new BlendComposite(BlendingMode.GLOW); public static final BlendComposite Freeze = new BlendComposite(BlendingMode.FREEZE); public static final BlendComposite Heat = new BlendComposite(BlendingMode.HEAT); public static final BlendComposite Add = new BlendComposite(BlendingMode.ADD); public static final BlendComposite Subtract = new BlendComposite(BlendingMode.SUBTRACT); public static final BlendComposite Stamp = new BlendComposite(BlendingMode.STAMP); public static final BlendComposite Red = new BlendComposite(BlendingMode.RED); public static final BlendComposite Green = new BlendComposite(BlendingMode.GREEN); public static final BlendComposite Blue = new BlendComposite(BlendingMode.BLUE); public static final BlendComposite Hue = new BlendComposite(BlendingMode.HUE); public static final BlendComposite Saturation = new BlendComposite(BlendingMode.SATURATION); public static final BlendComposite Color = new BlendComposite(BlendingMode.COLOR); public static final BlendComposite Luminosity = new BlendComposite(BlendingMode.LUMINOSITY); private final float alpha; private final BlendingMode mode; private BlendComposite(BlendingMode mode) { this(mode, 1.0f); } private BlendComposite(BlendingMode mode, float alpha) { this.mode = mode; if (alpha < 0.0f || alpha > 1.0f) { throw new IllegalArgumentException( "alpha must be comprised between 0.0f and 1.0f"); } this.alpha = alpha; } /** * <p>Creates a new composite based on the blending mode passed * as a parameter. A default opacity of 1.0 is applied.</p> * * @param mode the blending mode defining the compositing rule * @return a new <code>BlendComposite</code> based on the selected blending * mode, with an opacity of 1.0 */ public static BlendComposite getInstance(BlendingMode mode) { return new BlendComposite(mode); } /** * <p>Creates a new composite based on the blending mode and opacity passed * as parameters. The opacity must be a value between 0.0 and 1.0.</p> * * @param mode the blending mode defining the compositing rule * @param alpha the constant alpha to be multiplied with the alpha of the * source. <code>alpha</code> must be a floating point between 0.0 and 1.0. * @throws IllegalArgumentException if the opacity is less than 0.0 or * greater than 1.0 * @return a new <code>BlendComposite</code> based on the selected blending * mode and opacity */ public static BlendComposite getInstance(BlendingMode mode, float alpha) { return new BlendComposite(mode, alpha); } /** * <p>Returns a <code>BlendComposite</code> object that uses the specified * blending mode and this object's alpha value. If the newly specified * blending mode is the same as this object's, this object is returned.</p> * * @param mode the blending mode defining the compositing rule * @return a <code>BlendComposite</code> object derived from this object, * that uses the specified blending mode */ public BlendComposite derive(BlendingMode mode) { return this.mode == mode ? this : new BlendComposite(mode, getAlpha()); } /** * <p>Returns a <code>BlendComposite</code> object that uses the specified * opacity, or alpha, and this object's blending mode. If the newly specified * opacity is the same as this object's, this object is returned.</p> * * @param alpha the constant alpha to be multiplied with the alpha of the * source. <code>alpha</code> must be a floating point between 0.0 and 1.0. * @throws IllegalArgumentException if the opacity is less than 0.0 or * greater than 1.0 * @return a <code>BlendComposite</code> object derived from this object, * that uses the specified blending mode */ public BlendComposite derive(float alpha) { return this.alpha == alpha ? this : new BlendComposite(getMode(), alpha); } /** * <p>Returns the opacity of this composite. If no opacity has been defined, * 1.0 is returned.</p> * * @return the alpha value, or opacity, of this object */ public float getAlpha() { return alpha; } /** * <p>Returns the blending mode of this composite.</p> * * @return the blending mode used by this object */ public BlendingMode getMode() { return mode; } /** * {@inheritDoc} */ @Override public int hashCode() { return Float.floatToIntBits(alpha) * 31 + mode.ordinal(); } /** * {@inheritDoc} */ @Override public boolean equals(Object obj) { if (!(obj instanceof BlendComposite)) { return false; } BlendComposite bc = (BlendComposite) obj; return mode == bc.mode && alpha == bc.alpha; } private static boolean isRgbColorModel(ColorModel cm) { if (cm instanceof DirectColorModel && cm.getTransferType() == DataBuffer.TYPE_INT) { DirectColorModel directCM = (DirectColorModel) cm; return directCM.getRedMask() == 0x00FF0000 && directCM.getGreenMask() == 0x0000FF00 && directCM.getBlueMask() == 0x000000FF && (directCM.getNumComponents() == 3 || directCM.getAlphaMask() == 0xFF000000); } return false; } private static boolean isBgrColorModel(ColorModel cm) { if (cm instanceof DirectColorModel && cm.getTransferType() == DataBuffer.TYPE_INT) { DirectColorModel directCM = (DirectColorModel) cm; return directCM.getRedMask() == 0x000000FF && directCM.getGreenMask() == 0x0000FF00 && directCM.getBlueMask() == 0x00FF0000 && (directCM.getNumComponents() == 3 || directCM.getAlphaMask() == 0xFF000000); } return false; } /** * {@inheritDoc} */ public CompositeContext createContext(ColorModel srcColorModel, ColorModel dstColorModel, RenderingHints hints) { if (isRgbColorModel(srcColorModel) && isRgbColorModel(dstColorModel)) { return new BlendingRgbContext(this); } else if (isBgrColorModel(srcColorModel) && isBgrColorModel(dstColorModel)) { return new BlendingBgrContext(this); } throw new RasterFormatException("Incompatible color models"); } private static abstract class BlendingContext implements CompositeContext { protected final Blender blender; protected final BlendComposite composite; private BlendingContext(BlendComposite composite) { this.composite = composite; this.blender = Blender.getBlenderFor(composite); } public void dispose() { } } private static class BlendingRgbContext extends BlendingContext { private BlendingRgbContext(BlendComposite composite) { super(composite); } public void compose(Raster src, Raster dstIn, WritableRaster dstOut) { int width = Math.min(src.getWidth(), dstIn.getWidth()); int height = Math.min(src.getHeight(), dstIn.getHeight()); float alpha = composite.getAlpha(); int[] result = new int[4]; int[] srcPixel = new int[4]; int[] dstPixel = new int[4]; int[] srcPixels = new int[width]; int[] dstPixels = new int[width]; for (int y = 0; y < height; y++) { src.getDataElements(0, y, width, 1, srcPixels); dstIn.getDataElements(0, y, width, 1, dstPixels); for (int x = 0; x < width; x++) { // pixels are stored as INT_ARGB // our arrays are [R, G, B, A] int pixel = srcPixels[x]; srcPixel[0] = (pixel >> 16) & 0xFF; srcPixel[1] = (pixel >> 8) & 0xFF; srcPixel[2] = (pixel ) & 0xFF; srcPixel[3] = (pixel >> 24) & 0xFF; pixel = dstPixels[x]; dstPixel[0] = (pixel >> 16) & 0xFF; dstPixel[1] = (pixel >> 8) & 0xFF; dstPixel[2] = (pixel ) & 0xFF; dstPixel[3] = (pixel >> 24) & 0xFF; blender.blend(srcPixel, dstPixel, result); // mixes the result with the opacity dstPixels[x] = ((int) (dstPixel[3] + (result[3] - dstPixel[3]) * alpha) & 0xFF) << 24 | ((int) (dstPixel[0] + (result[0] - dstPixel[0]) * alpha) & 0xFF) << 16 | ((int) (dstPixel[1] + (result[1] - dstPixel[1]) * alpha) & 0xFF) << 8 | (int) (dstPixel[2] + (result[2] - dstPixel[2]) * alpha) & 0xFF; } dstOut.setDataElements(0, y, width, 1, dstPixels); } } } private static class BlendingBgrContext extends BlendingContext { private BlendingBgrContext(BlendComposite composite) { super(composite); } public void compose(Raster src, Raster dstIn, WritableRaster dstOut) { int width = Math.min(src.getWidth(), dstIn.getWidth()); int height = Math.min(src.getHeight(), dstIn.getHeight()); float alpha = composite.getAlpha(); int[] result = new int[4]; int[] srcPixel = new int[4]; int[] dstPixel = new int[4]; int[] srcPixels = new int[width]; int[] dstPixels = new int[width]; for (int y = 0; y < height; y++) { src.getDataElements(0, y, width, 1, srcPixels); dstIn.getDataElements(0, y, width, 1, dstPixels); for (int x = 0; x < width; x++) { // pixels are stored as INT_ABGR // our arrays are [R, G, B, A] int pixel = srcPixels[x]; srcPixel[0] = (pixel ) & 0xFF; srcPixel[1] = (pixel >> 8) & 0xFF; srcPixel[2] = (pixel >> 16) & 0xFF; srcPixel[3] = (pixel >> 24) & 0xFF; pixel = dstPixels[x]; dstPixel[0] = (pixel ) & 0xFF; dstPixel[1] = (pixel >> 8) & 0xFF; dstPixel[2] = (pixel >> 16) & 0xFF; dstPixel[3] = (pixel >> 24) & 0xFF; blender.blend(srcPixel, dstPixel, result); // mixes the result with the opacity dstPixels[x] = ((int) (dstPixel[3] + (result[3] - dstPixel[3]) * alpha) & 0xFF) << 24 | ((int) (dstPixel[0] + (result[0] - dstPixel[0]) * alpha) & 0xFF) | ((int) (dstPixel[1] + (result[1] - dstPixel[1]) * alpha) & 0xFF) << 8 | ((int) (dstPixel[2] + (result[2] - dstPixel[2]) * alpha) & 0xFF) << 16; } dstOut.setDataElements(0, y, width, 1, dstPixels); } } } private static abstract class Blender { public abstract void blend(int[] src, int[] dst, int[] result); public static Blender getBlenderFor(BlendComposite composite) { switch (composite.getMode()) { case ADD: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = Math.min(255, src[0] + dst[0]); result[1] = Math.min(255, src[1] + dst[1]); result[2] = Math.min(255, src[2] + dst[2]); result[3] = Math.min(255, src[3] + dst[3]); } }; case AVERAGE: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = (src[0] + dst[0]) >> 1; result[1] = (src[1] + dst[1]) >> 1; result[2] = (src[2] + dst[2]) >> 1; result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case BLUE: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = dst[0]; result[1] = src[1]; result[2] = dst[2]; result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case COLOR: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { float[] srcHSL = new float[3]; ColorUtilities.RGBtoHSL(src[0], src[1], src[2], srcHSL); float[] dstHSL = new float[3]; ColorUtilities.RGBtoHSL(dst[0], dst[1], dst[2], dstHSL); - ColorUtilities.HSLtoRGB(dstHSL[0], dstHSL[1], srcHSL[2], result); + ColorUtilities.HSLtoRGB(srcHSL[0], srcHSL[1], dstHSL[2], result); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case COLOR_BURN: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = src[0] == 0 ? 0 : Math.max(0, 255 - (((255 - dst[0]) << 8) / src[0])); result[1] = src[1] == 0 ? 0 : Math.max(0, 255 - (((255 - dst[1]) << 8) / src[1])); result[2] = src[2] == 0 ? 0 : Math.max(0, 255 - (((255 - dst[2]) << 8) / src[2])); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case COLOR_DODGE: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = src[0] == 255 ? 255 : Math.min((dst[0] << 8) / (255 - src[0]), 255); result[1] = src[1] == 255 ? 255 : Math.min((dst[1] << 8) / (255 - src[1]), 255); result[2] = src[2] == 255 ? 255 : Math.min((dst[2] << 8) / (255 - src[2]), 255); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case DARKEN: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = Math.min(src[0], dst[0]); result[1] = Math.min(src[1], dst[1]); result[2] = Math.min(src[2], dst[2]); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case DIFFERENCE: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = Math.abs(dst[0] - src[0]); result[1] = Math.abs(dst[1] - src[1]); result[2] = Math.abs(dst[2] - src[2]); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case EXCLUSION: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = dst[0] + src[0] - (dst[0] * src[0] >> 7); result[1] = dst[1] + src[1] - (dst[1] * src[1] >> 7); result[2] = dst[2] + src[2] - (dst[2] * src[2] >> 7); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case FREEZE: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = src[0] == 0 ? 0 : Math.max(0, 255 - (255 - dst[0]) * (255 - dst[0]) / src[0]); result[1] = src[1] == 0 ? 0 : Math.max(0, 255 - (255 - dst[1]) * (255 - dst[1]) / src[1]); result[2] = src[2] == 0 ? 0 : Math.max(0, 255 - (255 - dst[2]) * (255 - dst[2]) / src[2]); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case GLOW: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = dst[0] == 255 ? 255 : Math.min(255, src[0] * src[0] / (255 - dst[0])); result[1] = dst[1] == 255 ? 255 : Math.min(255, src[1] * src[1] / (255 - dst[1])); result[2] = dst[2] == 255 ? 255 : Math.min(255, src[2] * src[2] / (255 - dst[2])); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case GREEN: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = dst[0]; result[1] = dst[1]; result[2] = src[2]; result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case HARD_LIGHT: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = src[0] < 128 ? dst[0] * src[0] >> 7 : 255 - ((255 - src[0]) * (255 - dst[0]) >> 7); result[1] = src[1] < 128 ? dst[1] * src[1] >> 7 : 255 - ((255 - src[1]) * (255 - dst[1]) >> 7); result[2] = src[2] < 128 ? dst[2] * src[2] >> 7 : 255 - ((255 - src[2]) * (255 - dst[2]) >> 7); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case HEAT: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = dst[0] == 0 ? 0 : Math.max(0, 255 - (255 - src[0]) * (255 - src[0]) / dst[0]); result[1] = dst[1] == 0 ? 0 : Math.max(0, 255 - (255 - src[1]) * (255 - src[1]) / dst[1]); result[2] = dst[2] == 0 ? 0 : Math.max(0, 255 - (255 - src[2]) * (255 - src[2]) / dst[2]); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case HUE: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { float[] srcHSL = new float[3]; ColorUtilities.RGBtoHSL(src[0], src[1], src[2], srcHSL); float[] dstHSL = new float[3]; ColorUtilities.RGBtoHSL(dst[0], dst[1], dst[2], dstHSL); ColorUtilities.HSLtoRGB(srcHSL[0], dstHSL[1], dstHSL[2], result); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case INVERSE_COLOR_BURN: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = dst[0] == 0 ? 0 : Math.max(0, 255 - (((255 - src[0]) << 8) / dst[0])); result[1] = dst[1] == 0 ? 0 : Math.max(0, 255 - (((255 - src[1]) << 8) / dst[1])); result[2] = dst[2] == 0 ? 0 : Math.max(0, 255 - (((255 - src[2]) << 8) / dst[2])); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case INVERSE_COLOR_DODGE: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = dst[0] == 255 ? 255 : Math.min((src[0] << 8) / (255 - dst[0]), 255); result[1] = dst[1] == 255 ? 255 : Math.min((src[1] << 8) / (255 - dst[1]), 255); result[2] = dst[2] == 255 ? 255 : Math.min((src[2] << 8) / (255 - dst[2]), 255); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case LIGHTEN: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = Math.max(src[0], dst[0]); result[1] = Math.max(src[1], dst[1]); result[2] = Math.max(src[2], dst[2]); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case LUMINOSITY: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { float[] srcHSL = new float[3]; ColorUtilities.RGBtoHSL(src[0], src[1], src[2], srcHSL); float[] dstHSL = new float[3]; ColorUtilities.RGBtoHSL(dst[0], dst[1], dst[2], dstHSL); ColorUtilities.HSLtoRGB(dstHSL[0], dstHSL[1], srcHSL[2], result); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case MULTIPLY: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = (src[0] * dst[0]) >> 8; result[1] = (src[1] * dst[1]) >> 8; result[2] = (src[2] * dst[2]) >> 8; result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case NEGATION: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = 255 - Math.abs(255 - dst[0] - src[0]); result[1] = 255 - Math.abs(255 - dst[1] - src[1]); result[2] = 255 - Math.abs(255 - dst[2] - src[2]); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case OVERLAY: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = dst[0] < 128 ? dst[0] * src[0] >> 7 : 255 - ((255 - dst[0]) * (255 - src[0]) >> 7); result[1] = dst[1] < 128 ? dst[1] * src[1] >> 7 : 255 - ((255 - dst[1]) * (255 - src[1]) >> 7); result[2] = dst[2] < 128 ? dst[2] * src[2] >> 7 : 255 - ((255 - dst[2]) * (255 - src[2]) >> 7); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case RED: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = src[0]; result[1] = dst[1]; result[2] = dst[2]; result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case REFLECT: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = src[0] == 255 ? 255 : Math.min(255, dst[0] * dst[0] / (255 - src[0])); result[1] = src[1] == 255 ? 255 : Math.min(255, dst[1] * dst[1] / (255 - src[1])); result[2] = src[2] == 255 ? 255 : Math.min(255, dst[2] * dst[2] / (255 - src[2])); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case SATURATION: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { float[] srcHSL = new float[3]; ColorUtilities.RGBtoHSL(src[0], src[1], src[2], srcHSL); float[] dstHSL = new float[3]; ColorUtilities.RGBtoHSL(dst[0], dst[1], dst[2], dstHSL); ColorUtilities.HSLtoRGB(dstHSL[0], srcHSL[1], dstHSL[2], result); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case SCREEN: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = 255 - ((255 - src[0]) * (255 - dst[0]) >> 8); result[1] = 255 - ((255 - src[1]) * (255 - dst[1]) >> 8); result[2] = 255 - ((255 - src[2]) * (255 - dst[2]) >> 8); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case SOFT_BURN: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = dst[0] + src[0] < 256 ? (dst[0] == 255 ? 255 : Math.min(255, (src[0] << 7) / (255 - dst[0]))) : Math.max(0, 255 - (((255 - dst[0]) << 7) / src[0])); result[1] = dst[1] + src[1] < 256 ? (dst[1] == 255 ? 255 : Math.min(255, (src[1] << 7) / (255 - dst[1]))) : Math.max(0, 255 - (((255 - dst[1]) << 7) / src[1])); result[2] = dst[2] + src[2] < 256 ? (dst[2] == 255 ? 255 : Math.min(255, (src[2] << 7) / (255 - dst[2]))) : Math.max(0, 255 - (((255 - dst[2]) << 7) / src[2])); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case SOFT_DODGE: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = dst[0] + src[0] < 256 ? (src[0] == 255 ? 255 : Math.min(255, (dst[0] << 7) / (255 - src[0]))) : Math.max(0, 255 - (((255 - src[0]) << 7) / dst[0])); result[1] = dst[1] + src[1] < 256 ? (src[1] == 255 ? 255 : Math.min(255, (dst[1] << 7) / (255 - src[1]))) : Math.max(0, 255 - (((255 - src[1]) << 7) / dst[1])); result[2] = dst[2] + src[2] < 256 ? (src[2] == 255 ? 255 : Math.min(255, (dst[2] << 7) / (255 - src[2]))) : Math.max(0, 255 - (((255 - src[2]) << 7) / dst[2])); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case SOFT_LIGHT: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { int mRed = src[0] * dst[0] / 255; int mGreen = src[1] * dst[1] / 255; int mBlue = src[2] * dst[2] / 255; result[0] = mRed + src[0] * (255 - ((255 - src[0]) * (255 - dst[0]) / 255) - mRed) / 255; result[1] = mGreen + src[1] * (255 - ((255 - src[1]) * (255 - dst[1]) / 255) - mGreen) / 255; result[2] = mBlue + src[2] * (255 - ((255 - src[2]) * (255 - dst[2]) / 255) - mBlue) / 255; result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case STAMP: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = Math.max(0, Math.min(255, dst[0] + 2 * src[0] - 256)); result[1] = Math.max(0, Math.min(255, dst[1] + 2 * src[1] - 256)); result[2] = Math.max(0, Math.min(255, dst[2] + 2 * src[2] - 256)); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case SUBTRACT: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = Math.max(0, src[0] + dst[0] - 256); result[1] = Math.max(0, src[1] + dst[1] - 256); result[2] = Math.max(0, src[2] + dst[2] - 256); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; } throw new IllegalArgumentException("Blender not implemented for " + composite.getMode().name()); } } }
true
true
public static Blender getBlenderFor(BlendComposite composite) { switch (composite.getMode()) { case ADD: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = Math.min(255, src[0] + dst[0]); result[1] = Math.min(255, src[1] + dst[1]); result[2] = Math.min(255, src[2] + dst[2]); result[3] = Math.min(255, src[3] + dst[3]); } }; case AVERAGE: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = (src[0] + dst[0]) >> 1; result[1] = (src[1] + dst[1]) >> 1; result[2] = (src[2] + dst[2]) >> 1; result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case BLUE: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = dst[0]; result[1] = src[1]; result[2] = dst[2]; result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case COLOR: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { float[] srcHSL = new float[3]; ColorUtilities.RGBtoHSL(src[0], src[1], src[2], srcHSL); float[] dstHSL = new float[3]; ColorUtilities.RGBtoHSL(dst[0], dst[1], dst[2], dstHSL); ColorUtilities.HSLtoRGB(dstHSL[0], dstHSL[1], srcHSL[2], result); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case COLOR_BURN: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = src[0] == 0 ? 0 : Math.max(0, 255 - (((255 - dst[0]) << 8) / src[0])); result[1] = src[1] == 0 ? 0 : Math.max(0, 255 - (((255 - dst[1]) << 8) / src[1])); result[2] = src[2] == 0 ? 0 : Math.max(0, 255 - (((255 - dst[2]) << 8) / src[2])); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case COLOR_DODGE: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = src[0] == 255 ? 255 : Math.min((dst[0] << 8) / (255 - src[0]), 255); result[1] = src[1] == 255 ? 255 : Math.min((dst[1] << 8) / (255 - src[1]), 255); result[2] = src[2] == 255 ? 255 : Math.min((dst[2] << 8) / (255 - src[2]), 255); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case DARKEN: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = Math.min(src[0], dst[0]); result[1] = Math.min(src[1], dst[1]); result[2] = Math.min(src[2], dst[2]); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case DIFFERENCE: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = Math.abs(dst[0] - src[0]); result[1] = Math.abs(dst[1] - src[1]); result[2] = Math.abs(dst[2] - src[2]); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case EXCLUSION: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = dst[0] + src[0] - (dst[0] * src[0] >> 7); result[1] = dst[1] + src[1] - (dst[1] * src[1] >> 7); result[2] = dst[2] + src[2] - (dst[2] * src[2] >> 7); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case FREEZE: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = src[0] == 0 ? 0 : Math.max(0, 255 - (255 - dst[0]) * (255 - dst[0]) / src[0]); result[1] = src[1] == 0 ? 0 : Math.max(0, 255 - (255 - dst[1]) * (255 - dst[1]) / src[1]); result[2] = src[2] == 0 ? 0 : Math.max(0, 255 - (255 - dst[2]) * (255 - dst[2]) / src[2]); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case GLOW: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = dst[0] == 255 ? 255 : Math.min(255, src[0] * src[0] / (255 - dst[0])); result[1] = dst[1] == 255 ? 255 : Math.min(255, src[1] * src[1] / (255 - dst[1])); result[2] = dst[2] == 255 ? 255 : Math.min(255, src[2] * src[2] / (255 - dst[2])); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case GREEN: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = dst[0]; result[1] = dst[1]; result[2] = src[2]; result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case HARD_LIGHT: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = src[0] < 128 ? dst[0] * src[0] >> 7 : 255 - ((255 - src[0]) * (255 - dst[0]) >> 7); result[1] = src[1] < 128 ? dst[1] * src[1] >> 7 : 255 - ((255 - src[1]) * (255 - dst[1]) >> 7); result[2] = src[2] < 128 ? dst[2] * src[2] >> 7 : 255 - ((255 - src[2]) * (255 - dst[2]) >> 7); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case HEAT: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = dst[0] == 0 ? 0 : Math.max(0, 255 - (255 - src[0]) * (255 - src[0]) / dst[0]); result[1] = dst[1] == 0 ? 0 : Math.max(0, 255 - (255 - src[1]) * (255 - src[1]) / dst[1]); result[2] = dst[2] == 0 ? 0 : Math.max(0, 255 - (255 - src[2]) * (255 - src[2]) / dst[2]); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case HUE: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { float[] srcHSL = new float[3]; ColorUtilities.RGBtoHSL(src[0], src[1], src[2], srcHSL); float[] dstHSL = new float[3]; ColorUtilities.RGBtoHSL(dst[0], dst[1], dst[2], dstHSL); ColorUtilities.HSLtoRGB(srcHSL[0], dstHSL[1], dstHSL[2], result); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case INVERSE_COLOR_BURN: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = dst[0] == 0 ? 0 : Math.max(0, 255 - (((255 - src[0]) << 8) / dst[0])); result[1] = dst[1] == 0 ? 0 : Math.max(0, 255 - (((255 - src[1]) << 8) / dst[1])); result[2] = dst[2] == 0 ? 0 : Math.max(0, 255 - (((255 - src[2]) << 8) / dst[2])); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case INVERSE_COLOR_DODGE: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = dst[0] == 255 ? 255 : Math.min((src[0] << 8) / (255 - dst[0]), 255); result[1] = dst[1] == 255 ? 255 : Math.min((src[1] << 8) / (255 - dst[1]), 255); result[2] = dst[2] == 255 ? 255 : Math.min((src[2] << 8) / (255 - dst[2]), 255); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case LIGHTEN: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = Math.max(src[0], dst[0]); result[1] = Math.max(src[1], dst[1]); result[2] = Math.max(src[2], dst[2]); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case LUMINOSITY: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { float[] srcHSL = new float[3]; ColorUtilities.RGBtoHSL(src[0], src[1], src[2], srcHSL); float[] dstHSL = new float[3]; ColorUtilities.RGBtoHSL(dst[0], dst[1], dst[2], dstHSL); ColorUtilities.HSLtoRGB(dstHSL[0], dstHSL[1], srcHSL[2], result); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case MULTIPLY: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = (src[0] * dst[0]) >> 8; result[1] = (src[1] * dst[1]) >> 8; result[2] = (src[2] * dst[2]) >> 8; result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case NEGATION: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = 255 - Math.abs(255 - dst[0] - src[0]); result[1] = 255 - Math.abs(255 - dst[1] - src[1]); result[2] = 255 - Math.abs(255 - dst[2] - src[2]); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case OVERLAY: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = dst[0] < 128 ? dst[0] * src[0] >> 7 : 255 - ((255 - dst[0]) * (255 - src[0]) >> 7); result[1] = dst[1] < 128 ? dst[1] * src[1] >> 7 : 255 - ((255 - dst[1]) * (255 - src[1]) >> 7); result[2] = dst[2] < 128 ? dst[2] * src[2] >> 7 : 255 - ((255 - dst[2]) * (255 - src[2]) >> 7); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case RED: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = src[0]; result[1] = dst[1]; result[2] = dst[2]; result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case REFLECT: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = src[0] == 255 ? 255 : Math.min(255, dst[0] * dst[0] / (255 - src[0])); result[1] = src[1] == 255 ? 255 : Math.min(255, dst[1] * dst[1] / (255 - src[1])); result[2] = src[2] == 255 ? 255 : Math.min(255, dst[2] * dst[2] / (255 - src[2])); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case SATURATION: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { float[] srcHSL = new float[3]; ColorUtilities.RGBtoHSL(src[0], src[1], src[2], srcHSL); float[] dstHSL = new float[3]; ColorUtilities.RGBtoHSL(dst[0], dst[1], dst[2], dstHSL); ColorUtilities.HSLtoRGB(dstHSL[0], srcHSL[1], dstHSL[2], result); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case SCREEN: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = 255 - ((255 - src[0]) * (255 - dst[0]) >> 8); result[1] = 255 - ((255 - src[1]) * (255 - dst[1]) >> 8); result[2] = 255 - ((255 - src[2]) * (255 - dst[2]) >> 8); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case SOFT_BURN: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = dst[0] + src[0] < 256 ? (dst[0] == 255 ? 255 : Math.min(255, (src[0] << 7) / (255 - dst[0]))) : Math.max(0, 255 - (((255 - dst[0]) << 7) / src[0])); result[1] = dst[1] + src[1] < 256 ? (dst[1] == 255 ? 255 : Math.min(255, (src[1] << 7) / (255 - dst[1]))) : Math.max(0, 255 - (((255 - dst[1]) << 7) / src[1])); result[2] = dst[2] + src[2] < 256 ? (dst[2] == 255 ? 255 : Math.min(255, (src[2] << 7) / (255 - dst[2]))) : Math.max(0, 255 - (((255 - dst[2]) << 7) / src[2])); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case SOFT_DODGE: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = dst[0] + src[0] < 256 ? (src[0] == 255 ? 255 : Math.min(255, (dst[0] << 7) / (255 - src[0]))) : Math.max(0, 255 - (((255 - src[0]) << 7) / dst[0])); result[1] = dst[1] + src[1] < 256 ? (src[1] == 255 ? 255 : Math.min(255, (dst[1] << 7) / (255 - src[1]))) : Math.max(0, 255 - (((255 - src[1]) << 7) / dst[1])); result[2] = dst[2] + src[2] < 256 ? (src[2] == 255 ? 255 : Math.min(255, (dst[2] << 7) / (255 - src[2]))) : Math.max(0, 255 - (((255 - src[2]) << 7) / dst[2])); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case SOFT_LIGHT: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { int mRed = src[0] * dst[0] / 255; int mGreen = src[1] * dst[1] / 255; int mBlue = src[2] * dst[2] / 255; result[0] = mRed + src[0] * (255 - ((255 - src[0]) * (255 - dst[0]) / 255) - mRed) / 255; result[1] = mGreen + src[1] * (255 - ((255 - src[1]) * (255 - dst[1]) / 255) - mGreen) / 255; result[2] = mBlue + src[2] * (255 - ((255 - src[2]) * (255 - dst[2]) / 255) - mBlue) / 255; result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case STAMP: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = Math.max(0, Math.min(255, dst[0] + 2 * src[0] - 256)); result[1] = Math.max(0, Math.min(255, dst[1] + 2 * src[1] - 256)); result[2] = Math.max(0, Math.min(255, dst[2] + 2 * src[2] - 256)); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case SUBTRACT: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = Math.max(0, src[0] + dst[0] - 256); result[1] = Math.max(0, src[1] + dst[1] - 256); result[2] = Math.max(0, src[2] + dst[2] - 256); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; } throw new IllegalArgumentException("Blender not implemented for " + composite.getMode().name()); }
public static Blender getBlenderFor(BlendComposite composite) { switch (composite.getMode()) { case ADD: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = Math.min(255, src[0] + dst[0]); result[1] = Math.min(255, src[1] + dst[1]); result[2] = Math.min(255, src[2] + dst[2]); result[3] = Math.min(255, src[3] + dst[3]); } }; case AVERAGE: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = (src[0] + dst[0]) >> 1; result[1] = (src[1] + dst[1]) >> 1; result[2] = (src[2] + dst[2]) >> 1; result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case BLUE: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = dst[0]; result[1] = src[1]; result[2] = dst[2]; result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case COLOR: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { float[] srcHSL = new float[3]; ColorUtilities.RGBtoHSL(src[0], src[1], src[2], srcHSL); float[] dstHSL = new float[3]; ColorUtilities.RGBtoHSL(dst[0], dst[1], dst[2], dstHSL); ColorUtilities.HSLtoRGB(srcHSL[0], srcHSL[1], dstHSL[2], result); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case COLOR_BURN: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = src[0] == 0 ? 0 : Math.max(0, 255 - (((255 - dst[0]) << 8) / src[0])); result[1] = src[1] == 0 ? 0 : Math.max(0, 255 - (((255 - dst[1]) << 8) / src[1])); result[2] = src[2] == 0 ? 0 : Math.max(0, 255 - (((255 - dst[2]) << 8) / src[2])); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case COLOR_DODGE: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = src[0] == 255 ? 255 : Math.min((dst[0] << 8) / (255 - src[0]), 255); result[1] = src[1] == 255 ? 255 : Math.min((dst[1] << 8) / (255 - src[1]), 255); result[2] = src[2] == 255 ? 255 : Math.min((dst[2] << 8) / (255 - src[2]), 255); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case DARKEN: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = Math.min(src[0], dst[0]); result[1] = Math.min(src[1], dst[1]); result[2] = Math.min(src[2], dst[2]); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case DIFFERENCE: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = Math.abs(dst[0] - src[0]); result[1] = Math.abs(dst[1] - src[1]); result[2] = Math.abs(dst[2] - src[2]); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case EXCLUSION: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = dst[0] + src[0] - (dst[0] * src[0] >> 7); result[1] = dst[1] + src[1] - (dst[1] * src[1] >> 7); result[2] = dst[2] + src[2] - (dst[2] * src[2] >> 7); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case FREEZE: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = src[0] == 0 ? 0 : Math.max(0, 255 - (255 - dst[0]) * (255 - dst[0]) / src[0]); result[1] = src[1] == 0 ? 0 : Math.max(0, 255 - (255 - dst[1]) * (255 - dst[1]) / src[1]); result[2] = src[2] == 0 ? 0 : Math.max(0, 255 - (255 - dst[2]) * (255 - dst[2]) / src[2]); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case GLOW: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = dst[0] == 255 ? 255 : Math.min(255, src[0] * src[0] / (255 - dst[0])); result[1] = dst[1] == 255 ? 255 : Math.min(255, src[1] * src[1] / (255 - dst[1])); result[2] = dst[2] == 255 ? 255 : Math.min(255, src[2] * src[2] / (255 - dst[2])); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case GREEN: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = dst[0]; result[1] = dst[1]; result[2] = src[2]; result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case HARD_LIGHT: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = src[0] < 128 ? dst[0] * src[0] >> 7 : 255 - ((255 - src[0]) * (255 - dst[0]) >> 7); result[1] = src[1] < 128 ? dst[1] * src[1] >> 7 : 255 - ((255 - src[1]) * (255 - dst[1]) >> 7); result[2] = src[2] < 128 ? dst[2] * src[2] >> 7 : 255 - ((255 - src[2]) * (255 - dst[2]) >> 7); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case HEAT: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = dst[0] == 0 ? 0 : Math.max(0, 255 - (255 - src[0]) * (255 - src[0]) / dst[0]); result[1] = dst[1] == 0 ? 0 : Math.max(0, 255 - (255 - src[1]) * (255 - src[1]) / dst[1]); result[2] = dst[2] == 0 ? 0 : Math.max(0, 255 - (255 - src[2]) * (255 - src[2]) / dst[2]); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case HUE: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { float[] srcHSL = new float[3]; ColorUtilities.RGBtoHSL(src[0], src[1], src[2], srcHSL); float[] dstHSL = new float[3]; ColorUtilities.RGBtoHSL(dst[0], dst[1], dst[2], dstHSL); ColorUtilities.HSLtoRGB(srcHSL[0], dstHSL[1], dstHSL[2], result); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case INVERSE_COLOR_BURN: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = dst[0] == 0 ? 0 : Math.max(0, 255 - (((255 - src[0]) << 8) / dst[0])); result[1] = dst[1] == 0 ? 0 : Math.max(0, 255 - (((255 - src[1]) << 8) / dst[1])); result[2] = dst[2] == 0 ? 0 : Math.max(0, 255 - (((255 - src[2]) << 8) / dst[2])); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case INVERSE_COLOR_DODGE: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = dst[0] == 255 ? 255 : Math.min((src[0] << 8) / (255 - dst[0]), 255); result[1] = dst[1] == 255 ? 255 : Math.min((src[1] << 8) / (255 - dst[1]), 255); result[2] = dst[2] == 255 ? 255 : Math.min((src[2] << 8) / (255 - dst[2]), 255); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case LIGHTEN: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = Math.max(src[0], dst[0]); result[1] = Math.max(src[1], dst[1]); result[2] = Math.max(src[2], dst[2]); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case LUMINOSITY: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { float[] srcHSL = new float[3]; ColorUtilities.RGBtoHSL(src[0], src[1], src[2], srcHSL); float[] dstHSL = new float[3]; ColorUtilities.RGBtoHSL(dst[0], dst[1], dst[2], dstHSL); ColorUtilities.HSLtoRGB(dstHSL[0], dstHSL[1], srcHSL[2], result); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case MULTIPLY: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = (src[0] * dst[0]) >> 8; result[1] = (src[1] * dst[1]) >> 8; result[2] = (src[2] * dst[2]) >> 8; result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case NEGATION: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = 255 - Math.abs(255 - dst[0] - src[0]); result[1] = 255 - Math.abs(255 - dst[1] - src[1]); result[2] = 255 - Math.abs(255 - dst[2] - src[2]); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case OVERLAY: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = dst[0] < 128 ? dst[0] * src[0] >> 7 : 255 - ((255 - dst[0]) * (255 - src[0]) >> 7); result[1] = dst[1] < 128 ? dst[1] * src[1] >> 7 : 255 - ((255 - dst[1]) * (255 - src[1]) >> 7); result[2] = dst[2] < 128 ? dst[2] * src[2] >> 7 : 255 - ((255 - dst[2]) * (255 - src[2]) >> 7); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case RED: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = src[0]; result[1] = dst[1]; result[2] = dst[2]; result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case REFLECT: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = src[0] == 255 ? 255 : Math.min(255, dst[0] * dst[0] / (255 - src[0])); result[1] = src[1] == 255 ? 255 : Math.min(255, dst[1] * dst[1] / (255 - src[1])); result[2] = src[2] == 255 ? 255 : Math.min(255, dst[2] * dst[2] / (255 - src[2])); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case SATURATION: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { float[] srcHSL = new float[3]; ColorUtilities.RGBtoHSL(src[0], src[1], src[2], srcHSL); float[] dstHSL = new float[3]; ColorUtilities.RGBtoHSL(dst[0], dst[1], dst[2], dstHSL); ColorUtilities.HSLtoRGB(dstHSL[0], srcHSL[1], dstHSL[2], result); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case SCREEN: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = 255 - ((255 - src[0]) * (255 - dst[0]) >> 8); result[1] = 255 - ((255 - src[1]) * (255 - dst[1]) >> 8); result[2] = 255 - ((255 - src[2]) * (255 - dst[2]) >> 8); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case SOFT_BURN: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = dst[0] + src[0] < 256 ? (dst[0] == 255 ? 255 : Math.min(255, (src[0] << 7) / (255 - dst[0]))) : Math.max(0, 255 - (((255 - dst[0]) << 7) / src[0])); result[1] = dst[1] + src[1] < 256 ? (dst[1] == 255 ? 255 : Math.min(255, (src[1] << 7) / (255 - dst[1]))) : Math.max(0, 255 - (((255 - dst[1]) << 7) / src[1])); result[2] = dst[2] + src[2] < 256 ? (dst[2] == 255 ? 255 : Math.min(255, (src[2] << 7) / (255 - dst[2]))) : Math.max(0, 255 - (((255 - dst[2]) << 7) / src[2])); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case SOFT_DODGE: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = dst[0] + src[0] < 256 ? (src[0] == 255 ? 255 : Math.min(255, (dst[0] << 7) / (255 - src[0]))) : Math.max(0, 255 - (((255 - src[0]) << 7) / dst[0])); result[1] = dst[1] + src[1] < 256 ? (src[1] == 255 ? 255 : Math.min(255, (dst[1] << 7) / (255 - src[1]))) : Math.max(0, 255 - (((255 - src[1]) << 7) / dst[1])); result[2] = dst[2] + src[2] < 256 ? (src[2] == 255 ? 255 : Math.min(255, (dst[2] << 7) / (255 - src[2]))) : Math.max(0, 255 - (((255 - src[2]) << 7) / dst[2])); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case SOFT_LIGHT: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { int mRed = src[0] * dst[0] / 255; int mGreen = src[1] * dst[1] / 255; int mBlue = src[2] * dst[2] / 255; result[0] = mRed + src[0] * (255 - ((255 - src[0]) * (255 - dst[0]) / 255) - mRed) / 255; result[1] = mGreen + src[1] * (255 - ((255 - src[1]) * (255 - dst[1]) / 255) - mGreen) / 255; result[2] = mBlue + src[2] * (255 - ((255 - src[2]) * (255 - dst[2]) / 255) - mBlue) / 255; result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case STAMP: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = Math.max(0, Math.min(255, dst[0] + 2 * src[0] - 256)); result[1] = Math.max(0, Math.min(255, dst[1] + 2 * src[1] - 256)); result[2] = Math.max(0, Math.min(255, dst[2] + 2 * src[2] - 256)); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; case SUBTRACT: return new Blender() { @Override public void blend(int[] src, int[] dst, int[] result) { result[0] = Math.max(0, src[0] + dst[0] - 256); result[1] = Math.max(0, src[1] + dst[1] - 256); result[2] = Math.max(0, src[2] + dst[2] - 256); result[3] = Math.min(255, src[3] + dst[3] - (src[3] * dst[3]) / 255); } }; } throw new IllegalArgumentException("Blender not implemented for " + composite.getMode().name()); }
diff --git a/src/main/java/com/hubspot/dropwizard/guice/GuiceBundle.java b/src/main/java/com/hubspot/dropwizard/guice/GuiceBundle.java index 34c2d55..3e884bf 100644 --- a/src/main/java/com/hubspot/dropwizard/guice/GuiceBundle.java +++ b/src/main/java/com/hubspot/dropwizard/guice/GuiceBundle.java @@ -1,118 +1,118 @@ package com.hubspot.dropwizard.guice; import com.codahale.dropwizard.Configuration; import com.codahale.dropwizard.ConfiguredBundle; import com.codahale.dropwizard.setup.Bootstrap; import com.codahale.dropwizard.setup.Environment; import com.google.common.base.Function; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Module; import com.google.inject.servlet.GuiceFilter; import com.sun.jersey.api.core.ResourceConfig; import com.sun.jersey.spi.container.servlet.ServletContainer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.util.List; public class GuiceBundle<T extends Configuration> implements ConfiguredBundle<T> { final Logger logger = LoggerFactory.getLogger(GuiceBundle.class); private final AutoConfig autoConfig; private final List<Module> modules; private Injector injector; private DropwizardEnvironmentModule dropwizardEnvironmentModule; private Optional<Class<T>> configurationClass; private GuiceContainer container; public static class Builder<T extends Configuration> { private AutoConfig autoConfig; private List<Module> modules = Lists.newArrayList(); private Optional<Class<T>> configurationClass = Optional.<Class<T>>absent(); public Builder<T> addModule(Module module) { Preconditions.checkNotNull(module); modules.add(module); return this; } public Builder<T> setConfigClass(Class<T> clazz) { configurationClass = Optional.of(clazz); return this; } public Builder<T> enableAutoConfig(String... basePackages) { Preconditions.checkNotNull(basePackages.length > 0); Preconditions.checkArgument(autoConfig == null, "autoConfig already enabled!"); autoConfig = new AutoConfig(basePackages); return this; } public GuiceBundle<T> build() { return new GuiceBundle<T>(autoConfig, modules, configurationClass); } } public static <T extends Configuration> Builder<T> newBuilder() { return new Builder<T>(); } private GuiceBundle(AutoConfig autoConfig, List<Module> modules, Optional<Class<T>> configurationClass) { Preconditions.checkNotNull(modules); Preconditions.checkArgument(!modules.isEmpty()); this.modules = modules; this.autoConfig = autoConfig; this.configurationClass = configurationClass; } @Override public void initialize(Bootstrap<?> bootstrap) { container = new GuiceContainer(); JerseyContainerModule jerseyContainerModule = new JerseyContainerModule(container); if (configurationClass.isPresent()) { dropwizardEnvironmentModule = new DropwizardEnvironmentModule<T>(configurationClass.get()); } else { dropwizardEnvironmentModule = new DropwizardEnvironmentModule<Configuration>(Configuration.class); } modules.add(jerseyContainerModule); modules.add(dropwizardEnvironmentModule); injector = Guice.createInjector(modules); if (autoConfig != null) { autoConfig.initialize(bootstrap, injector); } } @Override public void run(final T configuration, final Environment environment) { container.setResourceConfig(environment.jersey().getResourceConfig()); - container.getServletContext().addFilter("Guice Filter", GuiceFilter.class); environment.jersey().replace(new Function<ResourceConfig, ServletContainer>() { @Nullable @Override public ServletContainer apply(ResourceConfig resourceConfig) { return container; } }); + environment.servlets().addFilter("Guice Filter", GuiceFilter.class); setEnvironment(configuration, environment); if (autoConfig != null) { autoConfig.run(environment, injector); } } @SuppressWarnings("unchecked") private void setEnvironment(final T configuration, final Environment environment) { dropwizardEnvironmentModule.setEnvironmentData(configuration, environment); } public Injector getInjector() { return injector; } }
false
true
public void run(final T configuration, final Environment environment) { container.setResourceConfig(environment.jersey().getResourceConfig()); container.getServletContext().addFilter("Guice Filter", GuiceFilter.class); environment.jersey().replace(new Function<ResourceConfig, ServletContainer>() { @Nullable @Override public ServletContainer apply(ResourceConfig resourceConfig) { return container; } }); setEnvironment(configuration, environment); if (autoConfig != null) { autoConfig.run(environment, injector); } }
public void run(final T configuration, final Environment environment) { container.setResourceConfig(environment.jersey().getResourceConfig()); environment.jersey().replace(new Function<ResourceConfig, ServletContainer>() { @Nullable @Override public ServletContainer apply(ResourceConfig resourceConfig) { return container; } }); environment.servlets().addFilter("Guice Filter", GuiceFilter.class); setEnvironment(configuration, environment); if (autoConfig != null) { autoConfig.run(environment, injector); } }
diff --git a/src/haven/Material.java b/src/haven/Material.java index 14156f28..ee9c29a7 100644 --- a/src/haven/Material.java +++ b/src/haven/Material.java @@ -1,262 +1,262 @@ /* * This file is part of the Haven & Hearth game client. * Copyright (C) 2009 Fredrik Tolf <[email protected]>, and * Björn Johannessen <[email protected]> * * Redistribution and/or modification of this file is subject to the * terms of the GNU Lesser General Public License, version 3, as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * Other parts of this source tree adhere to other copying * rights. Please see the file `COPYING' in the root directory of the * source tree for details. * * A copy the GNU Lesser General Public License is distributed along * with the source tree of which this file is a part in the file * `doc/LPGL-3'. If it is missing for any reason, please see the Free * Software Foundation's website at <http://www.fsf.org/>, or write * to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307 USA */ package haven; import java.awt.Color; import java.util.*; import javax.media.opengl.*; import static haven.Utils.c2fa; public class Material extends GLState { public final GLState[] states; public static final GLState nofacecull = new GLState.StandAlone(PView.proj) { public void apply(GOut g) { g.gl.glDisable(GL.GL_CULL_FACE); } public void unapply(GOut g) { g.gl.glEnable(GL.GL_CULL_FACE); } }; public static final GLState alphaclip = new GLState.StandAlone(PView.proj) { public void apply(GOut g) { g.gl.glEnable(GL.GL_ALPHA_TEST); } public void unapply(GOut g) { g.gl.glDisable(GL.GL_ALPHA_TEST); } }; public static final float[] defamb = {0.2f, 0.2f, 0.2f, 1.0f}; public static final float[] defdif = {0.8f, 0.8f, 0.8f, 1.0f}; public static final float[] defspc = {0.0f, 0.0f, 0.0f, 1.0f}; public static final float[] defemi = {0.0f, 0.0f, 0.0f, 1.0f}; public static final GLState.Slot<Colors> colors = new GLState.Slot<Colors>(Colors.class); public static class Colors extends GLState { public float[] amb, dif, spc, emi; public float shine; public Colors() { amb = defamb; dif = defdif; spc = defspc; emi = defemi; } public Colors(Color amb, Color dif, Color spc, Color emi, float shine) { build(amb, dif, spc, emi); this.shine = shine; } public Colors(Color col) { this(new Color((int)(col.getRed() * defamb[0]), (int)(col.getGreen() * defamb[1]), (int)(col.getBlue() * defamb[2]), col.getAlpha()), new Color((int)(col.getRed() * defdif[0]), (int)(col.getGreen() * defdif[1]), (int)(col.getBlue() * defdif[2]), col.getAlpha()), new Color(0, 0, 0, 0), new Color(0, 0, 0, 0), 0); } public void build(Color amb, Color dif, Color spc, Color emi) { this.amb = c2fa(amb); this.dif = c2fa(dif); this.spc = c2fa(spc); this.emi = c2fa(emi); } public void apply(GOut g) { GL gl = g.gl; gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_AMBIENT, amb, 0); gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_DIFFUSE, dif, 0); gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_SPECULAR, spc, 0); gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_EMISSION, emi, 0); gl.glMaterialf(GL.GL_FRONT_AND_BACK, GL.GL_SHININESS, shine); } public void unapply(GOut g) { GL gl = g.gl; gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_AMBIENT, defamb, 0); gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_DIFFUSE, defdif, 0); gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_SPECULAR, defspc, 0); gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_EMISSION, defemi, 0); gl.glMaterialf(GL.GL_FRONT_AND_BACK, GL.GL_SHININESS, 0.0f); } public int capplyfrom(GLState from) { if(from instanceof Colors) return(5); return(-1); } public void applyfrom(GOut g, GLState from) { if(from instanceof Colors) apply(g); } public void prep(Buffer buf) { buf.put(colors, this); } public String toString() { return(String.format("(%.1f, %.1f, %.1f), (%.1f, %.1f, %.1f), (%.1f, %.1f, %.1f @ %.1f)", amb[0], amb[1], amb[2], dif[0], dif[1], dif[2], spc[0], spc[1], spc[2], shine)); } } public void apply(GOut g) {} public void unapply(GOut g) {} public Material(GLState... states) { this.states = states; } public Material() { this(new Colors(), alphaclip); } public Material(Color amb, Color dif, Color spc, Color emi, float shine) { this(new Colors(amb, dif, spc, emi, shine), alphaclip); } public Material(Color col) { this(new Colors(col)); } public Material(Tex tex) { this(new Colors(), tex, alphaclip); } public String toString() { return(Arrays.asList(states).toString()); } private static GLState deflight = Light.vlights; public void prep(Buffer buf) { for(GLState st : states) st.prep(buf); buf.cfg.deflight.prep(buf); } public static class Res extends Resource.Layer { public final int id; private transient List<GLState> states = new LinkedList<GLState>(); private transient List<Resolver> left = new LinkedList<Resolver>(); private transient Material m; private boolean mipmap = false, linear = false; private interface Resolver { public GLState resolve(); } private static Color col(byte[] buf, int[] off) { double r = Utils.floatd(buf, off[0]); off[0] += 5; double g = Utils.floatd(buf, off[0]); off[0] += 5; double b = Utils.floatd(buf, off[0]); off[0] += 5; double a = Utils.floatd(buf, off[0]); off[0] += 5; return(new Color((float)r, (float)g, (float)b, (float)a)); } public Res(Resource res, byte[] buf) { res.super(); id = Utils.uint16d(buf, 0); int[] off = {2}; while(off[0] < buf.length) { String thing = Utils.strd(buf, off).intern(); if(thing == "col") { Color amb = col(buf, off); Color dif = col(buf, off); Color spc = col(buf, off); double shine = Utils.floatd(buf, off[0]); off[0] += 5; Color emi = col(buf, off); states.add(new Colors(amb, dif, spc, emi, (float)shine)); } else if(thing == "linear") { linear = true; } else if(thing == "mipmap") { mipmap = true; } else if(thing == "nofacecull") { states.add(nofacecull); } else if(thing == "tex") { final int id = Utils.uint16d(buf, off[0]); off[0] += 2; left.add(new Resolver() { public GLState resolve() { - for(Resource.Image img : getres().layers(Resource.imgc, false)) { + for(Resource.Image img : getres().layers(Resource.imgc)) { if(img.id == id) return(img.tex()); } throw(new RuntimeException(String.format("Specified texture %d not found in %s", id, getres()))); } }); } else if(thing == "texlink") { final String nm = Utils.strd(buf, off); final int ver = Utils.uint16d(buf, off[0]); off[0] += 2; final int id = Utils.uint16d(buf, off[0]); off[0] += 2; left.add(new Resolver() { public GLState resolve() { Resource res = Resource.load(nm, ver); - for(Resource.Image img : res.layers(Resource.imgc, false)) { + for(Resource.Image img : res.layers(Resource.imgc)) { if(img.id == id) return(img.tex()); } throw(new RuntimeException(String.format("Specified texture %d for %s not found in %s", id, getres(), res))); } }); } else { throw(new Resource.LoadException("Unknown material part: " + thing, getres())); } } states.add(alphaclip); } public Material get() { synchronized(this) { if(m == null) { for(Iterator<Resolver> i = left.iterator(); i.hasNext();) { Resolver r = i.next(); states.add(r.resolve()); i.remove(); } m = new Material(states.toArray(new GLState[0])); } return(m); } } public void init() { for(Resource.Image img : getres().layers(Resource.imgc, false)) { TexGL tex = (TexGL)img.tex(); if(mipmap) tex.mipmap(); if(linear) tex.magfilter(GL.GL_LINEAR); } } } }
false
true
public Res(Resource res, byte[] buf) { res.super(); id = Utils.uint16d(buf, 0); int[] off = {2}; while(off[0] < buf.length) { String thing = Utils.strd(buf, off).intern(); if(thing == "col") { Color amb = col(buf, off); Color dif = col(buf, off); Color spc = col(buf, off); double shine = Utils.floatd(buf, off[0]); off[0] += 5; Color emi = col(buf, off); states.add(new Colors(amb, dif, spc, emi, (float)shine)); } else if(thing == "linear") { linear = true; } else if(thing == "mipmap") { mipmap = true; } else if(thing == "nofacecull") { states.add(nofacecull); } else if(thing == "tex") { final int id = Utils.uint16d(buf, off[0]); off[0] += 2; left.add(new Resolver() { public GLState resolve() { for(Resource.Image img : getres().layers(Resource.imgc, false)) { if(img.id == id) return(img.tex()); } throw(new RuntimeException(String.format("Specified texture %d not found in %s", id, getres()))); } }); } else if(thing == "texlink") { final String nm = Utils.strd(buf, off); final int ver = Utils.uint16d(buf, off[0]); off[0] += 2; final int id = Utils.uint16d(buf, off[0]); off[0] += 2; left.add(new Resolver() { public GLState resolve() { Resource res = Resource.load(nm, ver); for(Resource.Image img : res.layers(Resource.imgc, false)) { if(img.id == id) return(img.tex()); } throw(new RuntimeException(String.format("Specified texture %d for %s not found in %s", id, getres(), res))); } }); } else { throw(new Resource.LoadException("Unknown material part: " + thing, getres())); } } states.add(alphaclip); }
public Res(Resource res, byte[] buf) { res.super(); id = Utils.uint16d(buf, 0); int[] off = {2}; while(off[0] < buf.length) { String thing = Utils.strd(buf, off).intern(); if(thing == "col") { Color amb = col(buf, off); Color dif = col(buf, off); Color spc = col(buf, off); double shine = Utils.floatd(buf, off[0]); off[0] += 5; Color emi = col(buf, off); states.add(new Colors(amb, dif, spc, emi, (float)shine)); } else if(thing == "linear") { linear = true; } else if(thing == "mipmap") { mipmap = true; } else if(thing == "nofacecull") { states.add(nofacecull); } else if(thing == "tex") { final int id = Utils.uint16d(buf, off[0]); off[0] += 2; left.add(new Resolver() { public GLState resolve() { for(Resource.Image img : getres().layers(Resource.imgc)) { if(img.id == id) return(img.tex()); } throw(new RuntimeException(String.format("Specified texture %d not found in %s", id, getres()))); } }); } else if(thing == "texlink") { final String nm = Utils.strd(buf, off); final int ver = Utils.uint16d(buf, off[0]); off[0] += 2; final int id = Utils.uint16d(buf, off[0]); off[0] += 2; left.add(new Resolver() { public GLState resolve() { Resource res = Resource.load(nm, ver); for(Resource.Image img : res.layers(Resource.imgc)) { if(img.id == id) return(img.tex()); } throw(new RuntimeException(String.format("Specified texture %d for %s not found in %s", id, getres(), res))); } }); } else { throw(new Resource.LoadException("Unknown material part: " + thing, getres())); } } states.add(alphaclip); }
diff --git a/WEB-INF/src/edu/wustl/catissuecore/deid/DeidReport.java b/WEB-INF/src/edu/wustl/catissuecore/deid/DeidReport.java index f78924889..8bf939c48 100644 --- a/WEB-INF/src/edu/wustl/catissuecore/deid/DeidReport.java +++ b/WEB-INF/src/edu/wustl/catissuecore/deid/DeidReport.java @@ -1,238 +1,238 @@ /** * */ package edu.wustl.catissuecore.deid; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Set; import org.jdom.Element; import org.jdom.output.Format; import edu.wustl.catissuecore.domain.Participant; import edu.wustl.catissuecore.domain.SpecimenCollectionGroup; import edu.wustl.catissuecore.domain.pathology.DeidentifiedSurgicalPathologyReport; import edu.wustl.catissuecore.domain.pathology.IdentifiedSurgicalPathologyReport; import edu.wustl.catissuecore.domain.pathology.ReportSection; import edu.wustl.catissuecore.domain.pathology.TextContent; import edu.wustl.catissuecore.reportloader.Parser; import edu.wustl.catissuecore.reportloader.ReportLoaderUtil; import edu.wustl.common.util.XMLPropertyHandler; import edu.wustl.common.util.dbManager.DAOException; import edu.wustl.common.util.logger.Logger; /** * @author vijay_pande * This class is a thread which converts a single identified report into its equivalent de-identified report. */ public class DeidReport extends Thread { public static final Object OBJ=new Object(); private IdentifiedSurgicalPathologyReport ispr; /** * @param ispr identified Surgical Pathology Report * @throws Exception * constructor for the DeidReport thread */ public DeidReport(IdentifiedSurgicalPathologyReport ispr) throws Exception { this.ispr=ispr; } /** * @see java.lang.Thread#run() * This is default run method of the thread. Which is like a deid pipeline. This pipeline manages the de-identification process. */ public void run() { try { org.jdom.Document currentRequestDocument = new org.jdom.Document(new Element("Dataset")); SpecimenCollectionGroup scg=ispr.getSpecimenCollectionGroup(); Participant participant=scg.getCollectionProtocolRegistration().getParticipant(); TextContent tc=ispr.getTextContent(); tc.setData(synthesizeSPRText(ispr)); ispr.setTextContent(tc); Element reportElement = DeidUtils.buildReportElement(participant, ispr, ispr.getTextContent().getData()); currentRequestDocument.getRootElement().addContent(reportElement); String deidRequest = DeidUtils.convertDocumentToString(currentRequestDocument, Format.getPrettyFormat()); String deidReport=deIdentify(deidRequest); String deidText=""; deidText=DeidUtils.extractReport(deidReport, XMLPropertyHandler.getValue("deid.dtd.filename")); Date deidCollectionDate=null; deidCollectionDate=DeidUtils.extractDate(deidText); DeidentifiedSurgicalPathologyReport pathologyReport = createPathologyReport(ispr, deidText, deidCollectionDate); try { ReportLoaderUtil.saveObject(pathologyReport); - ispr.setReportStatus(Parser.IDENTIFIED); + ispr.setReportStatus(Parser.DEIDENTIFIED); ispr.setDeidentifiedSurgicalPathologyReport(pathologyReport); ReportLoaderUtil.updateObject(ispr); } catch(DAOException daoEx) { Logger.out.error("Error while saving//updating Deidentified//Identified report ",daoEx); } } catch(Exception ex) { Logger.out.error("Deidentification process is failed:",ex); try { ispr.setReportStatus(Parser.DEID_PROCESS_FAILED); ReportLoaderUtil.updateObject(ispr); } catch(Exception e) { Logger.out.error("DeidReport: Updating Identified report status failed",e); } Logger.out.error("Upexpected error in DeidReport thread", ex); } } /** * @param ispr identified surgical pathology report * @param deidText de-intified text * @param deidCollectedDate collection date and time of report * @return DeidentifiedSurgicalPathologyReport * @throws Exception a generic exception oocured while creating de-identified report instance. */ private DeidentifiedSurgicalPathologyReport createPathologyReport(IdentifiedSurgicalPathologyReport ispr, String deidText, Date deidCollectedDate) throws Exception { DeidentifiedSurgicalPathologyReport deidReport=new DeidentifiedSurgicalPathologyReport(); if (ispr.getCollectionDateTime() != null) { deidReport.setCollectionDateTime(deidCollectedDate); } deidReport.setAccessionNumber(ispr.getAccessionNumber()); deidReport.setActivityStatus(ispr.getActivityStatus()); deidReport.setReportStatus(Parser.PENDING_FOR_XML); deidReport.setSpecimenCollectionGroup(ispr.getSpecimenCollectionGroup()); TextContent tc=new TextContent(); tc.setData(deidText); tc.setSurgicalPathologyReport(deidReport); deidReport.setSource(ispr.getSource()); deidReport.setTextContent(tc); deidReport.setIsFlagForReview(new Boolean(false)); deidReport.setIsQuanrantined(new Boolean(false)); return deidReport; } /** * @param ispr identified surgical pathoology report * @return sysnthesized Surgical pathology report text * @throws Exception a generic exception occured while synthesizing report text */ private String synthesizeSPRText(final IdentifiedSurgicalPathologyReport ispr) throws Exception { String docText = ""; //Get report sections for each report Set iss=ispr.getTextContent().getReportSectionCollection(); HashMap <String,String>nameToText = new HashMap<String, String>(); if(iss!=null) { for (Iterator i = iss.iterator(); i.hasNext();) { //Synthesize sections ReportSection rs = (ReportSection) i.next(); String abbr = rs.getName(); String text = rs.getDocumentFragment(); nameToText.put(abbr, text); } } else { Logger.out.info("NULL report section collection found in synthesizeSPRText method"); } for (int x = 0; x < DeIDPipelineManager.sectionPriority.size(); x++) { String abbr = (String) DeIDPipelineManager.sectionPriority.get(x); String sectionHeader = (String) DeIDPipelineManager.abbrToHeader.get(abbr); if (nameToText.containsKey(abbr)) { String sectionText = (String) nameToText.get(abbr); docText += "[" + sectionHeader + "]" + "\n\n" + sectionText + "\n\n\n"; } } return docText.trim(); } /** * @param text text to be de-identified * @return de-identified text * @throws Exception ocured while calling a native method call for de-identification * This method is responsible for preparing and calling a native method call to convert plain text into deindentified text. */ public String deIdentify(String text) throws Exception { String output = ""; try { synchronized(OBJ) { File f = new File("predeid.xml"); File f2 = new File("postdeid.tmp"); FileWriter fw = new FileWriter(f); fw.write(text); fw.close(); DeIDPipelineManager.deid.createDeidentifier(f.getAbsolutePath(), f2.getAbsolutePath()+ "?XML", DeIDPipelineManager.configFileName); BufferedReader br = new BufferedReader(new FileReader(f2)); String line = ""; while ((line = br.readLine()) != null) { output += line + "\n"; } br.close(); f.delete(); f2.delete(); OBJ.notifyAll(); } } catch (IOException ex) { Logger.out.error("File system error occured while creating or deleting temporary files for deidentification",ex); throw ex; } catch (Exception ex) { Logger.out.error("Severe error occured in the native method call for deidentification",ex); throw ex; } return output; } }
true
true
public void run() { try { org.jdom.Document currentRequestDocument = new org.jdom.Document(new Element("Dataset")); SpecimenCollectionGroup scg=ispr.getSpecimenCollectionGroup(); Participant participant=scg.getCollectionProtocolRegistration().getParticipant(); TextContent tc=ispr.getTextContent(); tc.setData(synthesizeSPRText(ispr)); ispr.setTextContent(tc); Element reportElement = DeidUtils.buildReportElement(participant, ispr, ispr.getTextContent().getData()); currentRequestDocument.getRootElement().addContent(reportElement); String deidRequest = DeidUtils.convertDocumentToString(currentRequestDocument, Format.getPrettyFormat()); String deidReport=deIdentify(deidRequest); String deidText=""; deidText=DeidUtils.extractReport(deidReport, XMLPropertyHandler.getValue("deid.dtd.filename")); Date deidCollectionDate=null; deidCollectionDate=DeidUtils.extractDate(deidText); DeidentifiedSurgicalPathologyReport pathologyReport = createPathologyReport(ispr, deidText, deidCollectionDate); try { ReportLoaderUtil.saveObject(pathologyReport); ispr.setReportStatus(Parser.IDENTIFIED); ispr.setDeidentifiedSurgicalPathologyReport(pathologyReport); ReportLoaderUtil.updateObject(ispr); } catch(DAOException daoEx) { Logger.out.error("Error while saving//updating Deidentified//Identified report ",daoEx); } } catch(Exception ex) { Logger.out.error("Deidentification process is failed:",ex); try { ispr.setReportStatus(Parser.DEID_PROCESS_FAILED); ReportLoaderUtil.updateObject(ispr); } catch(Exception e) { Logger.out.error("DeidReport: Updating Identified report status failed",e); } Logger.out.error("Upexpected error in DeidReport thread", ex); } }
public void run() { try { org.jdom.Document currentRequestDocument = new org.jdom.Document(new Element("Dataset")); SpecimenCollectionGroup scg=ispr.getSpecimenCollectionGroup(); Participant participant=scg.getCollectionProtocolRegistration().getParticipant(); TextContent tc=ispr.getTextContent(); tc.setData(synthesizeSPRText(ispr)); ispr.setTextContent(tc); Element reportElement = DeidUtils.buildReportElement(participant, ispr, ispr.getTextContent().getData()); currentRequestDocument.getRootElement().addContent(reportElement); String deidRequest = DeidUtils.convertDocumentToString(currentRequestDocument, Format.getPrettyFormat()); String deidReport=deIdentify(deidRequest); String deidText=""; deidText=DeidUtils.extractReport(deidReport, XMLPropertyHandler.getValue("deid.dtd.filename")); Date deidCollectionDate=null; deidCollectionDate=DeidUtils.extractDate(deidText); DeidentifiedSurgicalPathologyReport pathologyReport = createPathologyReport(ispr, deidText, deidCollectionDate); try { ReportLoaderUtil.saveObject(pathologyReport); ispr.setReportStatus(Parser.DEIDENTIFIED); ispr.setDeidentifiedSurgicalPathologyReport(pathologyReport); ReportLoaderUtil.updateObject(ispr); } catch(DAOException daoEx) { Logger.out.error("Error while saving//updating Deidentified//Identified report ",daoEx); } } catch(Exception ex) { Logger.out.error("Deidentification process is failed:",ex); try { ispr.setReportStatus(Parser.DEID_PROCESS_FAILED); ReportLoaderUtil.updateObject(ispr); } catch(Exception e) { Logger.out.error("DeidReport: Updating Identified report status failed",e); } Logger.out.error("Upexpected error in DeidReport thread", ex); } }
diff --git a/powershell/jaxrs/src/main/java/com/redhat/rhevm/api/powershell/resource/PowerShellIsosResource.java b/powershell/jaxrs/src/main/java/com/redhat/rhevm/api/powershell/resource/PowerShellIsosResource.java index 299694d2..80c76080 100644 --- a/powershell/jaxrs/src/main/java/com/redhat/rhevm/api/powershell/resource/PowerShellIsosResource.java +++ b/powershell/jaxrs/src/main/java/com/redhat/rhevm/api/powershell/resource/PowerShellIsosResource.java @@ -1,71 +1,75 @@ /* * Copyright © 2010 Red Hat, Inc. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package com.redhat.rhevm.api.powershell.resource; import com.redhat.rhevm.api.common.resource.UriInfoProvider; import com.redhat.rhevm.api.common.util.LinkHelper; import com.redhat.rhevm.api.model.DataCenter; import com.redhat.rhevm.api.model.Iso; import com.redhat.rhevm.api.model.Isos; import com.redhat.rhevm.api.resource.IsoResource; import com.redhat.rhevm.api.resource.IsosResource; import com.redhat.rhevm.api.powershell.model.PowerShellIso; import com.redhat.rhevm.api.powershell.util.PowerShellCmd; import com.redhat.rhevm.api.powershell.util.PowerShellParser; import com.redhat.rhevm.api.powershell.util.PowerShellPoolMap; import com.redhat.rhevm.api.powershell.util.PowerShellUtils; public class PowerShellIsosResource extends UriProviderWrapper implements IsosResource { private String dataCenterId; public PowerShellIsosResource(String dataCenterId, PowerShellPoolMap shellPools, PowerShellParser parser, UriInfoProvider uriProvider) { super(null, shellPools, parser, uriProvider); this.dataCenterId = dataCenterId; } @Override public Isos list() { StringBuilder buf = new StringBuilder(); + buf.append("$d = get-datacenter " + PowerShellUtils.escape(dataCenterId)); + buf.append("; "); + buf.append("if ($d.status -eq \"Up\") { "); buf.append("get-isoimages"); buf.append(" -datacenterid " + PowerShellUtils.escape(dataCenterId)); + buf.append("}"); Isos ret = new Isos(); for (Iso iso : PowerShellIso.parse(parser, PowerShellCmd.runCommand(getPool(), buf.toString()))) { ret.getIsos().add(addLinks(iso, dataCenterId)); } return ret; } @Override public IsoResource getIsoSubResource(String id) { return new PowerShellIsoResource(id, dataCenterId, this); } public Iso addLinks(Iso iso, String dataCenterId) { iso.setDataCenter(new DataCenter()); iso.getDataCenter().setId(dataCenterId); return LinkHelper.addLinks(getUriInfo(), iso); } }
false
true
public Isos list() { StringBuilder buf = new StringBuilder(); buf.append("get-isoimages"); buf.append(" -datacenterid " + PowerShellUtils.escape(dataCenterId)); Isos ret = new Isos(); for (Iso iso : PowerShellIso.parse(parser, PowerShellCmd.runCommand(getPool(), buf.toString()))) { ret.getIsos().add(addLinks(iso, dataCenterId)); } return ret; }
public Isos list() { StringBuilder buf = new StringBuilder(); buf.append("$d = get-datacenter " + PowerShellUtils.escape(dataCenterId)); buf.append("; "); buf.append("if ($d.status -eq \"Up\") { "); buf.append("get-isoimages"); buf.append(" -datacenterid " + PowerShellUtils.escape(dataCenterId)); buf.append("}"); Isos ret = new Isos(); for (Iso iso : PowerShellIso.parse(parser, PowerShellCmd.runCommand(getPool(), buf.toString()))) { ret.getIsos().add(addLinks(iso, dataCenterId)); } return ret; }
diff --git a/codemodel/src/com/sun/codemodel/JInvocation.java b/codemodel/src/com/sun/codemodel/JInvocation.java index 010f7158..195262bd 100644 --- a/codemodel/src/com/sun/codemodel/JInvocation.java +++ b/codemodel/src/com/sun/codemodel/JInvocation.java @@ -1,136 +1,136 @@ /* * Copyright 2004 Sun Microsystems, Inc. All rights reserved. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ package com.sun.codemodel; import java.util.ArrayList; import java.util.List; /** * JMethod invocation */ public final class JInvocation extends JExpressionImpl implements JStatement { /** * Object expression upon which this method will be invoked, or null if * this is a constructor invocation */ private JGenerable object; /** * Name of the method to be invoked */ private String name; private boolean isConstructor = false; /** * List of argument expressions for this method invocation */ private List<JExpression> args = new ArrayList<JExpression>(); /** * If isConstructor==true, this field keeps the type to be created. */ private JType type = null; /** * Invokes a method on an object. * * @param object * JExpression for the object upon which * the named method will be invoked, * or null if none * * @param name * Name of method to invoke */ JInvocation(JExpression object, String name) { this( (JGenerable)object, name ); } /** * Invokes a static method on a class. */ JInvocation(JClass type, String name) { this( (JGenerable)type, name ); } private JInvocation(JGenerable object, String name) { this.object = object; if (name.indexOf('.') >= 0) throw new IllegalArgumentException("JClass name contains '.': " + name); this.name = name; } /** * Invokes a constructor of an object (i.e., creates * a new object.) * * @param c * Type of the object to be created. If this type is * an array type, added arguments are treated as array * initializer. Thus you can create an expression like * <code>new int[]{1,2,3,4,5}</code>. */ JInvocation(JType c) { this.isConstructor = true; this.type = c; } /** * Add an expression to this invocation's argument list * * @param arg * Argument to add to argument list */ public JInvocation arg(JExpression arg) { if(arg==null) throw new IllegalArgumentException(); args.add(arg); return this; } /** * Adds a literal argument. * * Short for {@code arg(JExpr.lit(v))} */ public JInvocation arg(String v) { return arg(JExpr.lit(v)); } public void generate(JFormatter f) { if (isConstructor && type.isArray()) { // [RESULT] new T[]{arg1,arg2,arg3,...}; - f.p("new").t(type).p('{'); + f.p("new").g(type).p('{'); } else { if (isConstructor) - f.p("new").t(type).p('('); + f.p("new").g(type).p('('); else if (object != null) f.g(object).p('.').p(name).p('('); else f.id(name).p('('); } f.g(args); if (isConstructor && type.isArray()) f.p('}'); else f.p(')'); if( type instanceof JDefinedClass && ((JDefinedClass)type).isAnonymous() ) { ((JAnonymousClass)type).declareBody(f); } } public void state(JFormatter f) { f.g(this).p(';').nl(); } }
false
true
public void generate(JFormatter f) { if (isConstructor && type.isArray()) { // [RESULT] new T[]{arg1,arg2,arg3,...}; f.p("new").t(type).p('{'); } else { if (isConstructor) f.p("new").t(type).p('('); else if (object != null) f.g(object).p('.').p(name).p('('); else f.id(name).p('('); } f.g(args); if (isConstructor && type.isArray()) f.p('}'); else f.p(')'); if( type instanceof JDefinedClass && ((JDefinedClass)type).isAnonymous() ) { ((JAnonymousClass)type).declareBody(f); } }
public void generate(JFormatter f) { if (isConstructor && type.isArray()) { // [RESULT] new T[]{arg1,arg2,arg3,...}; f.p("new").g(type).p('{'); } else { if (isConstructor) f.p("new").g(type).p('('); else if (object != null) f.g(object).p('.').p(name).p('('); else f.id(name).p('('); } f.g(args); if (isConstructor && type.isArray()) f.p('}'); else f.p(')'); if( type instanceof JDefinedClass && ((JDefinedClass)type).isAnonymous() ) { ((JAnonymousClass)type).declareBody(f); } }
diff --git a/src/main/java/com/philihp/weblabora/model/building/ForestHut.java b/src/main/java/com/philihp/weblabora/model/building/ForestHut.java index db2e6e1..f773cff 100644 --- a/src/main/java/com/philihp/weblabora/model/building/ForestHut.java +++ b/src/main/java/com/philihp/weblabora/model/building/ForestHut.java @@ -1,44 +1,44 @@ package com.philihp.weblabora.model.building; import static com.philihp.weblabora.model.TerrainTypeEnum.COAST; import static com.philihp.weblabora.model.TerrainTypeEnum.HILLSIDE; import static com.philihp.weblabora.model.TerrainTypeEnum.PLAINS; import java.util.EnumSet; import com.philihp.weblabora.model.Board; import com.philihp.weblabora.model.BuildCost; import com.philihp.weblabora.model.Player; import com.philihp.weblabora.model.SettlementRound; import com.philihp.weblabora.model.Terrain; import com.philihp.weblabora.model.TerrainTypeEnum; import com.philihp.weblabora.model.TerrainUseEnum; import com.philihp.weblabora.model.UsageParamCoordinates; import com.philihp.weblabora.model.WeblaboraException; public class ForestHut extends BuildingCoordinateUsage { public ForestHut() { super("I29", SettlementRound.C, 3, "Forest Hut", BuildCost.is().clay(1) .straw(1), 5, 1, EnumSet.of(PLAINS, HILLSIDE, COAST), false); } @Override public void use(Board board, UsageParamCoordinates input) throws WeblaboraException { Player player = board.getPlayer(board.getActivePlayer()); Terrain spot = player.getLandscape() .getTerrainAt(input.getCoordinate()); if (spot.getTerrainUse() != TerrainUseEnum.FOREST) throw new WeblaboraException(getName() + " can't remove " + spot.getTerrainUse() + " at " + input + ", it can only remove FOREST"); else - spot.setTerrainType(TerrainTypeEnum.PLAINS); + spot.setTerrainUse(TerrainUseEnum.EMPTY); player.addSheep(2); player.addWood(2); player.addStone(1); } }
true
true
public void use(Board board, UsageParamCoordinates input) throws WeblaboraException { Player player = board.getPlayer(board.getActivePlayer()); Terrain spot = player.getLandscape() .getTerrainAt(input.getCoordinate()); if (spot.getTerrainUse() != TerrainUseEnum.FOREST) throw new WeblaboraException(getName() + " can't remove " + spot.getTerrainUse() + " at " + input + ", it can only remove FOREST"); else spot.setTerrainType(TerrainTypeEnum.PLAINS); player.addSheep(2); player.addWood(2); player.addStone(1); }
public void use(Board board, UsageParamCoordinates input) throws WeblaboraException { Player player = board.getPlayer(board.getActivePlayer()); Terrain spot = player.getLandscape() .getTerrainAt(input.getCoordinate()); if (spot.getTerrainUse() != TerrainUseEnum.FOREST) throw new WeblaboraException(getName() + " can't remove " + spot.getTerrainUse() + " at " + input + ", it can only remove FOREST"); else spot.setTerrainUse(TerrainUseEnum.EMPTY); player.addSheep(2); player.addWood(2); player.addStone(1); }
diff --git a/oak-jcr/src/main/java/org/apache/jackrabbit/oak/jcr/version/ReadWriteVersionManager.java b/oak-jcr/src/main/java/org/apache/jackrabbit/oak/jcr/version/ReadWriteVersionManager.java index b60324c439..848d82870e 100644 --- a/oak-jcr/src/main/java/org/apache/jackrabbit/oak/jcr/version/ReadWriteVersionManager.java +++ b/oak-jcr/src/main/java/org/apache/jackrabbit/oak/jcr/version/ReadWriteVersionManager.java @@ -1,160 +1,160 @@ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jackrabbit.oak.jcr.version; import javax.annotation.Nonnull; import javax.jcr.InvalidItemStateException; import javax.jcr.RepositoryException; import javax.jcr.UnsupportedRepositoryOperationException; import org.apache.jackrabbit.oak.api.CommitFailedException; import org.apache.jackrabbit.oak.api.Root; import org.apache.jackrabbit.oak.api.Tree; import org.apache.jackrabbit.oak.api.TreeLocation; import org.apache.jackrabbit.oak.api.Type; import org.apache.jackrabbit.oak.namepath.NamePathMapper; import org.apache.jackrabbit.oak.plugins.nodetype.ReadOnlyNodeTypeManager; import org.apache.jackrabbit.oak.plugins.version.ReadOnlyVersionManager; import org.apache.jackrabbit.oak.version.VersionConstants; import static com.google.common.base.Preconditions.checkNotNull; /** * <code>ReadWriteVersionManager</code>... */ public class ReadWriteVersionManager extends ReadOnlyVersionManager { private final TreeLocation versionStorageLocation; private final Root workspaceRoot; public ReadWriteVersionManager(@Nonnull TreeLocation versionStorageLocation, @Nonnull Root workspaceRoot) { this.versionStorageLocation = checkNotNull(versionStorageLocation); this.workspaceRoot = checkNotNull(workspaceRoot); } /** * Called by the write methods to refresh the state of the possible * session associated with this instance. The default implementation * of this method does nothing, but a subclass can use this callback * to keep a session in sync with the persisted version changes. * * @throws RepositoryException if the session could not be refreshed */ protected void refresh() throws RepositoryException { // do nothing } @Override @Nonnull protected Tree getVersionStorageTree() { return versionStorageLocation.getTree(); } @Override @Nonnull protected Root getWorkspaceRoot() { return workspaceRoot; } @Override @Nonnull protected ReadOnlyNodeTypeManager getNodeTypeManager() { return ReadOnlyNodeTypeManager.getInstance( workspaceRoot, NamePathMapper.DEFAULT); } /** * Performs a checkin on a versionable tree and returns the tree that * represents the created version. * * @param versionable the versionable node to check in. * @return the created version. * @throws InvalidItemStateException if the current root has pending * changes. * @throws UnsupportedRepositoryOperationException * if the versionable tree isn't actually * versionable. * @throws RepositoryException if an error occurs while checking the * node type of the tree. */ @Nonnull public Tree checkin(@Nonnull Tree versionable) throws RepositoryException, InvalidItemStateException, UnsupportedRepositoryOperationException { if (workspaceRoot.hasPendingChanges()) { throw new InvalidItemStateException("Unable to perform checkin. " + "Session has pending changes."); } if (!isVersionable(versionable)) { throw new UnsupportedRepositoryOperationException( versionable.getPath() + " is not versionable"); } TreeLocation location = versionable.getLocation(); if (isCheckedOut(location)) { versionable.setProperty(VersionConstants.JCR_ISCHECKEDOUT, Boolean.FALSE, Type.BOOLEAN); try { getWorkspaceRoot().commit(); refresh(); } catch (CommitFailedException e) { getWorkspaceRoot().refresh(); throw new RepositoryException(e); } } - return getBaseVersion(location.getTree()); + return getBaseVersion(getWorkspaceRoot().getTree(location.getPath())); } /** * Performs a checkout on a versionable tree. * * @param versionable the versionable node to check out. * @throws InvalidItemStateException if the current root has pending * changes. * @throws UnsupportedRepositoryOperationException * if the versionable tree isn't actually * versionable. * @throws RepositoryException if an error occurs while checking the * node type of the tree. */ public void checkout(@Nonnull Tree versionable) throws UnsupportedRepositoryOperationException, InvalidItemStateException, RepositoryException { if (workspaceRoot.hasPendingChanges()) { throw new InvalidItemStateException("Unable to perform checkout. " + "Session has pending changes."); } if (!isVersionable(versionable)) { throw new UnsupportedRepositoryOperationException( versionable.getPath() + " is not versionable"); } TreeLocation location = versionable.getLocation(); if (!isCheckedOut(location)) { versionable.setProperty(VersionConstants.JCR_ISCHECKEDOUT, Boolean.TRUE, Type.BOOLEAN); try { getWorkspaceRoot().commit(); refresh(); } catch (CommitFailedException e) { getWorkspaceRoot().refresh(); throw new RepositoryException(e); } } } // TODO: more methods that modify versions }
true
true
public Tree checkin(@Nonnull Tree versionable) throws RepositoryException, InvalidItemStateException, UnsupportedRepositoryOperationException { if (workspaceRoot.hasPendingChanges()) { throw new InvalidItemStateException("Unable to perform checkin. " + "Session has pending changes."); } if (!isVersionable(versionable)) { throw new UnsupportedRepositoryOperationException( versionable.getPath() + " is not versionable"); } TreeLocation location = versionable.getLocation(); if (isCheckedOut(location)) { versionable.setProperty(VersionConstants.JCR_ISCHECKEDOUT, Boolean.FALSE, Type.BOOLEAN); try { getWorkspaceRoot().commit(); refresh(); } catch (CommitFailedException e) { getWorkspaceRoot().refresh(); throw new RepositoryException(e); } } return getBaseVersion(location.getTree()); }
public Tree checkin(@Nonnull Tree versionable) throws RepositoryException, InvalidItemStateException, UnsupportedRepositoryOperationException { if (workspaceRoot.hasPendingChanges()) { throw new InvalidItemStateException("Unable to perform checkin. " + "Session has pending changes."); } if (!isVersionable(versionable)) { throw new UnsupportedRepositoryOperationException( versionable.getPath() + " is not versionable"); } TreeLocation location = versionable.getLocation(); if (isCheckedOut(location)) { versionable.setProperty(VersionConstants.JCR_ISCHECKEDOUT, Boolean.FALSE, Type.BOOLEAN); try { getWorkspaceRoot().commit(); refresh(); } catch (CommitFailedException e) { getWorkspaceRoot().refresh(); throw new RepositoryException(e); } } return getBaseVersion(getWorkspaceRoot().getTree(location.getPath())); }
diff --git a/app/controllers/VoteController.java b/app/controllers/VoteController.java index 459dd62..850519f 100644 --- a/app/controllers/VoteController.java +++ b/app/controllers/VoteController.java @@ -1,68 +1,68 @@ package controllers; import play.*; import play.mvc.*; import play.data.*; import views.html.*; import models.*; /** * Manage projects related operations. */ @Security.Authenticated(Secured.class) public class VoteController extends Controller { static Form<Criteria> criteriaForm = form(Criteria.class); static Form<Project> projectForm = form(Project.class); static Form<Ballot> ballotForm = form(Ballot.class); public static Long pjid; public static Result vote(){ if(User.getUserTypeId(User.findByUsername(request().username())) == 9) { return ok(views.html.adminVote.render(Project.findAllProject() , Criteria.all() , projectForm , ballotForm , User.findByUsername(request().username())) ); } else{ return ok(vote.render(Project.findAllProject() , Criteria.all() - , criteriaForm , projectForm + , ballotForm , User.findByUsername(request().username())) ); } } public static Result saveProject(Long id){ return ok(vote.render(Project.findAllProject() , Criteria.all() , projectForm , ballotForm , User.findByUsername(request().username())) ); } public static Result voteForProject() { Form<Ballot> bff = ballotForm.bindFromRequest(); System.out.println(bff.get().project_id); System.out.println(bff.get().criteria_id); System.out.println(bff.get().score); if (bff.get().score != 0) Ballot.saveBallot(bff.get() , User.findByUsername(request().username())); else redirect(routes.VoteController.vote()); return TODO; } }
false
true
public static Result vote(){ if(User.getUserTypeId(User.findByUsername(request().username())) == 9) { return ok(views.html.adminVote.render(Project.findAllProject() , Criteria.all() , projectForm , ballotForm , User.findByUsername(request().username())) ); } else{ return ok(vote.render(Project.findAllProject() , Criteria.all() , criteriaForm , projectForm , User.findByUsername(request().username())) ); } }
public static Result vote(){ if(User.getUserTypeId(User.findByUsername(request().username())) == 9) { return ok(views.html.adminVote.render(Project.findAllProject() , Criteria.all() , projectForm , ballotForm , User.findByUsername(request().username())) ); } else{ return ok(vote.render(Project.findAllProject() , Criteria.all() , projectForm , ballotForm , User.findByUsername(request().username())) ); } }
diff --git a/Osm2GpsMid/src/de/ueller/osmToGpsMid/model/HouseNumber.java b/Osm2GpsMid/src/de/ueller/osmToGpsMid/model/HouseNumber.java index e3ef3a82..5e07529a 100644 --- a/Osm2GpsMid/src/de/ueller/osmToGpsMid/model/HouseNumber.java +++ b/Osm2GpsMid/src/de/ueller/osmToGpsMid/model/HouseNumber.java @@ -1,53 +1,53 @@ /** * This file is part of OSM2GpsMid * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as published by * the Free Software Foundation. * * @version $Revision$ ($Name$) * @author hmueller,jkpj * Copyright (C) 2007-2010 Harald Mueller, Jyrki Kuoppala * derived from Path.java */ package de.ueller.osmToGpsMid.model; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; public class HouseNumber { private List<Node> nodeList = new ArrayList<Node>(); public HouseNumber() { super(); } public HouseNumber(ArrayList<Node> newNodeList) { nodeList = newNodeList; } public void add(Node n) { nodeList.add(n); } /** * */ public int getHouseNumberCount() { if (nodeList == null) { return 0; } - if (nodeList.size() > 1) { + if (nodeList.size() >= 1) { return (nodeList.size()); } return 0; } public List<Node> getNodes() { return nodeList; } }
true
true
public int getHouseNumberCount() { if (nodeList == null) { return 0; } if (nodeList.size() > 1) { return (nodeList.size()); } return 0; }
public int getHouseNumberCount() { if (nodeList == null) { return 0; } if (nodeList.size() >= 1) { return (nodeList.size()); } return 0; }
diff --git a/src/openmap/com/bbn/openmap/gui/time/TimeSliderLayer.java b/src/openmap/com/bbn/openmap/gui/time/TimeSliderLayer.java index 0ea6e3a1..48123867 100644 --- a/src/openmap/com/bbn/openmap/gui/time/TimeSliderLayer.java +++ b/src/openmap/com/bbn/openmap/gui/time/TimeSliderLayer.java @@ -1,1042 +1,1042 @@ // ********************************************************************** // // <copyright> // // BBN Technologies, a Verizon Company // 10 Moulton Street // Cambridge, MA 02138 // (617) 873-8000 // // Copyright (C) BBNT Solutions LLC. All rights reserved. // // </copyright> package com.bbn.openmap.gui.time; import java.awt.BasicStroke; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Polygon; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.awt.event.MouseEvent; import java.awt.geom.Point2D; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import com.bbn.openmap.Environment; import com.bbn.openmap.I18n; import com.bbn.openmap.MapBean; import com.bbn.openmap.MapHandler; import com.bbn.openmap.event.CenterListener; import com.bbn.openmap.event.CenterSupport; import com.bbn.openmap.event.MapMouseListener; import com.bbn.openmap.event.ZoomEvent; import com.bbn.openmap.event.ZoomListener; import com.bbn.openmap.event.ZoomSupport; import com.bbn.openmap.layer.OMGraphicHandlerLayer; import com.bbn.openmap.omGraphics.DrawingAttributes; import com.bbn.openmap.omGraphics.OMGraphicList; import com.bbn.openmap.omGraphics.OMLine; import com.bbn.openmap.omGraphics.OMPoly; import com.bbn.openmap.omGraphics.OMRect; import com.bbn.openmap.omGraphics.OMScalingIcon; import com.bbn.openmap.proj.Cartesian; import com.bbn.openmap.proj.Projection; import com.bbn.openmap.time.Clock; import com.bbn.openmap.time.TimeBounds; import com.bbn.openmap.time.TimeBoundsEvent; import com.bbn.openmap.time.TimeBoundsListener; import com.bbn.openmap.time.TimeEvent; import com.bbn.openmap.time.TimeEventListener; import com.bbn.openmap.time.TimerStatus; import com.bbn.openmap.tools.icon.BasicIconPart; import com.bbn.openmap.tools.icon.IconPart; import com.bbn.openmap.tools.icon.OMIconFactory; /** * Timeline layer * * Render events and allow for their selection on a variable-scale timeline */ public class TimeSliderLayer extends OMGraphicHandlerLayer implements PropertyChangeListener, MapMouseListener, ComponentListener, TimeBoundsListener, TimeEventListener { protected static Logger logger = Logger.getLogger("com.bbn.openmap.gui.time.TimeSliderLayer"); protected I18n i18n = Environment.getI18n(); protected CenterSupport centerDelegate; protected ZoomSupport zoomDelegate; long currentTime = 0; long gameStartTime = 0; long gameEndTime = 0; // KMTODO package this up into a standalone widget? // Times are generally in minutes double selectionWidthMinutes = 1.0; double maxSelectionWidthMinutes = 1.0; double selectionCenter = 0; OMRect boundsRectLeftHandle; // handles for scaling selection OMRect boundsRectRightHandle; OMLine baseLine; // thick line along middle OMPoly contextPoly; // lines that relate time slider to timeline above. int sliderPointHalfWidth = 5; TimelinePanel timelinePanel; TimelineLayer timelineLayer; public static double magicScaleFactor = 100000000; // KMTODO (Don? I guess // this is to // address a precision issue?) Clock clock; LabelPanel labelPanel; private boolean isNoTime = true; // In realTimeMode, gameEndTime is the origin, rather than gameStartTime private final boolean realTimeMode; // Used to refrain from re-scaling every TimeBoundsUpdate (in realTimeMode // only) private boolean userHasChangedScale = false; private final List<ITimeBoundsUserActionsListener> timeBoundsUserActionsListeners = new ArrayList<ITimeBoundsUserActionsListener>(); private final JButton zoomToSelection = new JButton("Zoom to Selection"); private final JButton renderFixedSelection = new JButton("Show Entire Selection"); /** * Construct the TimelineLayer. * * @param realTimeMode TODO */ public TimeSliderLayer(boolean realTimeMode) { this.realTimeMode = realTimeMode; setName("TimeSlider"); // This is how to set the ProjectionChangePolicy, which // dictates how the layer behaves when a new projection is // received. setProjectionChangePolicy(new com.bbn.openmap.layer.policy.StandardPCPolicy(this, false)); // Making the setting so this layer receives events from the // SelectMouseMode, which has a modeID of "Gestures". Other // IDs can be added as needed. setMouseModeIDsForEvents(new String[] { "Gestures" }); centerDelegate = new CenterSupport(this); zoomDelegate = new ZoomSupport(this); addComponentListener(this); } public void findAndInit(Object someObj) { if (someObj instanceof Clock) { clock = ((Clock) someObj); clock.addTimeEventListener(this); clock.addTimeBoundsListener(this); gameStartTime = ((Clock) someObj).getStartTime(); gameEndTime = ((Clock) someObj).getEndTime(); // Just in case we missed an early TimeBoundEvent updateTimeBounds(gameStartTime, gameEndTime); } if (someObj instanceof CenterListener) { centerDelegate.add((CenterListener) someObj); } if (someObj instanceof ZoomListener) { zoomDelegate.add((ZoomListener) someObj); } if (someObj instanceof TimelinePanel.Wrapper) { timelinePanel = ((TimelinePanel.Wrapper) someObj).getTimelinePanel(); timelinePanel.getMapBean().addPropertyChangeListener(this); timelineLayer = timelinePanel.getTimelineLayer(); } } /** * Called with the projection changes, should just generate the current * markings for the new projection. */ public synchronized OMGraphicList prepare() { OMGraphicList list = getList(); if (list == null) { list = new OMGraphicList(); } else { list.clear(); } TimeDrape drape = new TimeDrape(0, 0, -1, -1); drape.setVisible(isNoTime); drape.setFillPaint(Color.gray); drape.generate(getProjection()); list.add(drape); list.add(getControlWidgetList(getProjection())); return list; } /** * All we want to do here is reset the current position of all of the * widgets, and generate them with the projection for the new position. After * this call, the widgets are ready to paint. */ public synchronized OMGraphicList getControlWidgetList(Projection proj) { Projection projection = getProjection(); OMGraphicList controlWidgetList = new OMGraphicList(); // triangle indicating center of selection ImageIcon selectionPointImage; DrawingAttributes da = new DrawingAttributes(); da.setFillPaint(TimelineLayer.tint); da.setLinePaint(TimelineLayer.tint); IconPart ip = new BasicIconPart(new Polygon(new int[] { 50, 90, 10, 50 }, new int[] { 10, 90, 90, 10 }, 4), da); selectionPointImage = OMIconFactory.getIcon(32, 32, ip); - OMScalingIcon selectionPoint = new OMScalingIcon(0f, 0f, -5, 6, selectionPointImage, 1.0f); + OMScalingIcon selectionPoint = new OMScalingIcon(0f, 0f, 0, 6, selectionPointImage, 1.0f); final float selectionPointScale = 1.8f; selectionPoint.setMaxScale(selectionPointScale); selectionPoint.setMinScale(selectionPointScale); controlWidgetList.add(selectionPoint); boundsRectLeftHandle = new OMRect(0, 0, 0, 0); boundsRectLeftHandle.setFillPaint(Color.black); controlWidgetList.add(boundsRectLeftHandle); boundsRectRightHandle = new OMRect(0, 0, 0, 0); boundsRectRightHandle.setFillPaint(Color.black); controlWidgetList.add(boundsRectRightHandle); int[] xs = new int[8]; int[] ys = new int[8]; contextPoly = new OMPoly(xs, ys); contextPoly.setFillPaint(Color.white); controlWidgetList.add(contextPoly); baseLine = new OMLine(0, 0, 0, 0); baseLine.setLinePaint(Color.BLACK); baseLine.setStroke(new BasicStroke(2)); controlWidgetList.add(baseLine); if (projection == null) { return controlWidgetList; // Huhn? } double screenWidth = projection.getWidth(); float scale = (float) (magicScaleFactor * (double) TimelineLayer.forwardProjectMillis(gameEndTime - gameStartTime) / screenWidth); Point2D projCenter = projection.getCenter(); // TODO reconsider proper test here - for the moment, just brute-force // reproject always if (projCenter.getX() > selectionWidthMinutes || scale != projection.getScale()) { double nCenterLon = TimelineLayer.forwardProjectMillis(gameEndTime - gameStartTime) / 2f; projCenter.setLocation(nCenterLon, 0); projection = new Cartesian(projCenter, scale, projection.getWidth(), projection.getHeight()); setProjection(projection); } // Reset primary handle int contextBuffer = (int) (projection.getHeight() * .4); // If 'selectionCenter' is outside current time bounds, first attempt to // recompute from currentTime if (selectionCenter * 60.0 * TimeUnit.SECONDS.toMillis(1) > (gameEndTime - gameStartTime) || selectionCenter < 0) { selectionCenter = TimelineLayer.forwardProjectMillis(currentTime); } // And if _that_ fails, just clamp // DFD changed from TimeUnit.MINUTE.toMillis(1) to MILLISECONDS because // Java 5 doesn't have MINUTE if (selectionCenter * TimeUnit.MILLISECONDS.toMillis(60000) > (gameEndTime - gameStartTime)) { selectionCenter = (gameEndTime - gameStartTime) / TimeUnit.MILLISECONDS.toMillis(60000); } if (selectionCenter < 0) { selectionCenter = 0; } int x = (int) projection.forward(0, selectionCenter).getX(); // Reset bounds and handles Point2D sliderEndPoint = projection.forward(0, selectionWidthMinutes); Point2D origin = projection.forward(0, 0); int selectionHalfWidth = (int) ((sliderEndPoint.getX() - origin.getX()) / 2); int north = contextBuffer; int west = x - selectionHalfWidth; int south = projection.getHeight() - 1; int east = x + selectionHalfWidth; int mid = contextBuffer + 1 + (south - contextBuffer) / 2; if (logger.isLoggable(Level.FINE)) { logger.fine("selectionCenter:" + selectionCenter + ", selectionWidthMinutes:" + selectionWidthMinutes + ", x:" + x + ", origin:" + origin); logger.fine(" projection:" + projection); } selectionPoint.setLon((float) selectionCenter); selectionPoint.generate(projection); // and the two handles for the bounds int handleWest = west - sliderPointHalfWidth; int handleEast = west + sliderPointHalfWidth; final int sliderPointHalfHeight = 2; boundsRectLeftHandle.setLocation(handleWest, north + sliderPointHalfHeight, handleEast, south - sliderPointHalfHeight); boundsRectLeftHandle.generate(projection); handleWest = east - sliderPointHalfWidth; handleEast = east + sliderPointHalfWidth; boundsRectRightHandle.setLocation(handleWest, north + sliderPointHalfHeight, handleEast, south - sliderPointHalfHeight); boundsRectRightHandle.generate(projection); // and the context lines, that show how the current selection maps to // the timeline above xs = contextPoly.getXs(); ys = contextPoly.getYs(); xs[0] = 0; ys[0] = -1; xs[1] = 0; ys[1] = north; xs[2] = west; ys[2] = north; xs[3] = west; ys[3] = south; xs[4] = east; ys[4] = south; xs[5] = east; ys[5] = north; xs[6] = projection.getWidth() - 1; ys[6] = north; xs[7] = projection.getWidth() - 1; ys[7] = -1; contextPoly.generate(projection); baseLine.setPts(new int[] { 0, mid, projection.getWidth(), mid }); baseLine.generate(projection); return controlWidgetList; } protected void updateTimeline() { if (timelinePanel != null) { float scale = (float) (magicScaleFactor * selectionWidthMinutes / getProjection().getWidth()); if (logger.isLoggable(Level.FINE)) { logger.fine("Updating timeline with scale: " + scale); } timelinePanel.getMapBean().setScale(scale); } } public String getName() { return "TimelineLayer"; } /** * Updates zoom and center listeners with new projection information. * */ protected void finalizeProjection() { Projection projection = getProjection(); Cartesian cartesian = (projection instanceof Cartesian) ? (Cartesian) projection : null; if (cartesian != null) { double screenWidth = cartesian.getWidth(); cartesian.setLeftLimit(TimelineLayer.forwardProjectMillis(gameStartTime)); cartesian.setRightLimit(TimelineLayer.forwardProjectMillis(gameEndTime)); cartesian.setLimitAnchorPoint(new Point2D.Double(TimelineLayer.forwardProjectMillis(-gameStartTime), 0)); float scale = (float) (magicScaleFactor * (double) TimelineLayer.forwardProjectMillis(gameEndTime - gameStartTime) / screenWidth); zoomDelegate.fireZoom(ZoomEvent.ABSOLUTE, scale); double nCenterLon = TimelineLayer.forwardProjectMillis(gameEndTime - gameStartTime) / 2f; logger.fine("Telling the center delegate that the new center is 0, " + nCenterLon); centerDelegate.fireCenter(0, nCenterLon); // We are getting really large values for the center point of the // projection that the layer knows about. The MapBean projection // gets set OK, but then the projection held by the layer wrong, and // it throws the whole widget out of wack. If we set // the center of the projection to what it should be (the center // point between the start and end times), then everything settles // out. double x = cartesian.getCenter().getX(); if (x != nCenterLon) { ((MapBean) ((MapHandler) getBeanContext()).get(MapBean.class)).setCenter(0, nCenterLon); } repaint(); } } public void updateTime(TimeEvent te) { if (checkAndSetForNoTime(te)) { return; } TimerStatus timerStatus = te.getTimerStatus(); if (timerStatus.equals(TimerStatus.STEP_FORWARD) || timerStatus.equals(TimerStatus.STEP_BACKWARD) || timerStatus.equals(TimerStatus.UPDATE)) { currentTime = te.getSystemTime(); currentTime -= gameStartTime; selectionCenter = TimelineLayer.forwardProjectMillis(currentTime); doPrepare(); } if (timerStatus.equals(TimerStatus.FORWARD) || timerStatus.equals(TimerStatus.BACKWARD) || timerStatus.equals(TimerStatus.STOPPED)) { if (logger.isLoggable(Level.FINE)) { logger.fine("updated time: " + te); } // Checking for a running clock prevents a time status // update after the clock is stopped. The // AudioFileHandlers don't care about the current time // if it isn't running. if (realTimeMode || ((Clock) te.getSource()).isRunning()) { // update(te.getSystemTime()); currentTime = te.getSystemTime(); currentTime -= gameStartTime; selectionCenter = TimelineLayer.forwardProjectMillis(currentTime); doPrepare(); } } } /* * @seejava.beans.PropertyChangeListener#propertyChange(java.beans. * PropertyChangeEvent) */ public void propertyChange(PropertyChangeEvent evt) { String propertyName = evt.getPropertyName(); if (propertyName == MapBean.ProjectionProperty) { // This property should be from the TimelineLayer's MapBean, solely // for the scale measurement. logger.fine(propertyName + " from " + evt.getSource()); Projection timeLineProj = (Projection) evt.getNewValue(); // Need to solve for selectionWidthMinutes if (!realTimeMode || !userHasChangedScale) { selectionWidthMinutes = timeLineProj.getScale() * getProjection().getWidth() / magicScaleFactor; } if (selectionWidthMinutes > maxSelectionWidthMinutes + .0001 /* || selectionWidthMinutes < .0001 */) { if (logger.isLoggable(Level.FINE)) { logger.fine("resetting selectionWidthMinutes to max (projection change property change), was " + selectionWidthMinutes + ", now " + maxSelectionWidthMinutes); } selectionWidthMinutes = maxSelectionWidthMinutes; } doPrepare(); } } public boolean getUserHasChangedScale() { return userHasChangedScale; } public void setUserHasChangedScale(boolean userHasChangedScale) { this.userHasChangedScale = userHasChangedScale; } protected boolean checkAndSetForNoTime(TimeEvent te) { isNoTime = te == TimeEvent.NO_TIME; return isNoTime; } public MapMouseListener getMapMouseListener() { return this; } public String[] getMouseModeServiceList() { return getMouseModeIDsForEvents(); } enum DragState { NONE, PRIMARY_HANDLE, LEFT_HANDLE, RIGHT_HANDLE } DragState dragState = DragState.NONE; public boolean mousePressed(MouseEvent e) { updateMouseTimeDisplay(e); clearFixedRenderRange(); int x = e.getPoint().x; int y = e.getPoint().y; if (boundsRectLeftHandle.contains(x, y)) { dragState = DragState.LEFT_HANDLE; userHasChangedScale = true; } else if (boundsRectRightHandle.contains(x, y)) { dragState = DragState.RIGHT_HANDLE; userHasChangedScale = true; } else { dragState = DragState.PRIMARY_HANDLE; Projection projection = getProjection(); if (projection != null) { Point2D invPnt = projection.inverse(x, y); setSelectionCenter(invPnt.getX()); updateTimeline(); } } return true; } public boolean mouseReleased(MouseEvent e) { updateMouseTimeDisplay(e); dragState = DragState.NONE; return false; } public boolean mouseClicked(MouseEvent e) { updateMouseTimeDisplay(e); return false; } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { timelineLayer.updateMouseTimeDisplay(new Long(-1)); } void setSelectionCenter(double newCenter) { selectionCenter = newCenter; if (selectionCenter < 0) { selectionCenter = 0; } double offsetEnd = (double) (gameEndTime - gameStartTime) / 1000.0 / 60.0; if (selectionCenter > offsetEnd) { selectionCenter = offsetEnd; } clock.setTime(gameStartTime + (long) (selectionCenter * 60 * 1000)); } public boolean mouseDragged(MouseEvent e) { updateMouseTimeDisplay(e); Projection projection = getProjection(); if (projection == null) { return false; // Huhn? } double worldMouse; Point2D invPnt; int x = e.getPoint().x; int y = e.getPoint().y; int selectionCenterX = (int) projection.forward(0, selectionCenter).getX(); boolean scaleChange = false; switch (dragState) { case PRIMARY_HANDLE: invPnt = projection.inverse(x, y); setSelectionCenter(invPnt.getX()); break; case LEFT_HANDLE: if (x >= selectionCenterX - sliderPointHalfWidth) { x = selectionCenterX - sliderPointHalfWidth; } invPnt = projection.inverse(x, y); worldMouse = invPnt.getX(); selectionWidthMinutes = 2 * (selectionCenter - worldMouse); scaleChange = true; break; case RIGHT_HANDLE: if (x <= selectionCenterX + sliderPointHalfWidth) { x = selectionCenterX + sliderPointHalfWidth; } invPnt = projection.inverse(x, y); worldMouse = invPnt.getX(); selectionWidthMinutes = 2 * (worldMouse - selectionCenter); scaleChange = true; break; } if(scaleChange) { if (selectionWidthMinutes > maxSelectionWidthMinutes) { if (logger.isLoggable(Level.FINE)) { logger.fine("resetting selectionWidthMinutes to max, was " + selectionWidthMinutes + ", now " + maxSelectionWidthMinutes); } selectionWidthMinutes = maxSelectionWidthMinutes; } updateTimeline(); timelineLayer.doPrepare(); } doPrepare(); return true; } public boolean mouseMoved(MouseEvent e) { updateMouseTimeDisplay(e); return true; } public void mouseMoved() { } protected double updateMouseTimeDisplay(MouseEvent e) { Projection proj = getProjection(); Point2D latLong = proj.inverse(e.getPoint()); double lon = latLong.getX(); double endTime = TimelineLayer.forwardProjectMillis(gameEndTime - gameStartTime); if (lon < 0) { lon = 0; } else if (lon > endTime) { lon = endTime; } long offsetMillis = TimelineLayer.inverseProjectMillis(lon); timelineLayer.updateMouseTimeDisplay(new Long(offsetMillis)); return lon; } public void componentHidden(ComponentEvent e) { } public void componentMoved(ComponentEvent e) { } public void componentResized(ComponentEvent e) { finalizeProjection(); } public void componentShown(ComponentEvent e) { } public LabelPanel getTimeLabels() { if (labelPanel == null) { labelPanel = new LabelPanel(); } return labelPanel; } public void updateTimeLabels(long startTime, long endTime) { LabelPanel lp = getTimeLabels(); lp.updateTimeLabels(startTime, endTime); } class LabelPanel extends JPanel implements com.bbn.openmap.gui.MapPanelChild { protected JComponent timeStartLabel; protected JComponent timeEndLabel; public final static String NO_TIME_STRING = "--/--/-- (--:--:--)"; public LabelPanel() { GridBagLayout gridbag = new GridBagLayout(); GridBagConstraints c = new GridBagConstraints(); setLayout(gridbag); if (realTimeMode) { JButton timeStartLabelButton = new JButton(NO_TIME_STRING); timeStartLabelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { for (ITimeBoundsUserActionsListener listener : timeBoundsUserActionsListeners) { listener.invokeDateSelectionGUI(false); } } }); timeStartLabel = timeStartLabelButton; Font f = timeStartLabel.getFont(); f = new Font(f.getFamily(), f.getStyle(), f.getSize() - 1); timeStartLabel.setFont(f); gridbag.setConstraints(timeStartLabel, c); add(timeStartLabel); c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 1.0f; JLabel buffer = new JLabel(); gridbag.setConstraints(buffer, c); add(buffer); renderFixedSelection.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { long selectionStart = timelineLayer.getSelectionStart(); long selectionEnd = timelineLayer.getSelectionEnd(); if (selectionStart > 0 && selectionEnd > 0) { for (ITimeBoundsUserActionsListener listener : timeBoundsUserActionsListeners) { listener.setFixedRenderRange(selectionStart, selectionEnd); } } } }); renderFixedSelection.setEnabled(false); renderFixedSelection.setFont(f); c.weightx = 0f; gridbag.setConstraints(renderFixedSelection, c); add(renderFixedSelection); c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 1.0f; buffer = new JLabel(); gridbag.setConstraints(buffer, c); add(buffer); zoomToSelection.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { long selectionStart = timelineLayer.getSelectionStart(); long selectionEnd = timelineLayer.getSelectionEnd(); if (selectionStart > 0 && selectionEnd > 0) { timelineLayer.clearSelection(); userHasChangedScale = false; for (ITimeBoundsUserActionsListener listener : timeBoundsUserActionsListeners) { listener.setTimeBounds(selectionStart, selectionEnd); } updateTimeBounds(selectionStart, selectionEnd); updateTimeline(); } } }); zoomToSelection.setEnabled(false); zoomToSelection.setFont(f); c.weightx = 0f; gridbag.setConstraints(zoomToSelection, c); add(zoomToSelection); c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 1.0f; buffer = new JLabel(); gridbag.setConstraints(buffer, c); add(buffer); JButton jumpToRealTime = new JButton("Jump to Real Time"); jumpToRealTime.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { userHasChangedScale = false; for (ITimeBoundsUserActionsListener listener : timeBoundsUserActionsListeners) { listener.jumpToRealTime(); } updateTimeline(); } }); jumpToRealTime.setFont(f); c.weightx = 0f; gridbag.setConstraints(jumpToRealTime, c); add(jumpToRealTime); c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 1.0f; buffer = new JLabel(); gridbag.setConstraints(buffer, c); add(buffer); c.fill = GridBagConstraints.NONE; c.weightx = 0f; JButton timeEndLabelButton = new JButton(NO_TIME_STRING); timeEndLabelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { for (ITimeBoundsUserActionsListener listener : timeBoundsUserActionsListeners) { listener.invokeDateSelectionGUI(true); } } }); timeEndLabel = timeEndLabelButton; timeEndLabel.setFont(f); gridbag.setConstraints(timeEndLabel, c); add(timeEndLabel); } else { timeStartLabel = new JLabel(NO_TIME_STRING); Font f = timeStartLabel.getFont(); f = new Font(f.getFamily(), f.getStyle(), f.getSize() - 1); timeStartLabel.setFont(f); gridbag.setConstraints(timeStartLabel, c); add(timeStartLabel); c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 1.0f; JLabel buffer = new JLabel(); gridbag.setConstraints(buffer, c); add(buffer); c.fill = GridBagConstraints.NONE; c.weightx = 0f; timeEndLabel = new JLabel(NO_TIME_STRING, JLabel.RIGHT); timeEndLabel.setFont(f); gridbag.setConstraints(timeEndLabel, c); add(timeEndLabel); } } public String getPreferredLocation() { return BorderLayout.SOUTH; } public void setPreferredLocation(String string) { } public void updateTimeLabels(long startTime, long endTime) { if (realTimeMode) { ((JButton) timeStartLabel).setText(getLabelStringForTime(startTime)); ((JButton) timeEndLabel).setText(getLabelStringForTime(endTime)); } else { ((JLabel) timeStartLabel).setText(getLabelStringForTime(startTime)); ((JLabel) timeEndLabel).setText(getLabelStringForTime(endTime)); } } public String getLabelStringForTime(long time) { String ret = NO_TIME_STRING; if (time != Long.MAX_VALUE && time != Long.MIN_VALUE) { Date date = new Date(time); ret = TimePanel.dateFormat.format(date); } return ret; } public String getParentName() { // TODO Auto-generated method stub return null; } } public void paint(Graphics g) { try { super.paint(g); } catch (Exception e) { if (logger.isLoggable(Level.FINE)) { logger.warning(e.getMessage()); e.printStackTrace(); } } } public static class TimeDrape extends OMRect { int lo; int to; int ro; int bo; public TimeDrape(int leftOffset, int topOffset, int rightOffset, int bottomOffset) { super(0, 0, 0, 0); lo = leftOffset; to = topOffset; ro = rightOffset; bo = bottomOffset; } public boolean generate(Projection proj) { setLocation(0 + lo, 0 + to, proj.getWidth() + ro, proj.getHeight() + bo); return super.generate(proj); } } public void updateTimeBounds(TimeBoundsEvent tbe) { if (logger.isLoggable(Level.FINE)) { logger.fine("updating time bounds: " + tbe); } TimeBounds timeBounds = (TimeBounds) tbe.getNewTimeBounds(); if (timeBounds != null) { updateTimeBounds(timeBounds.getStartTime(), timeBounds.getEndTime()); } else { // TODO handle when time bounds are null, meaning when no time // bounds providers are active. } } public void updateTimeBounds(long start, long end) { // Recall that currentTime is in relative space (assumes start == 0) long boundsStartOffset = start - gameStartTime; currentTime -= boundsStartOffset; selectionCenter = TimelineLayer.forwardProjectMillis(currentTime); gameStartTime = start; gameEndTime = end; updateTimeLabels(gameStartTime, gameEndTime); // DateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy // HH:mm:ss"); // Date date = new Date(gameStartTime); // String sts = dateFormat.format(date); // date.setTime(gameEndTime); // String ets = dateFormat.format(date); maxSelectionWidthMinutes = TimelineLayer.forwardProjectMillis(gameEndTime - gameStartTime); if (realTimeMode && !userHasChangedScale) { selectionWidthMinutes = maxSelectionWidthMinutes; } else { if (selectionWidthMinutes > maxSelectionWidthMinutes || selectionWidthMinutes < .0001) { if (logger.isLoggable(Level.FINE)) { logger.fine("resetting selectionWidthMinutes to max (time bounds property change), was " + selectionWidthMinutes + ", now " + maxSelectionWidthMinutes); } selectionWidthMinutes = maxSelectionWidthMinutes; } } finalizeProjection(); updateTimeline(); doPrepare(); repaint(); } /** * Treat mouse wheel rotations like slider-handle drags. * * @param rot The number of rotation clicks (positive for zoom in, negative * for zoom out). */ public void adjustZoomFromMouseWheel(int rot) { Projection projection = getProjection(); if (projection == null) { return; // Huhn? } setUserHasChangedScale(true); // Determine the effect of growing / shrinking the slider scale by 'rot' // pixels // So given current selection width (in minutes) and minutes-per-pixel, // just // apply rot as a delta Point2D minutesPnt0 = projection.inverse(0, 0); Point2D minutesPnt1 = projection.inverse(1, 0); double minutesPerPixel = minutesPnt1.getX() - minutesPnt0.getX(); double minSelectionWidthMinutes = minutesPerPixel * sliderPointHalfWidth * 2; double selectionWidthPixels = selectionWidthMinutes / minutesPerPixel; double multiplier = selectionWidthPixels / 40; // Use a multiplier selectionWidthMinutes += rot * minutesPerPixel * multiplier; if (selectionWidthMinutes < minSelectionWidthMinutes) { selectionWidthMinutes = minSelectionWidthMinutes; } if (selectionWidthMinutes > maxSelectionWidthMinutes) { selectionWidthMinutes = maxSelectionWidthMinutes; } updateTimeline(); doPrepare(); } public void addTimeBoundsUserActionsListener(ITimeBoundsUserActionsListener timeBoundsUserActionsListener) { timeBoundsUserActionsListeners.add(timeBoundsUserActionsListener); } public void removeTimeBoundsUserActionsListener(ITimeBoundsUserActionsListener timeBoundsUserActionsListener) { timeBoundsUserActionsListeners.remove(timeBoundsUserActionsListener); } public void clearFixedRenderRange() { for (ITimeBoundsUserActionsListener listener : timeBoundsUserActionsListeners) { listener.clearFixedRenderRange(); } } void setSelectionValid(boolean valid) { zoomToSelection.setEnabled(valid); renderFixedSelection.setEnabled(valid); } }
true
true
public synchronized OMGraphicList getControlWidgetList(Projection proj) { Projection projection = getProjection(); OMGraphicList controlWidgetList = new OMGraphicList(); // triangle indicating center of selection ImageIcon selectionPointImage; DrawingAttributes da = new DrawingAttributes(); da.setFillPaint(TimelineLayer.tint); da.setLinePaint(TimelineLayer.tint); IconPart ip = new BasicIconPart(new Polygon(new int[] { 50, 90, 10, 50 }, new int[] { 10, 90, 90, 10 }, 4), da); selectionPointImage = OMIconFactory.getIcon(32, 32, ip); OMScalingIcon selectionPoint = new OMScalingIcon(0f, 0f, -5, 6, selectionPointImage, 1.0f); final float selectionPointScale = 1.8f; selectionPoint.setMaxScale(selectionPointScale); selectionPoint.setMinScale(selectionPointScale); controlWidgetList.add(selectionPoint); boundsRectLeftHandle = new OMRect(0, 0, 0, 0); boundsRectLeftHandle.setFillPaint(Color.black); controlWidgetList.add(boundsRectLeftHandle); boundsRectRightHandle = new OMRect(0, 0, 0, 0); boundsRectRightHandle.setFillPaint(Color.black); controlWidgetList.add(boundsRectRightHandle); int[] xs = new int[8]; int[] ys = new int[8]; contextPoly = new OMPoly(xs, ys); contextPoly.setFillPaint(Color.white); controlWidgetList.add(contextPoly); baseLine = new OMLine(0, 0, 0, 0); baseLine.setLinePaint(Color.BLACK); baseLine.setStroke(new BasicStroke(2)); controlWidgetList.add(baseLine); if (projection == null) { return controlWidgetList; // Huhn? } double screenWidth = projection.getWidth(); float scale = (float) (magicScaleFactor * (double) TimelineLayer.forwardProjectMillis(gameEndTime - gameStartTime) / screenWidth); Point2D projCenter = projection.getCenter(); // TODO reconsider proper test here - for the moment, just brute-force // reproject always if (projCenter.getX() > selectionWidthMinutes || scale != projection.getScale()) { double nCenterLon = TimelineLayer.forwardProjectMillis(gameEndTime - gameStartTime) / 2f; projCenter.setLocation(nCenterLon, 0); projection = new Cartesian(projCenter, scale, projection.getWidth(), projection.getHeight()); setProjection(projection); } // Reset primary handle int contextBuffer = (int) (projection.getHeight() * .4); // If 'selectionCenter' is outside current time bounds, first attempt to // recompute from currentTime if (selectionCenter * 60.0 * TimeUnit.SECONDS.toMillis(1) > (gameEndTime - gameStartTime) || selectionCenter < 0) { selectionCenter = TimelineLayer.forwardProjectMillis(currentTime); } // And if _that_ fails, just clamp // DFD changed from TimeUnit.MINUTE.toMillis(1) to MILLISECONDS because // Java 5 doesn't have MINUTE if (selectionCenter * TimeUnit.MILLISECONDS.toMillis(60000) > (gameEndTime - gameStartTime)) { selectionCenter = (gameEndTime - gameStartTime) / TimeUnit.MILLISECONDS.toMillis(60000); } if (selectionCenter < 0) { selectionCenter = 0; } int x = (int) projection.forward(0, selectionCenter).getX(); // Reset bounds and handles Point2D sliderEndPoint = projection.forward(0, selectionWidthMinutes); Point2D origin = projection.forward(0, 0); int selectionHalfWidth = (int) ((sliderEndPoint.getX() - origin.getX()) / 2); int north = contextBuffer; int west = x - selectionHalfWidth; int south = projection.getHeight() - 1; int east = x + selectionHalfWidth; int mid = contextBuffer + 1 + (south - contextBuffer) / 2; if (logger.isLoggable(Level.FINE)) { logger.fine("selectionCenter:" + selectionCenter + ", selectionWidthMinutes:" + selectionWidthMinutes + ", x:" + x + ", origin:" + origin); logger.fine(" projection:" + projection); } selectionPoint.setLon((float) selectionCenter); selectionPoint.generate(projection); // and the two handles for the bounds int handleWest = west - sliderPointHalfWidth; int handleEast = west + sliderPointHalfWidth; final int sliderPointHalfHeight = 2; boundsRectLeftHandle.setLocation(handleWest, north + sliderPointHalfHeight, handleEast, south - sliderPointHalfHeight); boundsRectLeftHandle.generate(projection); handleWest = east - sliderPointHalfWidth; handleEast = east + sliderPointHalfWidth; boundsRectRightHandle.setLocation(handleWest, north + sliderPointHalfHeight, handleEast, south - sliderPointHalfHeight); boundsRectRightHandle.generate(projection); // and the context lines, that show how the current selection maps to // the timeline above xs = contextPoly.getXs(); ys = contextPoly.getYs(); xs[0] = 0; ys[0] = -1; xs[1] = 0; ys[1] = north; xs[2] = west; ys[2] = north; xs[3] = west; ys[3] = south; xs[4] = east; ys[4] = south; xs[5] = east; ys[5] = north; xs[6] = projection.getWidth() - 1; ys[6] = north; xs[7] = projection.getWidth() - 1; ys[7] = -1; contextPoly.generate(projection); baseLine.setPts(new int[] { 0, mid, projection.getWidth(), mid }); baseLine.generate(projection); return controlWidgetList; }
public synchronized OMGraphicList getControlWidgetList(Projection proj) { Projection projection = getProjection(); OMGraphicList controlWidgetList = new OMGraphicList(); // triangle indicating center of selection ImageIcon selectionPointImage; DrawingAttributes da = new DrawingAttributes(); da.setFillPaint(TimelineLayer.tint); da.setLinePaint(TimelineLayer.tint); IconPart ip = new BasicIconPart(new Polygon(new int[] { 50, 90, 10, 50 }, new int[] { 10, 90, 90, 10 }, 4), da); selectionPointImage = OMIconFactory.getIcon(32, 32, ip); OMScalingIcon selectionPoint = new OMScalingIcon(0f, 0f, 0, 6, selectionPointImage, 1.0f); final float selectionPointScale = 1.8f; selectionPoint.setMaxScale(selectionPointScale); selectionPoint.setMinScale(selectionPointScale); controlWidgetList.add(selectionPoint); boundsRectLeftHandle = new OMRect(0, 0, 0, 0); boundsRectLeftHandle.setFillPaint(Color.black); controlWidgetList.add(boundsRectLeftHandle); boundsRectRightHandle = new OMRect(0, 0, 0, 0); boundsRectRightHandle.setFillPaint(Color.black); controlWidgetList.add(boundsRectRightHandle); int[] xs = new int[8]; int[] ys = new int[8]; contextPoly = new OMPoly(xs, ys); contextPoly.setFillPaint(Color.white); controlWidgetList.add(contextPoly); baseLine = new OMLine(0, 0, 0, 0); baseLine.setLinePaint(Color.BLACK); baseLine.setStroke(new BasicStroke(2)); controlWidgetList.add(baseLine); if (projection == null) { return controlWidgetList; // Huhn? } double screenWidth = projection.getWidth(); float scale = (float) (magicScaleFactor * (double) TimelineLayer.forwardProjectMillis(gameEndTime - gameStartTime) / screenWidth); Point2D projCenter = projection.getCenter(); // TODO reconsider proper test here - for the moment, just brute-force // reproject always if (projCenter.getX() > selectionWidthMinutes || scale != projection.getScale()) { double nCenterLon = TimelineLayer.forwardProjectMillis(gameEndTime - gameStartTime) / 2f; projCenter.setLocation(nCenterLon, 0); projection = new Cartesian(projCenter, scale, projection.getWidth(), projection.getHeight()); setProjection(projection); } // Reset primary handle int contextBuffer = (int) (projection.getHeight() * .4); // If 'selectionCenter' is outside current time bounds, first attempt to // recompute from currentTime if (selectionCenter * 60.0 * TimeUnit.SECONDS.toMillis(1) > (gameEndTime - gameStartTime) || selectionCenter < 0) { selectionCenter = TimelineLayer.forwardProjectMillis(currentTime); } // And if _that_ fails, just clamp // DFD changed from TimeUnit.MINUTE.toMillis(1) to MILLISECONDS because // Java 5 doesn't have MINUTE if (selectionCenter * TimeUnit.MILLISECONDS.toMillis(60000) > (gameEndTime - gameStartTime)) { selectionCenter = (gameEndTime - gameStartTime) / TimeUnit.MILLISECONDS.toMillis(60000); } if (selectionCenter < 0) { selectionCenter = 0; } int x = (int) projection.forward(0, selectionCenter).getX(); // Reset bounds and handles Point2D sliderEndPoint = projection.forward(0, selectionWidthMinutes); Point2D origin = projection.forward(0, 0); int selectionHalfWidth = (int) ((sliderEndPoint.getX() - origin.getX()) / 2); int north = contextBuffer; int west = x - selectionHalfWidth; int south = projection.getHeight() - 1; int east = x + selectionHalfWidth; int mid = contextBuffer + 1 + (south - contextBuffer) / 2; if (logger.isLoggable(Level.FINE)) { logger.fine("selectionCenter:" + selectionCenter + ", selectionWidthMinutes:" + selectionWidthMinutes + ", x:" + x + ", origin:" + origin); logger.fine(" projection:" + projection); } selectionPoint.setLon((float) selectionCenter); selectionPoint.generate(projection); // and the two handles for the bounds int handleWest = west - sliderPointHalfWidth; int handleEast = west + sliderPointHalfWidth; final int sliderPointHalfHeight = 2; boundsRectLeftHandle.setLocation(handleWest, north + sliderPointHalfHeight, handleEast, south - sliderPointHalfHeight); boundsRectLeftHandle.generate(projection); handleWest = east - sliderPointHalfWidth; handleEast = east + sliderPointHalfWidth; boundsRectRightHandle.setLocation(handleWest, north + sliderPointHalfHeight, handleEast, south - sliderPointHalfHeight); boundsRectRightHandle.generate(projection); // and the context lines, that show how the current selection maps to // the timeline above xs = contextPoly.getXs(); ys = contextPoly.getYs(); xs[0] = 0; ys[0] = -1; xs[1] = 0; ys[1] = north; xs[2] = west; ys[2] = north; xs[3] = west; ys[3] = south; xs[4] = east; ys[4] = south; xs[5] = east; ys[5] = north; xs[6] = projection.getWidth() - 1; ys[6] = north; xs[7] = projection.getWidth() - 1; ys[7] = -1; contextPoly.generate(projection); baseLine.setPts(new int[] { 0, mid, projection.getWidth(), mid }); baseLine.generate(projection); return controlWidgetList; }
diff --git a/src/main/java/org/cujau/utils/csv/CSVSymbols.java b/src/main/java/org/cujau/utils/csv/CSVSymbols.java index 6e57613..d9df5dc 100644 --- a/src/main/java/org/cujau/utils/csv/CSVSymbols.java +++ b/src/main/java/org/cujau/utils/csv/CSVSymbols.java @@ -1,61 +1,61 @@ package org.cujau.utils.csv; import java.text.DecimalFormatSymbols; import java.util.Locale; public class CSVSymbols { private static final char DEFAULT_SEPARATOR = ','; private static final char ALTERNATE_SEPARATOR = ';'; private char separator; private String lineSeparator; public CSVSymbols() { this( Locale.getDefault() ); } public CSVSymbols( Locale locale ) { buildDefaults( locale ); } public void setRecordSeparator( char separator ) { this.separator = separator; } public char getRecordSeparator() { return separator; } public void setLineSeparator( String lineSeparator ) { this.lineSeparator = lineSeparator; } public String getLineSeparator() { return lineSeparator; } private void buildDefaults( Locale locale ) { separator = DEFAULT_SEPARATOR; lineSeparator = System.getProperty( "line.separator" ); // // Try to determine what the record separator should be. // DecimalFormatSymbols dfs = new DecimalFormatSymbols( locale ); - // The first part of this statement is to detect locales like 'fr' and 'de' where + // The first part of this statement is to detect locales like 'fr' and 'de' where // the decimal separator is not the 'en' standard '.'. // // The second part of this statement is to detect locales like 'de_CH' where the - // decimal separator is not the 'en' standard ','. + // grouping separator is not the 'en' standard ','. // // If either of these are detected, we will use the alternate separator (;) rather // than the standard (,) separator. // - if ( dfs.getDecimalSeparator() == DEFAULT_SEPARATOR || - dfs.getGroupingSeparator() != DEFAULT_SEPARATOR ) { - // Use the alternate separator as that is probably what Excel is expecting. + if ( dfs.getDecimalSeparator() == DEFAULT_SEPARATOR + || dfs.getGroupingSeparator() != DEFAULT_SEPARATOR ) { + // Use the alternate separator as that is probably what Excel is expecting. separator = ALTERNATE_SEPARATOR; } } }
false
true
private void buildDefaults( Locale locale ) { separator = DEFAULT_SEPARATOR; lineSeparator = System.getProperty( "line.separator" ); // // Try to determine what the record separator should be. // DecimalFormatSymbols dfs = new DecimalFormatSymbols( locale ); // The first part of this statement is to detect locales like 'fr' and 'de' where // the decimal separator is not the 'en' standard '.'. // // The second part of this statement is to detect locales like 'de_CH' where the // decimal separator is not the 'en' standard ','. // // If either of these are detected, we will use the alternate separator (;) rather // than the standard (,) separator. // if ( dfs.getDecimalSeparator() == DEFAULT_SEPARATOR || dfs.getGroupingSeparator() != DEFAULT_SEPARATOR ) { // Use the alternate separator as that is probably what Excel is expecting. separator = ALTERNATE_SEPARATOR; } }
private void buildDefaults( Locale locale ) { separator = DEFAULT_SEPARATOR; lineSeparator = System.getProperty( "line.separator" ); // // Try to determine what the record separator should be. // DecimalFormatSymbols dfs = new DecimalFormatSymbols( locale ); // The first part of this statement is to detect locales like 'fr' and 'de' where // the decimal separator is not the 'en' standard '.'. // // The second part of this statement is to detect locales like 'de_CH' where the // grouping separator is not the 'en' standard ','. // // If either of these are detected, we will use the alternate separator (;) rather // than the standard (,) separator. // if ( dfs.getDecimalSeparator() == DEFAULT_SEPARATOR || dfs.getGroupingSeparator() != DEFAULT_SEPARATOR ) { // Use the alternate separator as that is probably what Excel is expecting. separator = ALTERNATE_SEPARATOR; } }