diff
stringlengths
164
2.11M
is_single_chunk
bool
2 classes
is_single_function
bool
2 classes
buggy_function
stringlengths
0
335k
fixed_function
stringlengths
23
335k
diff --git a/src/com/github/ivanshchitov/sequencerealnumbers/SequenceRealNumbersTest.java b/src/com/github/ivanshchitov/sequencerealnumbers/SequenceRealNumbersTest.java index a788b7f..192bf4f 100644 --- a/src/com/github/ivanshchitov/sequencerealnumbers/SequenceRealNumbersTest.java +++ b/src/com/github/ivanshchitov/sequencerealnumbers/SequenceRealNumbersTest.java @@ -1,196 +1,195 @@ package com.github.ivanshchitov.sequencerealnumbers; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * Test class for SequenceRealNumbers class. * * @author Ivan Shchitov */ public class SequenceRealNumbersTest { /** * Tests getMaximum() method with one element. */ @Test public void getMaximumTest1() { SequenceRealNumbers sequenceTest = new SequenceRealNumbers(); sequenceTest.add(1.0); assertEquals( Double.doubleToLongBits(1), Double.doubleToLongBits(sequenceTest.getMaximum()) ); - System.out.println("Finished test on getMaximum() method with one element."); + System.out.println("Finished getMaximumTest1."); } /** * Tests getMaximum() method with same elements. */ @Test public void getMaximumTest2() { SequenceRealNumbers sequenceTest = new SequenceRealNumbers(); sequenceTest.add(1.0); sequenceTest.add(1.0); sequenceTest.add(1.0); assertEquals( Double.doubleToLongBits(1), Double.doubleToLongBits(sequenceTest.getMaximum()) ); - System.out.println("Finished test on getMaximum() method with same elements."); + System.out.println("Finished getMaximumTest2."); } /** * Tests getMaximum() method with negative elements. */ @Test public void getMaximumTest3() { SequenceRealNumbers sequenceTest = new SequenceRealNumbers(); sequenceTest.add(-1.0); sequenceTest.add(-2.0); assertEquals( Double.doubleToLongBits(-1), Double.doubleToLongBits(sequenceTest.getMaximum()) ); - System.out.println("Finished test on getMaximum() method with negative elements."); + System.out.println("Finished getMaximumTest3."); } /** * Tests getMinimum() method with one element. */ @Test public void getMinimumTest1() { SequenceRealNumbers sequenceTest = new SequenceRealNumbers(); sequenceTest.add(1.0); assertEquals( Double.doubleToLongBits(1), Double.doubleToLongBits(sequenceTest.getMinimum()) ); - System.out.println("Finished test on getMinimum() method with one element."); + System.out.println("Finished getMinimumTest1."); } /** * Tests getMinimum() method with same element. */ @Test public void getMinimumTest2() { SequenceRealNumbers sequenceTest = new SequenceRealNumbers(); sequenceTest.add(1.0); sequenceTest.add(1.0); sequenceTest.add(1.0); assertEquals( Double.doubleToLongBits(1), Double.doubleToLongBits(sequenceTest.getMinimum()) ); - System.out.println("Finished test on getMinimum() method with same element."); + System.out.println("Finished getMinimumTest2."); } /** * Tests getMinimum() method with negative element. */ @Test public void getMinimumTest3() { SequenceRealNumbers sequenceTest = new SequenceRealNumbers(); sequenceTest.add(-1.0); sequenceTest.add(-2.0); assertEquals( Double.doubleToLongBits(-2), Double.doubleToLongBits(sequenceTest.getMinimum()) ); - System.out.println("Finished test on getMinimum() method with negative element."); + System.out.println("Finished getMinimumTest3."); } /** * Tests getAverage() method with sum elements = 0. */ @Test public void getAverageTest1() { SequenceRealNumbers sequenceTest = new SequenceRealNumbers(); sequenceTest.add(1.0); sequenceTest.add(0); sequenceTest.add(-1); assertEquals( Double.doubleToLongBits(0), Double.doubleToLongBits(sequenceTest.getAverage()) ); - System.out.println("Finished test on getAverage() method with sum elements = 0."); + System.out.println("Finished getAverageTest1."); } /** * Tests getAverage() method with same elements. */ @Test public void getAverageTest2() { SequenceRealNumbers sequenceTest = new SequenceRealNumbers(); sequenceTest.add(1.0); sequenceTest.add(1.0); sequenceTest.add(1); assertEquals( Double.doubleToLongBits(1), Double.doubleToLongBits(sequenceTest.getAverage()) ); - System.out.println("Finished test on getAverage() method with same elements."); + System.out.println("Finished getAverageTest2."); } /** * Tests getMedian() with an even size of sequence. */ @Test public void evenSizeSequenceMedian() { SequenceRealNumbers sequenceTest = new SequenceRealNumbers(); sequenceTest.add(2.0); sequenceTest.add(0.2); assertEquals( Double.doubleToLongBits(1.1), Double.doubleToLongBits(sequenceTest.getMedian()) ); - System.out.println("Finished test on getMedian() method with even size."); + System.out.println("Finished evenSizeSequenceMedian."); } /** * Tests getMedian() with an even size of sequence. */ @Test public void unevenSizeSequenceMedian() { SequenceRealNumbers sequenceTest = new SequenceRealNumbers(); sequenceTest.add(1.0); assertEquals( Double.doubleToLongBits(1), Double.doubleToLongBits(sequenceTest.getMedian()) ); - System.out.println("Finished test on getMedian() method with uneven size."); + System.out.println("Finished unevenSizeSequenceMedian."); } /** * Tests getSize() method. */ @Test public void getSizeTest() { SequenceRealNumbers sequenceTest = new SequenceRealNumbers(); sequenceTest.add(1.0); sequenceTest.add(0.2); sequenceTest.add(3); assertEquals( Double.doubleToLongBits(3), Double.doubleToLongBits(sequenceTest.getSize()) ); - System.out.println("Finished test on getSize() method."); + System.out.println("Finished getSizeTest."); } /** * Tests getElement() method. */ @Test public void getElementTest() { SequenceRealNumbers sequenceTest = new SequenceRealNumbers(); sequenceTest.add(1.0); try { sequenceTest.getElement(-1); } catch (ArrayIndexOutOfBoundsException e) { - System.out.println("Finished test on getElement() method.\n" - + "We caught ArrayIndexOutOfBoundsException."); + System.out.println("Finished getElementTest."); } } }
false
false
null
null
diff --git a/src/main/java/net/minekingdom/Sepia/environment/Expression.java b/src/main/java/net/minekingdom/Sepia/environment/Expression.java index 0b9e343..959f831 100644 --- a/src/main/java/net/minekingdom/Sepia/environment/Expression.java +++ b/src/main/java/net/minekingdom/Sepia/environment/Expression.java @@ -1,315 +1,314 @@ package net.minekingdom.Sepia.environment; import java.text.ParseException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Stack; import org.spout.api.command.CommandSource; import net.minekingdom.Sepia.environment.heap.Bucket; import net.minekingdom.Sepia.environment.heap.Heap; import net.minekingdom.Sepia.script.Token; import net.minekingdom.Sepia.script.Variable; import net.minekingdom.Sepia.script.operator.ArrayBuilder; import net.minekingdom.Sepia.script.operator.Grouping; import net.minekingdom.Sepia.script.operator.Operator; import net.minekingdom.Sepia.script.operator.arithmetic.Addition; import net.minekingdom.Sepia.script.operator.arithmetic.Subtraction; import net.minekingdom.Sepia.script.value.Value; import net.minekingdom.Sepia.script.value.primitive.DecimalValue; import net.minekingdom.Sepia.script.value.primitive.IntegerValue; import net.minekingdom.Sepia.script.value.primitive.StringValue; import net.minekingdom.Sepia.script.value.structure.PlayerValue; import net.minekingdom.Sepia.script.value.structure.VectorValue; import net.minekingdom.Sepia.script.value.structure.WorldValue; public class Expression { private List<Token> execution; private Map<String, Variable> variables; private Expression(List<Token> execution) { this.execution = execution; this.variables = new HashMap<String, Variable>(); for (Token t : execution) { if (t instanceof Variable) { variables.put(t.toString(), (Variable) t); } } } public boolean hasVariable(String name) { return variables.containsKey(name); } public void setVariable(String name, Object value) { Variable var = variables.get(name); if (var == null) { throw new IllegalArgumentException("Variable " + name + " does not exist in expression"); } setVariable(var, value); } public void populate(Heap heap) { for (Map.Entry<String, Variable> entry : this.variables.entrySet()) { Bucket bucket = heap.get(entry.getKey()); if (bucket != null) { setVariable(entry.getValue(), bucket.getValue()); } } } public void clearVariables() { for (Variable var : this.variables.values()) { var.setValue(null); } } public Value evaluate(CommandSource source) { List<Token> list = new ArrayList<Token>(execution); for (int i = 0; i < list.size(); i++) { Token t = list.get(i); if (t instanceof Operator) { Operator o = (Operator) t; LinkedList<Token> l = new LinkedList<Token>(); for (int j = 0; j < o.getNumberOfArguments(); j++) { l.addFirst(list.get(i - j - 1)); } Token[] values = new Token[l.size()]; l.toArray(values); Value result; try { result = o.invoke(source, values); } catch (ClassCastException ex) { List<Token> tmp = new ArrayList<Token>(); Collections.addAll(tmp, values); throw new RuntimeException("Cannot apply operation " + t + " to " + tmp); } for (int j = 0; j < o.getNumberOfArguments() + 1; j++) { list.remove(i - o.getNumberOfArguments()); } i -= o.getNumberOfArguments(); list.add(i, result); } } if (list.size() != 1) { throw new RuntimeException("Invalid expression"); } return (Value) list.get(0); } private void setVariable(Variable var, Object value) { var.setValue(Value.getValue(value)); } public static Expression build(String expr) throws ParseException { return new Expression(getPostfixOrder(expr)); } private static List<Token> getPostfixOrder(String expr) throws ParseException { ShuntingYard sy = new ShuntingYard(); int lastLeftParenthesis = 0; main: for ( int i = 0; i < expr.length(); i++ ) { - System.out.println(expr.charAt(i)); - if (Character.isDigit(expr.charAt(i))) { int size = 0; while (i + ++size < expr.length() && (isAlphaNumeric(expr.charAt(i + size)) || expr.charAt(i + size) == '.')); String val = expr.substring(i, i + size); try { sy.processValue(new IntegerValue(Long.parseLong(val))); } catch (NumberFormatException ex){ try { sy.processValue(new DecimalValue(Double.parseDouble(val))); } catch (NumberFormatException ex2){ throw new ParseException("Invalid number format", i); } } i += size - 1; } else if (Character.isAlphabetic(expr.charAt(i))) { int size = 0; while (i + ++size < expr.length() && isAlphaNumeric(expr.charAt(i + size))); String val = expr.substring(i, i + size); sy.processVariable(new Variable(val)); i += size - 1; } else if (expr.charAt(i) == '"' || expr.charAt(i) == '\'') { char delim = expr.charAt(i); int size = 0; while (i + ++size < expr.length() && (expr.charAt(i + size) != delim || expr.charAt(i + size - 1) == '\\')); if (expr.charAt(i + size) != delim) { throw new ParseException("Mismatching quotation marks", i); } sy.processValue(new StringValue(expr.substring(i + 1, i + size))); i += size; } else if (expr.charAt(i) == '(') { lastLeftParenthesis = i; sy.processOperator(Grouping.LEFT_PARENTHESIS, i); } else if (expr.charAt(i) == ')') { sy.processRightParenthesis(i); } else if (expr.charAt(i) == '<') { int size = 0; while (i + ++size < expr.length() && expr.charAt(i + size) != '>'); if (i + size == expr.length()) { throw new ParseException("Mismatching brackets in vector definition", i); } String val = expr.substring(i + 1, i + size); sy.processValue(VectorValue.parse(val)); i += size; } else if (expr.charAt(i) == '[') { int size = 0; while (i + ++size < expr.length() && expr.charAt(i + size) != ']'); if (i + size == expr.length()) { throw new ParseException("Mismatching brackets in vector definition", i); } String val = expr.substring(i + 1, i + size); int n = 0; if (val.length() != 0) { LinkedList<Token> list = new LinkedList<Token>(); ++n; int start = val.length(); int end = start; while ((start = val.lastIndexOf(',', start - 1)) != -1) { list.addAll(0, getPostfixOrder(val.substring(start + 1, end))); end = start; ++n; } list.addAll(0, getPostfixOrder(val.substring(0, end))); sy.addAll(list); } sy.processArrayBuilder(n, i); i += size; } else if (expr.charAt(i) == '@') { int size = 0; while (i + ++size < expr.length() && isAlphaNumeric(expr.charAt(i + size))); String val = expr.substring(i + 1, i + size); sy.processValue(new PlayerValue(val)); i += size - 1; } else if (expr.charAt(i) == '#') { int size = 0; while (i + ++size < expr.length() && isAlphaNumeric(expr.charAt(i + size))); String val = expr.substring(i + 1, i + size); sy.processValue(new WorldValue(val)); i += size - 1; } else { // Operator handling for (Operator o : Operator.OPERATORS) { if (expr.startsWith(o.toString(), i)) { o.process(sy, i); i += o.toString().length() - 1; continue main; } } if (!Character.isWhitespace(expr.charAt(i))) { throw new ParseException("Syntax error on token \"" + expr.charAt(i) + "\", delete this token", i); } } } sy.end(lastLeftParenthesis); return new ArrayList<Token>(sy.result); } private static boolean isAlphaNumeric(char c) { return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '_'; } public static class ShuntingYard { private Stack<Operator> operators; private List<Token> result; private Token last; public ShuntingYard() { this.operators = new Stack<Operator>(); this.result = new LinkedList<Token>(); } public void addAll(List<Token> postfixTokens) { this.result.addAll(postfixTokens); this.last = this.result.get(this.result.size() - 1); } public void processArrayBuilder(int n, int index) throws ParseException { processOperator(new ArrayBuilder(n), index); // we have to trick the system because the ArrayBuilder needs to stand as a value last = new Value(""); } public void processVariable(Variable variable) { this.result.add(last = variable); } public void processValue(Value value) { this.result.add(last = value); } public void processOperator(Operator o, int index) throws ParseException { if ( (result.isEmpty() || last instanceof Operator) && !(o instanceof Addition.Unary) && !(o instanceof Subtraction.Unary) - && !(o instanceof ArrayBuilder)) { + && !(o instanceof ArrayBuilder) + && !(o instanceof Grouping.LeftParenthesis)) { throw new ParseException("Syntax error on token \"" + o + "\", delete this token", index); } while (!operators.isEmpty() && !(operators.peek() instanceof Grouping.LeftParenthesis) && o.getPredecence() >= operators.peek().getPredecence()) { result.add(operators.pop()); } operators.push(o); last = o; } public void processRightParenthesis(int index) throws ParseException { while (!operators.isEmpty() && !(operators.peek() instanceof Grouping.LeftParenthesis)) { result.add(operators.pop()); } if (operators.isEmpty()) { throw new ParseException("Mismatching parenthesis", index); } operators.pop(); } public void end(int index) throws ParseException { while (!operators.isEmpty() && !(operators.peek() instanceof Grouping.LeftParenthesis)) { result.add(operators.pop()); } if (!operators.isEmpty()) { throw new ParseException("Mismatching parenthesis", index); } } public Token getLastToken() { return last; } } }
false
false
null
null
diff --git a/msv/src/com/sun/msv/reader/xmlschema/ComplexTypeDeclState.java b/msv/src/com/sun/msv/reader/xmlschema/ComplexTypeDeclState.java index ad0df36c..6e6373d2 100644 --- a/msv/src/com/sun/msv/reader/xmlschema/ComplexTypeDeclState.java +++ b/msv/src/com/sun/msv/reader/xmlschema/ComplexTypeDeclState.java @@ -1,164 +1,171 @@ /* * @(#)$Id$ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.xmlschema; import com.sun.msv.datatype.xsd.XSDatatype; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.SimpleNameClass; import com.sun.msv.grammar.ReferenceContainer; import com.sun.msv.grammar.xmlschema.AttributeWildcard; import com.sun.msv.grammar.xmlschema.ComplexTypeExp; import com.sun.msv.util.StartTagInfo; import com.sun.msv.reader.State; import org.xml.sax.Locator; /** * used to parse &lt;complexType&gt; element. * * @author <a href="mailto:[email protected]">Kohsuke KAWAGUCHI</a> */ public class ComplexTypeDeclState extends RedefinableDeclState implements AnyAttributeOwner { /** ComplexType object that we are now constructing. */ protected ComplexTypeExp decl; protected ReferenceContainer getContainer() { return ((XMLSchemaReader)reader).currentSchema.complexTypes; } protected void startSelf() { super.startSelf(); final XMLSchemaReader reader = (XMLSchemaReader)this.reader; String name = startTag.getAttribute("name"); if( name==null ) { if( isGlobal() ) reader.reportError( reader.ERR_MISSING_ATTRIBUTE, "complexType", "name" ); decl = new ComplexTypeExp( reader.currentSchema, null ); } else { if( isRedefine() ) // in redefine mode, use temporary object. // parsed complexType will be copied into the original one. decl = new ComplexTypeExp( reader.currentSchema, name ); else { decl = reader.currentSchema.complexTypes.getOrCreate(name); - if( decl.body.exp!=null ) + // MSV has pre-defiend types in xsd namespace (such as xs:anyType) + // this causes a problem when we are parsing schema4schema. + // to avoid this problem, we won't issue this error when we are + // parsing schema4schema. + // + // But this is more like a quick hack. What is the correct way to + // solve this problem? + if( decl.body.exp!=null && reader.currentSchema!=reader.xsdSchema ) reader.reportError( new Locator[]{this.location,reader.getDeclaredLocationOf(decl)}, reader.ERR_DUPLICATE_COMPLEXTYPE_DEFINITION, new Object[]{name} ); } } // set the final attribute to ComplexTypeExp. decl.finalValue = parseFinalValue( "final", reader.finalDefault ); decl.block = parseFinalValue( "block", reader.blockDefault ); } /** * parses the value of the block/finel attribute. */ private int parseFinalValue( String attName, String defaultValue ) { int r = 0; String value = startTag.getAttribute(attName); if( value==null ) value = defaultValue; if( value!=null ) { if( value.indexOf("#all")>=0 ) r |= ComplexTypeExp.RESTRICTION|ComplexTypeExp.EXTENSION; if( value.indexOf("extension")>=0 ) r |= ComplexTypeExp.EXTENSION; if( value.indexOf("restriction")>=0 ) r |= ComplexTypeExp.RESTRICTION; } return r; } public void setAttributeWildcard( AttributeWildcard local ) { decl.wildcard = local; } protected State createChildState( StartTagInfo tag ) { final XMLSchemaReader reader = (XMLSchemaReader)this.reader; // simpleContent, ComplexContent, group, all, choice, and sequence // are allowed only when we haven't seen type definition. if(tag.localName.equals("simpleContent") ) return reader.sfactory.simpleContent(this,tag,decl); if(tag.localName.equals("complexContent") ) return reader.sfactory.complexContent(this,tag,decl); State s = reader.createModelGroupState(this,tag); if(s!=null) return s; if( super.exp==null ) { // no content model was given. // I couldn't "decipher" what should we do in this case. // I assume "empty" just because it's most likely. exp = Expression.epsilon; } // TODO: attributes are prohibited after simpleContent/complexContent. // attribute, attributeGroup, and anyAttribtue can be specified // after content model is given. return reader.createAttributeState(this,tag); } protected Expression castExpression( Expression halfCastedExpression, Expression newChildExpression ) { if( halfCastedExpression==null ) return newChildExpression; // the first one // only the first one contains element. // the rest consists of attributes. // so this order of parameters is fine. return reader.pool.createSequence( newChildExpression, halfCastedExpression ); } protected Expression defaultExpression() { // if no content model is given, then this complex type is empty return Expression.epsilon; } protected Expression annealExpression(Expression contentType) { final XMLSchemaReader reader = (XMLSchemaReader)this.reader; String abstract_ = startTag.getAttribute("abstract"); if( "false".equals(abstract_) || abstract_==null ) // allow the content model to directly appear as this type. decl.setAbstract(false); else { decl.setAbstract(true); if( !"true".equals(abstract_) ) reader.reportError( reader.ERR_BAD_ATTRIBUTE_VALUE, "abstract", abstract_ ); // recover by ignoring this error. } String mixed = startTag.getAttribute("mixed"); if( "true".equals(mixed) ) contentType = reader.pool.createMixed(contentType); else if( mixed!=null && !"false".equals(mixed) ) reader.reportError( reader.ERR_BAD_ATTRIBUTE_VALUE, "mixed", mixed ); // recover by ignoring this error. decl.body.exp = contentType; if( isRedefine() ) { // copy new definition back into the original definition. oldDecl.redefine(decl); decl = (ComplexTypeExp)oldDecl; } reader.setDeclaredLocationOf(decl); reader.setDeclaredLocationOf(decl.body); return decl; } }
true
false
null
null
diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXContext.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXContext.java index 0d56bcde1..c37bcee50 100644 --- a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXContext.java +++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXContext.java @@ -1,647 +1,655 @@ /* * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved. * Copyright (c) 2010 JogAmp Community. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * - Redistribution of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistribution 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 Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN * MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL NOT BE LIABLE FOR * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR * ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR * DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use * in the design, construction, operation or maintenance of any nuclear * facility. * * Sun gratefully acknowledges that this software was originally authored * and developed by Kenneth Bradley Russell and Christopher John Kline. */ package jogamp.opengl.x11.glx; import java.nio.ByteBuffer; import java.nio.IntBuffer; import java.util.HashMap; import java.util.Map; import javax.media.nativewindow.AbstractGraphicsConfiguration; import javax.media.nativewindow.AbstractGraphicsDevice; import javax.media.nativewindow.NativeSurface; import javax.media.opengl.GLCapabilitiesImmutable; import javax.media.opengl.GLContext; import javax.media.opengl.GLException; import javax.media.opengl.GLProfile; import jogamp.nativewindow.x11.X11Lib; import jogamp.nativewindow.x11.X11Util; import jogamp.opengl.GLContextImpl; import jogamp.opengl.GLDrawableImpl; import jogamp.opengl.GLXExtensions; import com.jogamp.common.nio.Buffers; import com.jogamp.common.util.VersionNumber; import com.jogamp.gluegen.runtime.ProcAddressTable; import com.jogamp.gluegen.runtime.opengl.GLProcAddressResolver; import com.jogamp.nativewindow.x11.X11GraphicsDevice; import com.jogamp.opengl.GLExtensions; public class X11GLXContext extends GLContextImpl { private static final Map<String, String> functionNameMap; private static final Map<String, String> extensionNameMap; private GLXExt _glXExt; // Table that holds the addresses of the native C-language entry points for // GLX extension functions. private GLXExtProcAddressTable glXExtProcAddressTable; /** 1 MESA, 2 SGI, 0 undefined, -1 none */ private int hasSwapInterval = 0; private int hasSwapGroupNV = 0; // This indicates whether the context we have created is indirect // and therefore requires the toolkit to be locked around all GL // calls rather than just all GLX calls protected boolean isDirect; protected volatile VersionNumber glXServerVersion; protected volatile boolean isGLXVersionGreaterEqualOneThree; static { functionNameMap = new HashMap<String, String>(); functionNameMap.put("glAllocateMemoryNV", "glXAllocateMemoryNV"); functionNameMap.put("glFreeMemoryNV", "glXFreeMemoryNV"); extensionNameMap = new HashMap<String, String>(); extensionNameMap.put(GLExtensions.ARB_pbuffer, X11GLXDrawableFactory.GLX_SGIX_pbuffer); extensionNameMap.put(GLExtensions.ARB_pixel_format, X11GLXDrawableFactory.GLX_SGIX_pbuffer); // good enough } X11GLXContext(GLDrawableImpl drawable, GLContext shareWith) { super(drawable, shareWith); } @Override protected void resetStates() { // no inner state _glXExt=null; glXExtProcAddressTable = null; hasSwapInterval = 0; hasSwapGroupNV = 0; isDirect = false; glXServerVersion = null; isGLXVersionGreaterEqualOneThree = false; super.resetStates(); } @Override public final ProcAddressTable getPlatformExtProcAddressTable() { return getGLXExtProcAddressTable(); } public final GLXExtProcAddressTable getGLXExtProcAddressTable() { return glXExtProcAddressTable; } @Override public Object getPlatformGLExtensions() { return getGLXExt(); } public GLXExt getGLXExt() { if (_glXExt == null) { _glXExt = new GLXExtImpl(this); } return _glXExt; } @Override protected Map<String, String> getFunctionNameMap() { return functionNameMap; } @Override protected Map<String, String> getExtensionNameMap() { return extensionNameMap; } protected final boolean isGLXVersionGreaterEqualOneThree() { // fast-path: use cached boolean if(null != glXServerVersion) { return isGLXVersionGreaterEqualOneThree; } glXServerVersion = ((X11GLXDrawableFactory)drawable.getFactoryImpl()).getGLXVersionNumber(drawable.getNativeSurface().getGraphicsConfiguration().getScreen().getDevice()); isGLXVersionGreaterEqualOneThree = null != glXServerVersion ? glXServerVersion.compareTo(X11GLXDrawableFactory.versionOneThree) >= 0 : false; return isGLXVersionGreaterEqualOneThree; } + protected final void forceGLXVersionOneOne() { + glXServerVersion = X11GLXDrawableFactory.versionOneOne; + isGLXVersionGreaterEqualOneThree = false; + if(DEBUG) { + System.err.println("X11GLXContext.forceGLXVersionNumber: "+glXServerVersion); + } + } @Override public final boolean isGLReadDrawableAvailable() { return isGLXVersionGreaterEqualOneThree(); } private final boolean glXMakeContextCurrent(long dpy, long writeDrawable, long readDrawable, long ctx) { boolean res = false; try { if ( isGLXVersionGreaterEqualOneThree() ) { // System.err.println(getThreadName() +": X11GLXContext.makeCurrent: obj " + toHexString(hashCode()) + " / ctx "+toHexString(contextHandle)+": ctx "+toHexString(ctx)+", [write "+toHexString(writeDrawable)+", read "+toHexString(readDrawable)+"] - switch"); res = GLX.glXMakeContextCurrent(dpy, writeDrawable, readDrawable, ctx); } else if ( writeDrawable == readDrawable ) { // System.err.println(getThreadName() +": X11GLXContext.makeCurrent: obj " + toHexString(hashCode()) + " / ctx "+toHexString(contextHandle)+": ctx "+toHexString(ctx)+", [write "+toHexString(writeDrawable)+"] - switch"); res = GLX.glXMakeCurrent(dpy, writeDrawable, ctx); } else { // should not happen due to 'isGLReadDrawableAvailable()' query in GLContextImpl throw new InternalError("Given readDrawable but no driver support"); } } catch (RuntimeException re) { if( DEBUG_TRACE_SWITCH ) { System.err.println(getThreadName()+": Warning: X11GLXContext.glXMakeContextCurrent failed: "+re+", with "+ "dpy "+toHexString(dpy)+ ", write "+toHexString(writeDrawable)+ ", read "+toHexString(readDrawable)+ ", ctx "+toHexString(ctx)); re.printStackTrace(); } } return res; } @Override protected void destroyContextARBImpl(long ctx) { final long display = drawable.getNativeSurface().getDisplayHandle(); glXMakeContextCurrent(display, 0, 0, 0); GLX.glXDestroyContext(display, ctx); } private static final int ctx_arb_attribs_idx_major = 0; private static final int ctx_arb_attribs_idx_minor = 2; private static final int ctx_arb_attribs_idx_flags = 6; private static final int ctx_arb_attribs_idx_profile = 8; private static final int ctx_arb_attribs_rom[] = { /* 0 */ GLX.GLX_CONTEXT_MAJOR_VERSION_ARB, 0, /* 2 */ GLX.GLX_CONTEXT_MINOR_VERSION_ARB, 0, /* 4 */ GLX.GLX_RENDER_TYPE, GLX.GLX_RGBA_TYPE, // default /* 6 */ GLX.GLX_CONTEXT_FLAGS_ARB, 0, /* 8 */ 0, 0, /* 10 */ 0 }; @Override protected long createContextARBImpl(long share, boolean direct, int ctp, int major, int minor) { updateGLXProcAddressTable(); GLXExt _glXExt = getGLXExt(); if(DEBUG) { System.err.println(getThreadName()+": X11GLXContext.createContextARBImpl: "+getGLVersion(major, minor, ctp, "@creation") + ", handle "+toHexString(drawable.getHandle()) + ", share "+toHexString(share)+", direct "+direct+ ", glXCreateContextAttribsARB: "+toHexString(glXExtProcAddressTable._addressof_glXCreateContextAttribsARB)); } boolean ctBwdCompat = 0 != ( CTX_PROFILE_COMPAT & ctp ) ; boolean ctFwdCompat = 0 != ( CTX_OPTION_FORWARD & ctp ) ; boolean ctDebug = 0 != ( CTX_OPTION_DEBUG & ctp ) ; long ctx=0; IntBuffer attribs = Buffers.newDirectIntBuffer(ctx_arb_attribs_rom); attribs.put(ctx_arb_attribs_idx_major + 1, major); attribs.put(ctx_arb_attribs_idx_minor + 1, minor); if ( major > 3 || major == 3 && minor >= 2 ) { attribs.put(ctx_arb_attribs_idx_profile + 0, GLX.GLX_CONTEXT_PROFILE_MASK_ARB); if( ctBwdCompat ) { attribs.put(ctx_arb_attribs_idx_profile + 1, GLX.GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB); } else { attribs.put(ctx_arb_attribs_idx_profile + 1, GLX.GLX_CONTEXT_CORE_PROFILE_BIT_ARB); } } if ( major >= 3 ) { int flags = attribs.get(ctx_arb_attribs_idx_flags + 1); if( !ctBwdCompat && ctFwdCompat ) { flags |= GLX.GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB; } if( ctDebug ) { flags |= GLX.GLX_CONTEXT_DEBUG_BIT_ARB; } attribs.put(ctx_arb_attribs_idx_flags + 1, flags); } X11GLXGraphicsConfiguration config = (X11GLXGraphicsConfiguration)drawable.getNativeSurface().getGraphicsConfiguration(); AbstractGraphicsDevice device = config.getScreen().getDevice(); final long display = device.getHandle(); try { // critical path, a remote display might not support this command, // hence we need to catch the X11 Error within this block. X11Util.setX11ErrorHandler(true, DEBUG ? false : true); // make sure X11 error handler is set X11Lib.XSync(display, false); ctx = _glXExt.glXCreateContextAttribsARB(display, config.getFBConfig(), share, direct, attribs); } catch (RuntimeException re) { if(DEBUG) { Throwable t = new Throwable(getThreadName()+": Info: X11GLXContext.createContextARBImpl glXCreateContextAttribsARB failed with "+getGLVersion(major, minor, ctp, "@creation"), re); t.printStackTrace(); } } if(0!=ctx) { if (!glXMakeContextCurrent(display, drawable.getHandle(), drawableRead.getHandle(), ctx)) { if(DEBUG) { System.err.println(getThreadName()+": X11GLXContext.createContextARBImpl couldn't make current "+getGLVersion(major, minor, ctp, "@creation")); } // release & destroy glXMakeContextCurrent(display, 0, 0, 0); GLX.glXDestroyContext(display, ctx); ctx = 0; } else if (DEBUG) { System.err.println(getThreadName() + ": createContextARBImpl: OK "+getGLVersion(major, minor, ctp, "@creation")+", share "+share+", direct "+direct); } } else if (DEBUG) { System.err.println(getThreadName() + ": createContextARBImpl: NO "+getGLVersion(major, minor, ctp, "@creation")); } return ctx; } @Override protected boolean createImpl(GLContextImpl shareWith) { boolean direct = true; // try direct always isDirect = false; // fall back final X11GLXDrawableFactory factory = (X11GLXDrawableFactory)drawable.getFactoryImpl(); final X11GLXGraphicsConfiguration config = (X11GLXGraphicsConfiguration)drawable.getNativeSurface().getGraphicsConfiguration(); final AbstractGraphicsDevice device = config.getScreen().getDevice(); final X11GLXContext sharedContext = (X11GLXContext) factory.getOrCreateSharedContext(device); long display = device.getHandle(); final long share; if ( null != shareWith ) { share = shareWith.getHandle(); if (share == 0) { throw new GLException("GLContextShareSet returned an invalid OpenGL context"); } direct = GLX.glXIsDirect(display, share); } else { share = 0; } final GLCapabilitiesImmutable glCaps = (GLCapabilitiesImmutable) config.getChosenCapabilities(); final GLProfile glp = glCaps.getGLProfile(); - if( config.getFBConfigID() < 0 ) { - // not able to use FBConfig + if( !config.hasFBConfig() ) { + // not able to use FBConfig -> GLX 1.1 + forceGLXVersionOneOne(); if(glp.isGL3()) { throw new GLException(getThreadName()+": Unable to create OpenGL >= 3.1 context"); } contextHandle = GLX.glXCreateContext(display, config.getXVisualInfo(), share, direct); if ( 0 == contextHandle ) { throw new GLException(getThreadName()+": Unable to create context(0)"); } if ( !glXMakeContextCurrent(display, drawable.getHandle(), drawableRead.getHandle(), contextHandle) ) { throw new GLException(getThreadName()+": Error making temp context(0) current: display "+toHexString(display)+", context "+toHexString(contextHandle)+", drawable "+drawable); } setGLFunctionAvailability(true, 0, 0, CTX_PROFILE_COMPAT, false); // use GL_VERSION isDirect = GLX.glXIsDirect(display, contextHandle); if (DEBUG) { System.err.println(getThreadName() + ": createContextImpl: OK (old-1) share "+share+", direct "+isDirect+"/"+direct); } return true; } boolean createContextARBTried = false; // utilize the shared context's GLXExt in case it was using the ARB method and it already exists if( null != sharedContext && sharedContext.isCreatedWithARBMethod() ) { contextHandle = createContextARB(share, direct); createContextARBTried = true; if ( DEBUG && 0 != contextHandle ) { System.err.println(getThreadName() + ": createContextImpl: OK (ARB, using sharedContext) share "+share); } } final long temp_ctx; if( 0 == contextHandle ) { // To use GLX_ARB_create_context, we have to make a temp context current, // so we are able to use GetProcAddress temp_ctx = GLX.glXCreateNewContext(display, config.getFBConfig(), GLX.GLX_RGBA_TYPE, share, direct); if ( 0 == temp_ctx ) { throw new GLException(getThreadName()+": Unable to create temp OpenGL context(1)"); } if ( !glXMakeContextCurrent(display, drawable.getHandle(), drawableRead.getHandle(), temp_ctx) ) { throw new GLException(getThreadName()+": Error making temp context(1) current: display "+toHexString(display)+", context "+toHexString(temp_ctx)+", drawable "+drawable); } setGLFunctionAvailability(true, 0, 0, CTX_PROFILE_COMPAT, false); // use GL_VERSION glXMakeContextCurrent(display, 0, 0, 0); // release temp context if( !createContextARBTried ) { // is*Available calls are valid since setGLFunctionAvailability(..) was called final boolean isProcCreateContextAttribsARBAvailable = isFunctionAvailable("glXCreateContextAttribsARB"); final boolean isExtARBCreateContextAvailable = isExtensionAvailable("GLX_ARB_create_context"); if ( isProcCreateContextAttribsARBAvailable && isExtARBCreateContextAvailable ) { // initial ARB context creation contextHandle = createContextARB(share, direct); createContextARBTried=true; if (DEBUG) { if( 0 != contextHandle ) { System.err.println(getThreadName() + ": createContextImpl: OK (ARB, initial) share "+share); } else { System.err.println(getThreadName() + ": createContextImpl: NOT OK (ARB, initial) - creation failed - share "+share); } } } else if (DEBUG) { System.err.println(getThreadName() + ": createContextImpl: NOT OK (ARB, initial) - extension not available - share "+share+ ", isProcCreateContextAttribsARBAvailable "+isProcCreateContextAttribsARBAvailable+", isExtGLXARBCreateContextAvailable "+isExtARBCreateContextAvailable); } } } else { temp_ctx = 0; } if( 0 != contextHandle ) { if( 0 != temp_ctx ) { glXMakeContextCurrent(display, 0, 0, 0); GLX.glXDestroyContext(display, temp_ctx); if ( !glXMakeContextCurrent(display, drawable.getHandle(), drawableRead.getHandle(), contextHandle) ) { throw new GLException(getThreadName()+": Cannot make previous verified context current"); } } } else { if( glp.isGL3() ) { glXMakeContextCurrent(display, 0, 0, 0); GLX.glXDestroyContext(display, temp_ctx); throw new GLException(getThreadName()+": X11GLXContext.createContextImpl ctx !ARB, profile > GL2 requested (OpenGL >= 3.0.1). Requested: "+glp+", current: "+getGLVersion()); } if(DEBUG) { System.err.println(getThreadName()+": X11GLXContext.createContextImpl failed, fall back to !ARB context "+getGLVersion()); } // continue with temp context for GL <= 3.0 contextHandle = temp_ctx; if ( !glXMakeContextCurrent(display, drawable.getHandle(), drawableRead.getHandle(), contextHandle) ) { glXMakeContextCurrent(display, 0, 0, 0); GLX.glXDestroyContext(display, temp_ctx); throw new GLException(getThreadName()+": Error making context(1) current: display "+toHexString(display)+", context "+toHexString(contextHandle)+", drawable "+drawable); } if (DEBUG) { System.err.println(getThreadName() + ": createContextImpl: OK (old-2) share "+share); } } isDirect = GLX.glXIsDirect(display, contextHandle); if (DEBUG) { System.err.println(getThreadName() + ": createContextImpl: OK direct "+isDirect+"/"+direct); } return true; } @Override protected void makeCurrentImpl() throws GLException { long dpy = drawable.getNativeSurface().getDisplayHandle(); if (GLX.glXGetCurrentContext() != contextHandle) { if (!glXMakeContextCurrent(dpy, drawable.getHandle(), drawableRead.getHandle(), contextHandle)) { throw new GLException("Error making context " + toHexString(contextHandle) + " current on Thread " + getThreadName() + " with display " + toHexString(dpy) + ", drawableWrite " + toHexString(drawable.getHandle()) + ", drawableRead "+ toHexString(drawableRead.getHandle()) + " - " + this); } } } @Override protected void releaseImpl() throws GLException { long display = drawable.getNativeSurface().getDisplayHandle(); if (!glXMakeContextCurrent(display, 0, 0, 0)) { throw new GLException(getThreadName()+": Error freeing OpenGL context"); } } @Override protected void destroyImpl() throws GLException { destroyContextARBImpl(contextHandle); } @Override protected void copyImpl(GLContext source, int mask) throws GLException { long dst = getHandle(); long src = source.getHandle(); long display = drawable.getNativeSurface().getDisplayHandle(); if (0 == display) { throw new GLException(getThreadName()+": Connection to X display not yet set up"); } GLX.glXCopyContext(display, src, dst, mask); // Should check for X errors and raise GLException } @Override protected final void updateGLXProcAddressTable() { final AbstractGraphicsConfiguration aconfig = drawable.getNativeSurface().getGraphicsConfiguration(); final AbstractGraphicsDevice adevice = aconfig.getScreen().getDevice(); final String key = "GLX-"+adevice.getUniqueID(); if (DEBUG) { System.err.println(getThreadName() + ": Initializing GLX extension address table: "+key); } ProcAddressTable table = null; synchronized(mappedContextTypeObjectLock) { table = mappedGLXProcAddress.get( key ); } if(null != table) { glXExtProcAddressTable = (GLXExtProcAddressTable) table; if(DEBUG) { System.err.println(getThreadName() + ": GLContext GLX ProcAddressTable reusing key("+key+") -> "+toHexString(table.hashCode())); } } else { glXExtProcAddressTable = new GLXExtProcAddressTable(new GLProcAddressResolver()); resetProcAddressTable(getGLXExtProcAddressTable()); synchronized(mappedContextTypeObjectLock) { mappedGLXProcAddress.put(key, getGLXExtProcAddressTable()); if(DEBUG) { System.err.println(getThreadName() + ": GLContext GLX ProcAddressTable mapping key("+key+") -> "+toHexString(getGLXExtProcAddressTable().hashCode())); } } } } @Override protected final StringBuilder getPlatformExtensionsStringImpl() { final NativeSurface ns = drawable.getNativeSurface(); final X11GraphicsDevice x11Device = (X11GraphicsDevice) ns.getGraphicsConfiguration().getScreen().getDevice(); StringBuilder sb = new StringBuilder(); x11Device.lock(); try{ if (DEBUG) { System.err.println("GLX Version client version "+ GLXUtil.getClientVersionNumber()+ ", server: "+ GLXUtil.getGLXServerVersionNumber(x11Device)); } if(((X11GLXDrawableFactory)drawable.getFactoryImpl()).isGLXVersionGreaterEqualOneOne(x11Device)) { { final String ret = GLX.glXGetClientString(x11Device.getHandle(), GLX.GLX_EXTENSIONS); if (DEBUG) { System.err.println("GLX extensions (glXGetClientString): " + ret); } sb.append(ret).append(" "); } { final String ret = GLX.glXQueryExtensionsString(x11Device.getHandle(), ns.getScreenIndex()); if (DEBUG) { System.err.println("GLX extensions (glXQueryExtensionsString): " + ret); } sb.append(ret).append(" "); } { final String ret = GLX.glXQueryServerString(x11Device.getHandle(), ns.getScreenIndex(), GLX.GLX_EXTENSIONS); if (DEBUG) { System.err.println("GLX extensions (glXQueryServerString): " + ret); } sb.append(ret).append(" "); } } } finally { x11Device.unlock(); } return sb; } @Override public boolean isExtensionAvailable(String glExtensionName) { if (glExtensionName.equals(GLExtensions.ARB_pbuffer) || glExtensionName.equals(GLExtensions.ARB_pixel_format)) { return getGLDrawable().getFactory().canCreateGLPbuffer( drawable.getNativeSurface().getGraphicsConfiguration().getScreen().getDevice() ); } return super.isExtensionAvailable(glExtensionName); } @Override protected boolean setSwapIntervalImpl(int interval) { if( !drawable.getChosenGLCapabilities().isOnscreen() ) { return false; } final GLXExt glXExt = getGLXExt(); if(0==hasSwapInterval) { try { /** Same impl. .. if( glXExt.isExtensionAvailable(GLXExtensions.GLX_MESA_swap_control) ) { if(DEBUG) { System.err.println("X11GLXContext.setSwapInterval using: "+GLXExtensions.GLX_MESA_swap_control); } hasSwapInterval = 1; } else */ if ( glXExt.isExtensionAvailable(GLXExtensions.GLX_SGI_swap_control) ) { if(DEBUG) { System.err.println("X11GLXContext.setSwapInterval using: "+GLXExtensions.GLX_SGI_swap_control); } hasSwapInterval = 2; } else { hasSwapInterval = -1; } } catch (Throwable t) { hasSwapInterval=-1; } } /* try { switch( hasSwapInterval ) { case 1: return 0 == glXExt.glXSwapIntervalMESA(interval); case 2: return 0 == glXExt.glXSwapIntervalSGI(interval); } } catch (Throwable t) { hasSwapInterval = -1; } */ if (2 == hasSwapInterval) { try { return 0 == glXExt.glXSwapIntervalSGI(interval); } catch (Throwable t) { hasSwapInterval=-1; } } return false; } private final int initSwapGroupImpl(GLXExt glXExt) { if(0==hasSwapGroupNV) { try { hasSwapGroupNV = glXExt.isExtensionAvailable(GLXExtensions.GLX_NV_swap_group)?1:-1; } catch (Throwable t) { hasSwapGroupNV=1; } if(DEBUG) { System.err.println("initSwapGroupImpl: "+GLXExtensions.GLX_NV_swap_group+": "+hasSwapGroupNV); } } return hasSwapGroupNV; } @Override protected final boolean queryMaxSwapGroupsImpl(int[] maxGroups, int maxGroups_offset, int[] maxBarriers, int maxBarriers_offset) { boolean res = false; GLXExt glXExt = getGLXExt(); if (initSwapGroupImpl(glXExt)>0) { final NativeSurface ns = drawable.getNativeSurface(); try { final IntBuffer maxGroupsNIO = Buffers.newDirectIntBuffer(maxGroups.length - maxGroups_offset); final IntBuffer maxBarriersNIO = Buffers.newDirectIntBuffer(maxBarriers.length - maxBarriers_offset); if( glXExt.glXQueryMaxSwapGroupsNV(ns.getDisplayHandle(), ns.getScreenIndex(), maxGroupsNIO, maxBarriersNIO) ) { maxGroupsNIO.get(maxGroups, maxGroups_offset, maxGroupsNIO.remaining()); maxBarriersNIO.get(maxGroups, maxGroups_offset, maxBarriersNIO.remaining()); res = true; } } catch (Throwable t) { hasSwapGroupNV=-1; } } return res; } @Override protected final boolean joinSwapGroupImpl(int group) { boolean res = false; GLXExt glXExt = getGLXExt(); if (initSwapGroupImpl(glXExt)>0) { try { if( glXExt.glXJoinSwapGroupNV(drawable.getNativeSurface().getDisplayHandle(), drawable.getHandle(), group) ) { currentSwapGroup = group; res = true; } } catch (Throwable t) { hasSwapGroupNV=-1; } } return res; } @Override protected final boolean bindSwapBarrierImpl(int group, int barrier) { boolean res = false; GLXExt glXExt = getGLXExt(); if (initSwapGroupImpl(glXExt)>0) { try { if( glXExt.glXBindSwapBarrierNV(drawable.getNativeSurface().getDisplayHandle(), group, barrier) ) { res = true; } } catch (Throwable t) { hasSwapGroupNV=-1; } } return res; } @Override public ByteBuffer glAllocateMemoryNV(int arg0, float arg1, float arg2, float arg3) { return getGLXExt().glXAllocateMemoryNV(arg0, arg1, arg2, arg3); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); super.append(sb); sb.append(", direct "); sb.append(isDirect); sb.append("] "); return sb.toString(); } //---------------------------------------------------------------------- // Internals only below this point // } diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawableFactory.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawableFactory.java index e44be7509..394293bc0 100644 --- a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawableFactory.java +++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawableFactory.java @@ -1,664 +1,670 @@ /* * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved. * Copyright (c) 2010 JogAmp Community. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * - Redistribution of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistribution 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 Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN * MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL NOT BE LIABLE FOR * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR * ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR * DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use * in the design, construction, operation or maintenance of any nuclear * facility. */ package jogamp.opengl.x11.glx; import java.nio.Buffer; import java.nio.ShortBuffer; import java.util.Collection; import java.util.HashMap; import java.util.List; import javax.media.nativewindow.AbstractGraphicsConfiguration; import javax.media.nativewindow.AbstractGraphicsDevice; import javax.media.nativewindow.AbstractGraphicsScreen; import javax.media.nativewindow.NativeSurface; import javax.media.nativewindow.ProxySurface; import javax.media.nativewindow.UpstreamSurfaceHook; import javax.media.nativewindow.VisualIDHolder; import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLCapabilitiesChooser; import javax.media.opengl.GLCapabilitiesImmutable; import javax.media.opengl.GLContext; import javax.media.opengl.GLDrawable; import javax.media.opengl.GLException; import javax.media.opengl.GLProfile; import jogamp.nativewindow.WrappedSurface; import jogamp.nativewindow.x11.X11DummyUpstreamSurfaceHook; import jogamp.nativewindow.x11.X11Lib; import jogamp.nativewindow.x11.X11Util; import jogamp.opengl.DesktopGLDynamicLookupHelper; import jogamp.opengl.GLContextImpl; import jogamp.opengl.GLDrawableFactoryImpl; import jogamp.opengl.GLDrawableImpl; import jogamp.opengl.GLDynamicLookupHelper; import jogamp.opengl.GLGraphicsConfigurationUtil; import jogamp.opengl.SharedResourceRunner; import com.jogamp.common.util.VersionNumber; import com.jogamp.nativewindow.x11.X11GraphicsDevice; import com.jogamp.nativewindow.x11.X11GraphicsScreen; import com.jogamp.opengl.GLRendererQuirks; public class X11GLXDrawableFactory extends GLDrawableFactoryImpl { public static final VersionNumber versionOneZero = new VersionNumber(1, 0, 0); public static final VersionNumber versionOneOne = new VersionNumber(1, 1, 0); public static final VersionNumber versionOneTwo = new VersionNumber(1, 2, 0); public static final VersionNumber versionOneThree = new VersionNumber(1, 3, 0); public static final VersionNumber versionOneFour = new VersionNumber(1, 4, 0); static final String GLX_SGIX_pbuffer = "GLX_SGIX_pbuffer"; private static DesktopGLDynamicLookupHelper x11GLXDynamicLookupHelper = null; public X11GLXDrawableFactory() { super(); synchronized(X11GLXDrawableFactory.class) { if(null==x11GLXDynamicLookupHelper) { DesktopGLDynamicLookupHelper tmp = null; try { tmp = new DesktopGLDynamicLookupHelper(new X11GLXDynamicLibraryBundleInfo()); } catch (GLException gle) { if(DEBUG) { gle.printStackTrace(); } } if(null!=tmp && tmp.isLibComplete()) { x11GLXDynamicLookupHelper = tmp; GLX.getGLXProcAddressTable().reset(x11GLXDynamicLookupHelper); } } } defaultDevice = new X11GraphicsDevice(X11Util.getNullDisplayName(), AbstractGraphicsDevice.DEFAULT_UNIT); if(null!=x11GLXDynamicLookupHelper) { // Register our GraphicsConfigurationFactory implementations // The act of constructing them causes them to be registered X11GLXGraphicsConfigurationFactory.registerFactory(); sharedMap = new HashMap<String, SharedResourceRunner.Resource>(); // Init shared resources off thread // Will be released via ShutdownHook sharedResourceRunner = new SharedResourceRunner(new SharedResourceImplementation()); sharedResourceRunner.start(); } } @Override protected final boolean isComplete() { return null != x11GLXDynamicLookupHelper; } @Override protected final void destroy() { if(null != sharedResourceRunner) { sharedResourceRunner.stop(); sharedResourceRunner = null; } if(null != sharedMap) { sharedMap.clear(); sharedMap = null; } defaultDevice = null; /** * Pulling away the native library may cause havoc .. * x11GLXDynamicLookupHelper.destroy(); */ x11GLXDynamicLookupHelper = null; } @Override public final GLDynamicLookupHelper getGLDynamicLookupHelper(int profile) { return x11GLXDynamicLookupHelper; } private X11GraphicsDevice defaultDevice; private SharedResourceRunner sharedResourceRunner; private HashMap<String /* connection */, SharedResourceRunner.Resource> sharedMap; static class SharedResource implements SharedResourceRunner.Resource { private final String glXServerVendorName; private final boolean isGLXServerVendorATI; private final boolean isGLXServerVendorNVIDIA; private final VersionNumber glXServerVersion; private final boolean glXServerVersionOneOneCapable; private final boolean glXServerVersionOneThreeCapable; private final boolean glXMultisampleAvailable; X11GraphicsDevice device; X11GraphicsScreen screen; GLDrawableImpl drawable; GLContextImpl context; SharedResource(X11GraphicsDevice dev, X11GraphicsScreen scrn, GLDrawableImpl draw, GLContextImpl ctx, VersionNumber glXServerVer, String glXServerVendor, boolean glXServerMultisampleAvail) { device = dev; screen = scrn; drawable = draw; context = ctx; glXServerVersion = glXServerVer; glXServerVersionOneOneCapable = glXServerVersion.compareTo(versionOneOne) >= 0 ; glXServerVersionOneThreeCapable = glXServerVersion.compareTo(versionOneThree) >= 0 ; glXServerVendorName = glXServerVendor; isGLXServerVendorATI = GLXUtil.isVendorATI(glXServerVendorName); isGLXServerVendorNVIDIA = GLXUtil.isVendorNVIDIA(glXServerVendorName); glXMultisampleAvailable = glXServerMultisampleAvail; } @Override public final boolean isValid() { return null != context; } @Override final public AbstractGraphicsDevice getDevice() { return device; } @Override final public AbstractGraphicsScreen getScreen() { return screen; } @Override final public GLDrawableImpl getDrawable() { return drawable; } @Override final public GLContextImpl getContext() { return context; } @Override public GLRendererQuirks getRendererQuirks() { return null != context ? context.getRendererQuirks() : null; } final String getGLXVendorName() { return glXServerVendorName; } final boolean isGLXVendorATI() { return isGLXServerVendorATI; } final boolean isGLXVendorNVIDIA() { return isGLXServerVendorNVIDIA; } final VersionNumber getGLXVersion() { return glXServerVersion; } final boolean isGLXVersionGreaterEqualOneOne() { return glXServerVersionOneOneCapable; } final boolean isGLXVersionGreaterEqualOneThree() { return glXServerVersionOneThreeCapable; } final boolean isGLXMultisampleAvailable() { return glXMultisampleAvailable; } } class SharedResourceImplementation implements SharedResourceRunner.Implementation { @Override public void clear() { synchronized(sharedMap) { sharedMap.clear(); } } @Override public SharedResourceRunner.Resource mapPut(String connection, SharedResourceRunner.Resource resource) { synchronized(sharedMap) { return sharedMap.put(connection, resource); } } @Override public SharedResourceRunner.Resource mapGet(String connection) { synchronized(sharedMap) { return sharedMap.get(connection); } } @Override public Collection<SharedResourceRunner.Resource> mapValues() { synchronized(sharedMap) { return sharedMap.values(); } } @Override public boolean isDeviceSupported(String connection) { final boolean res; final X11GraphicsDevice x11Device = new X11GraphicsDevice(X11Util.openDisplay(connection), AbstractGraphicsDevice.DEFAULT_UNIT, true /* owner */); x11Device.lock(); try { res = GLXUtil.isGLXAvailableOnServer(x11Device); } finally { x11Device.unlock(); x11Device.close(); } if(DEBUG) { System.err.println("GLX "+(res ? "is" : "not")+" available on device/server: "+x11Device); } return res; } @Override public SharedResourceRunner.Resource createSharedResource(String connection) { final X11GraphicsDevice sharedDevice = new X11GraphicsDevice(X11Util.openDisplay(connection), AbstractGraphicsDevice.DEFAULT_UNIT, true /* owner */); sharedDevice.lock(); try { final X11GraphicsScreen sharedScreen = new X11GraphicsScreen(sharedDevice, sharedDevice.getDefaultScreen()); GLXUtil.initGLXClientDataSingleton(sharedDevice); final String glXServerVendorName = GLX.glXQueryServerString(sharedDevice.getHandle(), 0, GLX.GLX_VENDOR); - final VersionNumber glXServerVersion = GLXUtil.getGLXServerVersionNumber(sharedDevice); final boolean glXServerMultisampleAvailable = GLXUtil.isMultisampleAvailable(GLX.glXQueryServerString(sharedDevice.getHandle(), 0, GLX.GLX_EXTENSIONS)); final GLProfile glp = GLProfile.get(sharedDevice, GLProfile.GL_PROFILE_LIST_MIN_DESKTOP, false); if (null == glp) { throw new GLException("Couldn't get default GLProfile for device: "+sharedDevice); } final GLCapabilitiesImmutable caps = new GLCapabilities(glp); final GLDrawableImpl sharedDrawable = createOnscreenDrawableImpl(createDummySurfaceImpl(sharedDevice, false, caps, caps, null, 64, 64)); sharedDrawable.setRealized(true); - + final X11GLCapabilities chosenCaps = (X11GLCapabilities) sharedDrawable.getChosenGLCapabilities(); + final boolean glxForcedOneOne = !chosenCaps.hasFBConfig(); + final VersionNumber glXServerVersion; + if( glxForcedOneOne ) { + glXServerVersion = versionOneOne; + } else { + glXServerVersion = GLXUtil.getGLXServerVersionNumber(sharedDevice); + } final GLContextImpl sharedContext = (GLContextImpl) sharedDrawable.createContext(null); if (null == sharedContext) { throw new GLException("Couldn't create shared context for drawable: "+sharedDrawable); } boolean madeCurrent = false; sharedContext.makeCurrent(); try { madeCurrent = sharedContext.isCurrent(); } finally { sharedContext.release(); } if( sharedContext.hasRendererQuirk( GLRendererQuirks.DontCloseX11Display ) ) { X11Util.markAllDisplaysUnclosable(); } if (DEBUG) { System.err.println("SharedDevice: " + sharedDevice); System.err.println("SharedScreen: " + sharedScreen); System.err.println("SharedContext: " + sharedContext + ", madeCurrent " + madeCurrent); System.err.println("GLX Server Vendor: " + glXServerVendorName); - System.err.println("GLX Server Version: " + glXServerVersion); + System.err.println("GLX Server Version: " + glXServerVersion + ", forced "+glxForcedOneOne); System.err.println("GLX Server Multisample: " + glXServerMultisampleAvailable); System.err.println("GLX Client Vendor: " + GLXUtil.getClientVendorName()); System.err.println("GLX Client Version: " + GLXUtil.getClientVersionNumber()); System.err.println("GLX Client Multisample: " + GLXUtil.isClientMultisampleAvailable()); } return new SharedResource(sharedDevice, sharedScreen, sharedDrawable, sharedContext, glXServerVersion, glXServerVendorName, glXServerMultisampleAvailable && GLXUtil.isClientMultisampleAvailable()); } catch (Throwable t) { throw new GLException("X11GLXDrawableFactory - Could not initialize shared resources for "+connection, t); } finally { sharedDevice.unlock(); } } @Override public void releaseSharedResource(SharedResourceRunner.Resource shared) { SharedResource sr = (SharedResource) shared; if (DEBUG) { System.err.println("Shutdown Shared:"); System.err.println("Device : " + sr.device); System.err.println("Screen : " + sr.screen); System.err.println("Drawable: " + sr.drawable); System.err.println("CTX : " + sr.context); Thread.dumpStack(); } if (null != sr.context) { // may cause JVM SIGSEGV: sr.context.destroy(); // will also pull the dummy MutuableSurface sr.context = null; } if (null != sr.drawable) { // may cause JVM SIGSEGV: sr.drawable.setRealized(false); sr.drawable = null; } if (null != sr.screen) { sr.screen = null; } if (null != sr.device) { // may cause JVM SIGSEGV: sr.device.close(); sr.device = null; } } } @Override public final AbstractGraphicsDevice getDefaultDevice() { return defaultDevice; } @Override public final boolean getIsDeviceCompatible(AbstractGraphicsDevice device) { if(null != x11GLXDynamicLookupHelper && device instanceof X11GraphicsDevice) { return true; } return false; } @Override protected final Thread getSharedResourceThread() { return sharedResourceRunner.start(); } @Override protected final SharedResource getOrCreateSharedResourceImpl(AbstractGraphicsDevice device) { return (SharedResource) sharedResourceRunner.getOrCreateShared(device); } protected final long getOrCreateSharedDpy(AbstractGraphicsDevice device) { final SharedResourceRunner.Resource sr = getOrCreateSharedResource( device ); if(null!=sr) { return sr.getDevice().getHandle(); } return 0; } @Override protected List<GLCapabilitiesImmutable> getAvailableCapabilitiesImpl(AbstractGraphicsDevice device) { return X11GLXGraphicsConfigurationFactory.getAvailableCapabilities(this, device); } @Override protected final GLDrawableImpl createOnscreenDrawableImpl(NativeSurface target) { if (target == null) { throw new IllegalArgumentException("Null target"); } return new X11OnscreenGLXDrawable(this, target, false); } @Override protected final GLDrawableImpl createOffscreenDrawableImpl(NativeSurface target) { if (target == null) { throw new IllegalArgumentException("Null target"); } AbstractGraphicsConfiguration config = target.getGraphicsConfiguration(); GLCapabilitiesImmutable caps = (GLCapabilitiesImmutable) config.getChosenCapabilities(); if(!caps.isPBuffer()) { return new X11PixmapGLXDrawable(this, target); } // PBuffer GLDrawable Creation GLDrawableImpl pbufferDrawable; AbstractGraphicsDevice device = config.getScreen().getDevice(); /** * Due to the ATI Bug https://bugzilla.mozilla.org/show_bug.cgi?id=486277, * we need to have a context current on the same Display to create a PBuffer. * The dummy context shall also use the same Display, * since switching Display in this regard is another ATI bug. */ SharedResource sr = (SharedResource) sharedResourceRunner.getOrCreateShared(device); if( null!=sr && sr.isGLXVendorATI() && null == GLContext.getCurrent() ) { sr.getContext().makeCurrent(); try { pbufferDrawable = new X11PbufferGLXDrawable(this, target); } finally { sr.getContext().release(); } } else { pbufferDrawable = new X11PbufferGLXDrawable(this, target); } return pbufferDrawable; } public final boolean isGLXMultisampleAvailable(AbstractGraphicsDevice device) { if(null != device) { SharedResource sr = (SharedResource) sharedResourceRunner.getOrCreateShared(device); if(null!=sr) { return sr.isGLXMultisampleAvailable(); } } return false; } public final VersionNumber getGLXVersionNumber(AbstractGraphicsDevice device) { if(null != device) { SharedResource sr = (SharedResource) sharedResourceRunner.getOrCreateShared(device); if(null!=sr) { return sr.getGLXVersion(); } if( device instanceof X11GraphicsDevice ) { return GLXUtil.getGLXServerVersionNumber((X11GraphicsDevice)device); } } return null; } public final boolean isGLXVersionGreaterEqualOneOne(AbstractGraphicsDevice device) { if(null != device) { SharedResource sr = (SharedResource) sharedResourceRunner.getOrCreateShared(device); if(null!=sr) { return sr.isGLXVersionGreaterEqualOneOne(); } if( device instanceof X11GraphicsDevice ) { final VersionNumber glXServerVersion = GLXUtil.getGLXServerVersionNumber((X11GraphicsDevice)device); return glXServerVersion.compareTo(versionOneOne) >= 0; } } return false; } public final boolean isGLXVersionGreaterEqualOneThree(AbstractGraphicsDevice device) { if(null != device) { SharedResource sr = (SharedResource) sharedResourceRunner.getOrCreateShared(device); if(null!=sr) { return sr.isGLXVersionGreaterEqualOneThree(); } if( device instanceof X11GraphicsDevice ) { final VersionNumber glXServerVersion = GLXUtil.getGLXServerVersionNumber((X11GraphicsDevice)device); return glXServerVersion.compareTo(versionOneThree) >= 0; } } return false; } @Override public final boolean canCreateGLPbuffer(AbstractGraphicsDevice device) { if(null == device) { SharedResourceRunner.Resource sr = sharedResourceRunner.getOrCreateShared(defaultDevice); if(null!=sr) { device = sr.getDevice(); } } return isGLXVersionGreaterEqualOneThree(device); } @Override protected final ProxySurface createMutableSurfaceImpl(AbstractGraphicsDevice deviceReq, boolean createNewDevice, GLCapabilitiesImmutable capsChosen, GLCapabilitiesImmutable capsRequested, GLCapabilitiesChooser chooser, UpstreamSurfaceHook upstreamHook) { final X11GraphicsDevice device; if( createNewDevice || !(deviceReq instanceof X11GraphicsDevice) ) { device = new X11GraphicsDevice(X11Util.openDisplay(deviceReq.getConnection()), deviceReq.getUnitID(), true /* owner */); } else { device = (X11GraphicsDevice) deviceReq; } final X11GraphicsScreen screen = new X11GraphicsScreen(device, device.getDefaultScreen()); final X11GLXGraphicsConfiguration config = X11GLXGraphicsConfigurationFactory.chooseGraphicsConfigurationStatic(capsChosen, capsRequested, chooser, screen, VisualIDHolder.VID_UNDEFINED); if(null == config) { throw new GLException("Choosing GraphicsConfiguration failed w/ "+capsChosen+" on "+screen); } return new WrappedSurface(config, 0, upstreamHook, createNewDevice); } @Override public final ProxySurface createDummySurfaceImpl(AbstractGraphicsDevice deviceReq, boolean createNewDevice, GLCapabilitiesImmutable chosenCaps, GLCapabilitiesImmutable requestedCaps, GLCapabilitiesChooser chooser, int width, int height) { chosenCaps = GLGraphicsConfigurationUtil.fixOnscreenGLCapabilities(chosenCaps); return createMutableSurfaceImpl(deviceReq, createNewDevice, chosenCaps, requestedCaps, chooser, new X11DummyUpstreamSurfaceHook(width, height)); } @Override protected final ProxySurface createProxySurfaceImpl(AbstractGraphicsDevice deviceReq, int screenIdx, long windowHandle, GLCapabilitiesImmutable capsRequested, GLCapabilitiesChooser chooser, UpstreamSurfaceHook upstream) { final X11GraphicsDevice device = new X11GraphicsDevice(X11Util.openDisplay(deviceReq.getConnection()), deviceReq.getUnitID(), true /* owner */); final X11GraphicsScreen screen = new X11GraphicsScreen(device, screenIdx); final int xvisualID = X11Lib.GetVisualIDFromWindow(device.getHandle(), windowHandle); if(VisualIDHolder.VID_UNDEFINED == xvisualID) { throw new GLException("Undefined VisualID of window 0x"+Long.toHexString(windowHandle)+", window probably invalid"); } if(DEBUG) { System.err.println("X11GLXDrawableFactory.createProxySurfaceImpl 0x"+Long.toHexString(windowHandle)+": visualID 0x"+Integer.toHexString(xvisualID)); } final X11GLXGraphicsConfiguration cfg = X11GLXGraphicsConfigurationFactory.chooseGraphicsConfigurationStatic(capsRequested, capsRequested, chooser, screen, xvisualID); if(DEBUG) { System.err.println("X11GLXDrawableFactory.createProxySurfaceImpl 0x"+Long.toHexString(windowHandle)+": "+cfg); } return new WrappedSurface(cfg, windowHandle, upstream, true); } @Override protected final GLContext createExternalGLContextImpl() { return X11ExternalGLXContext.create(this, null); } @Override public final boolean canCreateExternalGLDrawable(AbstractGraphicsDevice device) { return canCreateGLPbuffer(device); } @Override protected final GLDrawable createExternalGLDrawableImpl() { return X11ExternalGLXDrawable.create(this, null); } //---------------------------------------------------------------------- // Gamma-related functionality // private boolean gotGammaRampLength; private int gammaRampLength; @Override protected final synchronized int getGammaRampLength() { if (gotGammaRampLength) { return gammaRampLength; } long display = getOrCreateSharedDpy(defaultDevice); if(0 == display) { return 0; } int[] size = new int[1]; boolean res = X11Lib.XF86VidModeGetGammaRampSize(display, X11Lib.DefaultScreen(display), size, 0); if (!res) { return 0; } gotGammaRampLength = true; gammaRampLength = size[0]; return gammaRampLength; } @Override protected final boolean setGammaRamp(float[] ramp) { long display = getOrCreateSharedDpy(defaultDevice); if(0 == display) { return false; } int len = ramp.length; short[] rampData = new short[len]; for (int i = 0; i < len; i++) { rampData[i] = (short) (ramp[i] * 65535); } boolean res = X11Lib.XF86VidModeSetGammaRamp(display, X11Lib.DefaultScreen(display), rampData.length, rampData, 0, rampData, 0, rampData, 0); return res; } @Override protected final Buffer getGammaRamp() { long display = getOrCreateSharedDpy(defaultDevice); if(0 == display) { return null; } int size = getGammaRampLength(); ShortBuffer rampData = ShortBuffer.wrap(new short[3 * size]); rampData.position(0); rampData.limit(size); ShortBuffer redRampData = rampData.slice(); rampData.position(size); rampData.limit(2 * size); ShortBuffer greenRampData = rampData.slice(); rampData.position(2 * size); rampData.limit(3 * size); ShortBuffer blueRampData = rampData.slice(); boolean res = X11Lib.XF86VidModeGetGammaRamp(display, X11Lib.DefaultScreen(display), size, redRampData, greenRampData, blueRampData); if (!res) { return null; } return rampData; } @Override protected final void resetGammaRamp(Buffer originalGammaRamp) { if (originalGammaRamp == null) { return; // getGammaRamp failed originally } long display = getOrCreateSharedDpy(defaultDevice); if(0 == display) { return; } ShortBuffer rampData = (ShortBuffer) originalGammaRamp; int capacity = rampData.capacity(); if ((capacity % 3) != 0) { throw new IllegalArgumentException("Must not be the original gamma ramp"); } int size = capacity / 3; rampData.position(0); rampData.limit(size); ShortBuffer redRampData = rampData.slice(); rampData.position(size); rampData.limit(2 * size); ShortBuffer greenRampData = rampData.slice(); rampData.position(2 * size); rampData.limit(3 * size); ShortBuffer blueRampData = rampData.slice(); X11Lib.XF86VidModeSetGammaRamp(display, X11Lib.DefaultScreen(display), size, redRampData, greenRampData, blueRampData); } } diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfiguration.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfiguration.java index 523364389..c23bd5337 100644 --- a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfiguration.java +++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfiguration.java @@ -1,485 +1,488 @@ /* * Copyright (c) 2008 Sun Microsystems, Inc. All Rights Reserved. * Copyright (c) 2010 JogAmp Community. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * - Redistribution of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistribution 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 Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN * MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL NOT BE LIABLE FOR * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR * ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR * DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. */ package jogamp.opengl.x11.glx; import java.nio.IntBuffer; import javax.media.nativewindow.CapabilitiesImmutable; import javax.media.nativewindow.GraphicsConfigurationFactory; import javax.media.nativewindow.VisualIDHolder; import javax.media.opengl.DefaultGLCapabilitiesChooser; import javax.media.opengl.GL; import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLCapabilitiesChooser; import javax.media.opengl.GLCapabilitiesImmutable; import javax.media.opengl.GLDrawableFactory; import javax.media.opengl.GLException; import javax.media.opengl.GLProfile; import jogamp.nativewindow.x11.X11Lib; import jogamp.nativewindow.x11.XRenderDirectFormat; import jogamp.nativewindow.x11.XRenderPictFormat; import jogamp.nativewindow.x11.XVisualInfo; import jogamp.opengl.GLGraphicsConfigurationUtil; import com.jogamp.common.nio.Buffers; import com.jogamp.common.nio.PointerBuffer; import com.jogamp.nativewindow.x11.X11GraphicsConfiguration; import com.jogamp.nativewindow.x11.X11GraphicsDevice; import com.jogamp.nativewindow.x11.X11GraphicsScreen; public class X11GLXGraphicsConfiguration extends X11GraphicsConfiguration implements Cloneable { public static final int MAX_ATTRIBS = 128; private GLCapabilitiesChooser chooser; X11GLXGraphicsConfiguration(X11GraphicsScreen screen, X11GLCapabilities capsChosen, GLCapabilitiesImmutable capsRequested, GLCapabilitiesChooser chooser) { super(screen, capsChosen, capsRequested, capsChosen.getXVisualInfo()); this.chooser=chooser; } public Object clone() { return super.clone(); } public final long getFBConfig() { return ((X11GLCapabilities)capabilitiesChosen).getFBConfig(); } public final int getFBConfigID() { return ((X11GLCapabilities)capabilitiesChosen).getFBConfigID(); } + public final boolean hasFBConfig() { + return ((X11GLCapabilities)capabilitiesChosen).hasFBConfig(); + } void updateGraphicsConfiguration() { final CapabilitiesImmutable aChosenCaps = getChosenCapabilities(); if( !(aChosenCaps instanceof X11GLCapabilities) || VisualIDHolder.VID_UNDEFINED == aChosenCaps.getVisualID(VIDType.X11_XVISUAL) ) { // This case is actually quite impossible, since on X11 the visualID and hence GraphicsConfiguration // must be determined _before_ window creation! final X11GLXGraphicsConfiguration newConfig = (X11GLXGraphicsConfiguration) GraphicsConfigurationFactory.getFactory(getScreen().getDevice(), aChosenCaps).chooseGraphicsConfiguration( aChosenCaps, getRequestedCapabilities(), chooser, getScreen(), VisualIDHolder.VID_UNDEFINED); if(null!=newConfig) { // FIXME: setScreen( ... ); setXVisualInfo(newConfig.getXVisualInfo()); setChosenCapabilities(newConfig.getChosenCapabilities()); if(DEBUG) { System.err.println("X11GLXGraphicsConfiguration.updateGraphicsConfiguration updated:"+this); } } else { throw new GLException("No native VisualID pre-chosen and update failed: "+this); } } else if (DEBUG) { System.err.println("X11GLXGraphicsConfiguration.updateGraphicsConfiguration kept:"+this); } } static X11GLXGraphicsConfiguration create(GLProfile glp, X11GraphicsScreen x11Screen, int fbcfgID) { final X11GraphicsDevice device = (X11GraphicsDevice) x11Screen.getDevice(); final long display = device.getHandle(); if(0==display) { throw new GLException("Display null of "+x11Screen); } final int screen = x11Screen.getIndex(); final long fbcfg = glXFBConfigID2FBConfig(display, screen, fbcfgID); if(0==fbcfg) { throw new GLException("FBConfig null of "+toHexString(fbcfgID)); } if(null==glp) { glp = GLProfile.getDefault(x11Screen.getDevice()); } final X11GLXDrawableFactory factory = (X11GLXDrawableFactory) GLDrawableFactory.getDesktopFactory(); final X11GLCapabilities caps = GLXFBConfig2GLCapabilities(device, glp, fbcfg, GLGraphicsConfigurationUtil.ALL_BITS, factory.isGLXMultisampleAvailable(device)); if(null==caps) { throw new GLException("GLCapabilities null of "+toHexString(fbcfg)); } return new X11GLXGraphicsConfiguration(x11Screen, caps, caps, new DefaultGLCapabilitiesChooser()); } static IntBuffer GLCapabilities2AttribList(GLCapabilitiesImmutable caps, boolean forFBAttr, boolean isMultisampleAvailable, long display, int screen) { int colorDepth = (caps.getRedBits() + caps.getGreenBits() + caps.getBlueBits()); if (colorDepth < 15) { throw new GLException("Bit depths < 15 (i.e., non-true-color) not supported"); } final IntBuffer res = Buffers.newDirectIntBuffer(MAX_ATTRIBS); int idx = 0; if (forFBAttr) { res.put(idx++, GLX.GLX_DRAWABLE_TYPE); final int surfaceType; if( caps.isOnscreen() ) { surfaceType = GLX.GLX_WINDOW_BIT; } else if( caps.isFBO() ) { surfaceType = GLX.GLX_WINDOW_BIT; // native replacement! } else if( caps.isPBuffer() ) { surfaceType = GLX.GLX_PBUFFER_BIT; } else if( caps.isBitmap() ) { surfaceType = GLX.GLX_PIXMAP_BIT; } else { throw new GLException("no surface type set in caps: "+caps); } res.put(idx++, surfaceType); res.put(idx++, GLX.GLX_RENDER_TYPE); res.put(idx++, GLX.GLX_RGBA_BIT); } else { res.put(idx++, GLX.GLX_RGBA); } // FIXME: Still a bug is Mesa: PBUFFER && GLX_STEREO==GL_FALSE ? if (forFBAttr) { res.put(idx++, GLX.GLX_DOUBLEBUFFER); res.put(idx++, caps.getDoubleBuffered()?GL.GL_TRUE:GL.GL_FALSE); res.put(idx++, GLX.GLX_STEREO); res.put(idx++, caps.getStereo()?GL.GL_TRUE:GL.GL_FALSE); res.put(idx++, GLX.GLX_TRANSPARENT_TYPE); res.put(idx++, GLX.GLX_NONE); /** res.put(idx++, caps.isBackgroundOpaque()?GLX.GLX_NONE:GLX.GLX_TRANSPARENT_RGB; if(!caps.isBackgroundOpaque()) { res.put(idx++, GLX.GLX_TRANSPARENT_RED_VALUE); res.put(idx++, caps.getTransparentRedValue()>=0?caps.getTransparentRedValue():(int)GLX.GLX_DONT_CARE); res.put(idx++, GLX.GLX_TRANSPARENT_GREEN_VALUE); res.put(idx++, caps.getTransparentGreenValue()>=0?caps.getTransparentGreenValue():(int)GLX.GLX_DONT_CARE); res.put(idx++, GLX.GLX_TRANSPARENT_BLUE_VALUE); res.put(idx++, caps.getTransparentBlueValue()>=0?caps.getTransparentBlueValue():(int)GLX.GLX_DONT_CARE); res.put(idx++, GLX.GLX_TRANSPARENT_ALPHA_VALUE); res.put(idx++, caps.getTransparentAlphaValue()>=0?caps.getTransparentAlphaValue():(int)GLX.GLX_DONT_CARE); } */ } else { if (caps.getDoubleBuffered()) { res.put(idx++, GLX.GLX_DOUBLEBUFFER); } if (caps.getStereo()) { res.put(idx++, GLX.GLX_STEREO); } } res.put(idx++, GLX.GLX_RED_SIZE); res.put(idx++, caps.getRedBits()); res.put(idx++, GLX.GLX_GREEN_SIZE); res.put(idx++, caps.getGreenBits()); res.put(idx++, GLX.GLX_BLUE_SIZE); res.put(idx++, caps.getBlueBits()); if(caps.getAlphaBits()>0) { res.put(idx++, GLX.GLX_ALPHA_SIZE); res.put(idx++, caps.getAlphaBits()); } if (caps.getStencilBits() > 0) { res.put(idx++, GLX.GLX_STENCIL_SIZE); res.put(idx++, caps.getStencilBits()); } res.put(idx++, GLX.GLX_DEPTH_SIZE); res.put(idx++, caps.getDepthBits()); if (caps.getAccumRedBits() > 0 || caps.getAccumGreenBits() > 0 || caps.getAccumBlueBits() > 0 || caps.getAccumAlphaBits() > 0) { res.put(idx++, GLX.GLX_ACCUM_RED_SIZE); res.put(idx++, caps.getAccumRedBits()); res.put(idx++, GLX.GLX_ACCUM_GREEN_SIZE); res.put(idx++, caps.getAccumGreenBits()); res.put(idx++, GLX.GLX_ACCUM_BLUE_SIZE); res.put(idx++, caps.getAccumBlueBits()); res.put(idx++, GLX.GLX_ACCUM_ALPHA_SIZE); res.put(idx++, caps.getAccumAlphaBits()); } if (isMultisampleAvailable && caps.getSampleBuffers()) { res.put(idx++, GLX.GLX_SAMPLE_BUFFERS); res.put(idx++, GL.GL_TRUE); res.put(idx++, GLX.GLX_SAMPLES); res.put(idx++, caps.getNumSamples()); } res.put(idx++, 0); return res; } // FBConfig static boolean GLXFBConfigIDValid(long display, int screen, int fbcfgid) { long fbcfg = X11GLXGraphicsConfiguration.glXFBConfigID2FBConfig(display, screen, fbcfgid); return (0 != fbcfg) ? X11GLXGraphicsConfiguration.GLXFBConfigValid( display, fbcfg ) : false ; } static boolean GLXFBConfigValid(long display, long fbcfg) { final IntBuffer tmp = Buffers.newDirectIntBuffer(1); if(GLX.GLX_BAD_ATTRIBUTE == GLX.glXGetFBConfigAttrib(display, fbcfg, GLX.GLX_RENDER_TYPE, tmp)) { return false; } return true; } static int FBCfgDrawableTypeBits(final X11GraphicsDevice device, final long fbcfg) { int val = 0; final IntBuffer tmp = Buffers.newDirectIntBuffer(1); int fbtype = glXGetFBConfig(device.getHandle(), fbcfg, GLX.GLX_DRAWABLE_TYPE, tmp); if ( 0 != ( fbtype & GLX.GLX_WINDOW_BIT ) ) { val |= GLGraphicsConfigurationUtil.WINDOW_BIT | GLGraphicsConfigurationUtil.FBO_BIT; } if ( 0 != ( fbtype & GLX.GLX_PIXMAP_BIT ) ) { val |= GLGraphicsConfigurationUtil.BITMAP_BIT; } if ( 0 != ( fbtype & GLX.GLX_PBUFFER_BIT ) ) { val |= GLGraphicsConfigurationUtil.PBUFFER_BIT; } return val; } static XRenderDirectFormat XVisual2XRenderMask(long dpy, long visual) { XRenderPictFormat renderPictFmt = X11Lib.XRenderFindVisualFormat(dpy, visual); if(null == renderPictFmt) { return null; } return renderPictFmt.getDirect(); } static X11GLCapabilities GLXFBConfig2GLCapabilities(X11GraphicsDevice device, GLProfile glp, long fbcfg, int winattrmask, boolean isMultisampleAvailable) { final int allDrawableTypeBits = FBCfgDrawableTypeBits(device, fbcfg); int drawableTypeBits = winattrmask & allDrawableTypeBits; final long display = device.getHandle(); int fbcfgid = X11GLXGraphicsConfiguration.glXFBConfig2FBConfigID(display, fbcfg); XVisualInfo visualInfo = GLX.glXGetVisualFromFBConfig(display, fbcfg); if(null == visualInfo) { if(DEBUG) { System.err.println("X11GLXGraphicsConfiguration.GLXFBConfig2GLCapabilities: Null XVisualInfo for FBConfigID 0x" + Integer.toHexString(fbcfgid)); } // onscreen must have an XVisualInfo drawableTypeBits &= ~(GLGraphicsConfigurationUtil.WINDOW_BIT | GLGraphicsConfigurationUtil.FBO_BIT); } if( 0 == drawableTypeBits ) { return null; } final IntBuffer tmp = Buffers.newDirectIntBuffer(1); if(GLX.GLX_BAD_ATTRIBUTE == GLX.glXGetFBConfigAttrib(display, fbcfg, GLX.GLX_RENDER_TYPE, tmp)) { return null; } if( 0 == ( GLX.GLX_RGBA_BIT & tmp.get(0) ) ) { return null; // no RGBA -> color index not supported } final X11GLCapabilities res = new X11GLCapabilities(visualInfo, fbcfg, fbcfgid, glp); if (isMultisampleAvailable) { res.setSampleBuffers(glXGetFBConfig(display, fbcfg, GLX.GLX_SAMPLE_BUFFERS, tmp) != 0); res.setNumSamples (glXGetFBConfig(display, fbcfg, GLX.GLX_SAMPLES, tmp)); } final XRenderDirectFormat xrmask = ( null != visualInfo ) ? XVisual2XRenderMask( display, visualInfo.getVisual() ) : null ; final int alphaMask = ( null != xrmask ) ? xrmask.getAlphaMask() : 0; res.setBackgroundOpaque( 0 >= alphaMask ); if( !res.isBackgroundOpaque() ) { res.setTransparentRedValue(xrmask.getRedMask()); res.setTransparentGreenValue(xrmask.getGreenMask()); res.setTransparentBlueValue(xrmask.getBlueMask()); res.setTransparentAlphaValue(alphaMask); } // ALPHA shall be set at last - due to it's auto setting by the above (!opaque / samples) res.setDoubleBuffered(glXGetFBConfig(display, fbcfg, GLX.GLX_DOUBLEBUFFER, tmp) != 0); res.setStereo (glXGetFBConfig(display, fbcfg, GLX.GLX_STEREO, tmp) != 0); res.setHardwareAccelerated(glXGetFBConfig(display, fbcfg, GLX.GLX_CONFIG_CAVEAT, tmp) != GLX.GLX_SLOW_CONFIG); res.setRedBits (glXGetFBConfig(display, fbcfg, GLX.GLX_RED_SIZE, tmp)); res.setGreenBits (glXGetFBConfig(display, fbcfg, GLX.GLX_GREEN_SIZE, tmp)); res.setBlueBits (glXGetFBConfig(display, fbcfg, GLX.GLX_BLUE_SIZE, tmp)); res.setAlphaBits (glXGetFBConfig(display, fbcfg, GLX.GLX_ALPHA_SIZE, tmp)); res.setAccumRedBits (glXGetFBConfig(display, fbcfg, GLX.GLX_ACCUM_RED_SIZE, tmp)); res.setAccumGreenBits(glXGetFBConfig(display, fbcfg, GLX.GLX_ACCUM_GREEN_SIZE, tmp)); res.setAccumBlueBits (glXGetFBConfig(display, fbcfg, GLX.GLX_ACCUM_BLUE_SIZE, tmp)); res.setAccumAlphaBits(glXGetFBConfig(display, fbcfg, GLX.GLX_ACCUM_ALPHA_SIZE, tmp)); res.setDepthBits (glXGetFBConfig(display, fbcfg, GLX.GLX_DEPTH_SIZE, tmp)); res.setStencilBits (glXGetFBConfig(display, fbcfg, GLX.GLX_STENCIL_SIZE, tmp)); return (X11GLCapabilities) GLGraphicsConfigurationUtil.fixWinAttribBitsAndHwAccel(device, drawableTypeBits, res); } private static String glXGetFBConfigErrorCode(int err) { switch (err) { case GLX.GLX_NO_EXTENSION: return "GLX_NO_EXTENSION"; case GLX.GLX_BAD_ATTRIBUTE: return "GLX_BAD_ATTRIBUTE"; default: return "Unknown error code " + err; } } static int glXGetFBConfig(long display, long cfg, int attrib, IntBuffer tmp) { if (display == 0) { throw new GLException("No display connection"); } int res = GLX.glXGetFBConfigAttrib(display, cfg, attrib, tmp); if (res != 0) { throw new GLException("glXGetFBConfig("+toHexString(attrib)+") failed: error code " + glXGetFBConfigErrorCode(res)); } return tmp.get(tmp.position()); } static int glXFBConfig2FBConfigID(long display, long cfg) { final IntBuffer tmpID = Buffers.newDirectIntBuffer(1); return glXGetFBConfig(display, cfg, GLX.GLX_FBCONFIG_ID, tmpID); } static long glXFBConfigID2FBConfig(long display, int screen, int id) { final IntBuffer attribs = Buffers.newDirectIntBuffer(new int[] { GLX.GLX_FBCONFIG_ID, id, 0 }); final IntBuffer count = Buffers.newDirectIntBuffer(1); count.put(0, -1); PointerBuffer fbcfgsL = GLX.glXChooseFBConfig(display, screen, attribs, count); if (fbcfgsL == null || fbcfgsL.limit()<1) { return 0; } return fbcfgsL.get(0); } // Visual Info static XVisualInfo XVisualID2XVisualInfo(long display, long visualID) { int[] count = new int[1]; XVisualInfo template = XVisualInfo.create(); template.setVisualid(visualID); XVisualInfo[] infos = X11Lib.XGetVisualInfo(display, X11Lib.VisualIDMask, template, count, 0); if (infos == null || infos.length == 0) { return null; } XVisualInfo res = XVisualInfo.create(infos[0]); if (DEBUG) { System.err.println("Fetched XVisualInfo for visual ID " + toHexString(visualID)); System.err.println("Resulting XVisualInfo: visualid = " + toHexString(res.getVisualid())); } return res; } static X11GLCapabilities XVisualInfo2GLCapabilities(final X11GraphicsDevice device, GLProfile glp, XVisualInfo info, final int winattrmask, boolean isMultisampleEnabled) { final int allDrawableTypeBits = GLGraphicsConfigurationUtil.WINDOW_BIT | GLGraphicsConfigurationUtil.BITMAP_BIT | GLGraphicsConfigurationUtil.FBO_BIT ; final int drawableTypeBits = winattrmask & allDrawableTypeBits; if( 0 == drawableTypeBits ) { return null; } final long display = device.getHandle(); final IntBuffer tmp = Buffers.newDirectIntBuffer(1); int val = glXGetConfig(display, info, GLX.GLX_USE_GL, tmp); if (val == 0) { if(DEBUG) { System.err.println("Visual ("+toHexString(info.getVisualid())+") does not support OpenGL"); } return null; } val = glXGetConfig(display, info, GLX.GLX_RGBA, tmp); if (val == 0) { if(DEBUG) { System.err.println("Visual ("+toHexString(info.getVisualid())+") does not support RGBA"); } return null; } GLCapabilities res = new X11GLCapabilities(info, glp); res.setDoubleBuffered(glXGetConfig(display, info, GLX.GLX_DOUBLEBUFFER, tmp) != 0); res.setStereo (glXGetConfig(display, info, GLX.GLX_STEREO, tmp) != 0); // Note: use of hardware acceleration is determined by // glXCreateContext, not by the XVisualInfo. Optimistically claim // that all GLCapabilities have the capability to be hardware // accelerated. if (isMultisampleEnabled) { res.setSampleBuffers(glXGetConfig(display, info, GLX.GLX_SAMPLE_BUFFERS, tmp) != 0); res.setNumSamples (glXGetConfig(display, info, GLX.GLX_SAMPLES, tmp)); } final XRenderDirectFormat xrmask = ( null != info ) ? XVisual2XRenderMask( display, info.getVisual() ) : null ; final int alphaMask = ( null != xrmask ) ? xrmask.getAlphaMask() : 0; res.setBackgroundOpaque( 0 >= alphaMask ); if( !res.isBackgroundOpaque() ) { res.setTransparentRedValue(xrmask.getRedMask()); res.setTransparentGreenValue(xrmask.getGreenMask()); res.setTransparentBlueValue(xrmask.getBlueMask()); res.setTransparentAlphaValue(alphaMask); } // ALPHA shall be set at last - due to it's auto setting by the above (!opaque / samples) res.setHardwareAccelerated(true); res.setDepthBits (glXGetConfig(display, info, GLX.GLX_DEPTH_SIZE, tmp)); res.setStencilBits (glXGetConfig(display, info, GLX.GLX_STENCIL_SIZE, tmp)); res.setRedBits (glXGetConfig(display, info, GLX.GLX_RED_SIZE, tmp)); res.setGreenBits (glXGetConfig(display, info, GLX.GLX_GREEN_SIZE, tmp)); res.setBlueBits (glXGetConfig(display, info, GLX.GLX_BLUE_SIZE, tmp)); res.setAlphaBits (glXGetConfig(display, info, GLX.GLX_ALPHA_SIZE, tmp)); res.setAccumRedBits (glXGetConfig(display, info, GLX.GLX_ACCUM_RED_SIZE, tmp)); res.setAccumGreenBits(glXGetConfig(display, info, GLX.GLX_ACCUM_GREEN_SIZE, tmp)); res.setAccumBlueBits (glXGetConfig(display, info, GLX.GLX_ACCUM_BLUE_SIZE, tmp)); res.setAccumAlphaBits(glXGetConfig(display, info, GLX.GLX_ACCUM_ALPHA_SIZE, tmp)); return (X11GLCapabilities) GLGraphicsConfigurationUtil.fixWinAttribBitsAndHwAccel(device, drawableTypeBits, res); } private static String glXGetConfigErrorCode(int err) { switch (err) { case GLX.GLX_NO_EXTENSION: return "GLX_NO_EXTENSION"; case GLX.GLX_BAD_SCREEN: return "GLX_BAD_SCREEN"; case GLX.GLX_BAD_ATTRIBUTE: return "GLX_BAD_ATTRIBUTE"; case GLX.GLX_BAD_VISUAL: return "GLX_BAD_VISUAL"; default: return "Unknown error code " + err; } } static int glXGetConfig(long display, XVisualInfo info, int attrib, IntBuffer tmp) { if (display == 0) { throw new GLException("No display connection"); } int res = GLX.glXGetConfig(display, info, attrib, tmp); if (res != 0) { throw new GLException("glXGetConfig("+toHexString(attrib)+") failed: error code " + glXGetConfigErrorCode(res)); } return tmp.get(tmp.position()); } public String toString() { return "X11GLXGraphicsConfiguration["+getScreen()+", visualID " + toHexString(getXVisualID()) + ", fbConfigID " + toHexString(getFBConfigID()) + ",\n\trequested " + getRequestedCapabilities()+ ",\n\tchosen " + getChosenCapabilities()+ "]"; } }
false
false
null
null
diff --git a/core/src/com/google/zxing/client/result/ResultParser.java b/core/src/com/google/zxing/client/result/ResultParser.java index 3b8e0762..d8172b4b 100644 --- a/core/src/com/google/zxing/client/result/ResultParser.java +++ b/core/src/com/google/zxing/client/result/ResultParser.java @@ -1,295 +1,295 @@ /* * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.client.result; import com.google.zxing.Result; import java.util.Hashtable; import java.util.Vector; /** * <p>Abstract class representing the result of decoding a barcode, as more than * a String -- as some type of structured data. This might be a subclass which represents * a URL, or an e-mail address. {@link #parseResult(com.google.zxing.Result)} will turn a raw * decoded string into the most appropriate type of structured representation.</p> * * <p>Thanks to Jeff Griffin for proposing rewrite of these classes that relies less * on exception-based mechanisms during parsing.</p> * * @author Sean Owen */ public abstract class ResultParser { public static ParsedResult parseResult(Result theResult) { // This is a bit messy, but given limited options in MIDP / CLDC, this may well be the simplest // way to go about this. For example, we have no reflection available, really. // Order is important here. ParsedResult result; if ((result = BookmarkDoCoMoResultParser.parse(theResult)) != null) { return result; } else if ((result = AddressBookDoCoMoResultParser.parse(theResult)) != null) { return result; } else if ((result = EmailDoCoMoResultParser.parse(theResult)) != null) { return result; } else if ((result = AddressBookAUResultParser.parse(theResult)) != null) { return result; } else if ((result = VCardResultParser.parse(theResult)) != null) { return result; } else if ((result = BizcardResultParser.parse(theResult)) != null) { return result; } else if ((result = VEventResultParser.parse(theResult)) != null) { return result; + } else if ((result = EmailAddressResultParser.parse(theResult)) != null) { + return result; } else if ((result = TelResultParser.parse(theResult)) != null) { return result; } else if ((result = SMSMMSResultParser.parse(theResult)) != null) { return result; } else if ((result = GeoResultParser.parse(theResult)) != null) { return result; } else if ((result = URLTOResultParser.parse(theResult)) != null) { return result; } else if ((result = URIResultParser.parse(theResult)) != null) { return result; - } else if ((result = EmailAddressResultParser.parse(theResult)) != null) { - return result; } else if ((result = ISBNResultParser.parse(theResult)) != null) { // We depend on ISBN parsing coming before UPC, as it is a subset. return result; } else if ((result = ProductResultParser.parse(theResult)) != null) { return result; } return new TextParsedResult(theResult.getText(), null); } protected static void maybeAppend(String value, StringBuffer result) { if (value != null) { result.append('\n'); result.append(value); } } protected static void maybeAppend(String[] value, StringBuffer result) { if (value != null) { for (int i = 0; i < value.length; i++) { result.append('\n'); result.append(value[i]); } } } protected static String[] maybeWrap(String value) { return value == null ? null : new String[] { value }; } protected static String unescapeBackslash(String escaped) { if (escaped != null) { int backslash = escaped.indexOf((int) '\\'); if (backslash >= 0) { int max = escaped.length(); StringBuffer unescaped = new StringBuffer(max - 1); unescaped.append(escaped.toCharArray(), 0, backslash); boolean nextIsEscaped = false; for (int i = backslash; i < max; i++) { char c = escaped.charAt(i); if (nextIsEscaped || c != '\\') { unescaped.append(c); nextIsEscaped = false; } else { nextIsEscaped = true; } } return unescaped.toString(); } } return escaped; } static String urlDecode(String escaped) { // No we can't use java.net.URLDecoder here. JavaME doesn't have it. if (escaped == null) { return null; } char[] escapedArray = escaped.toCharArray(); int first = findFirstEscape(escapedArray); if (first < 0) { return escaped; } int max = escapedArray.length; // final length is at most 2 less than original due to at least 1 unescaping StringBuffer unescaped = new StringBuffer(max - 2); // Can append everything up to first escape character unescaped.append(escapedArray, 0, first); for (int i = first; i < max; i++) { char c = escapedArray[i]; if (c == '+') { // + is translated directly into a space unescaped.append(' '); } else if (c == '%') { // Are there even two more chars? if not we will just copy the escaped sequence and be done if (i >= max - 2) { unescaped.append('%'); // append that % and move on } else { int firstDigitValue = parseHexDigit(escapedArray[++i]); int secondDigitValue = parseHexDigit(escapedArray[++i]); if (firstDigitValue < 0 || secondDigitValue < 0) { // bad digit, just move on unescaped.append('%'); unescaped.append(escapedArray[i-1]); unescaped.append(escapedArray[i]); } unescaped.append((char) ((firstDigitValue << 4) + secondDigitValue)); } } else { unescaped.append(c); } } return unescaped.toString(); } private static int findFirstEscape(char[] escapedArray) { int max = escapedArray.length; for (int i = 0; i < max; i++) { char c = escapedArray[i]; if (c == '+' || c == '%') { return i; } } return -1; } private static int parseHexDigit(char c) { if (c >= 'a') { if (c <= 'f') { return 10 + (c - 'a'); } } else if (c >= 'A') { if (c <= 'F') { return 10 + (c - 'A'); } } else if (c >= '0') { if (c <= '9') { return c - '0'; } } return -1; } protected static boolean isStringOfDigits(String value, int length) { if (value == null) { return false; } int stringLength = value.length(); if (length != stringLength) { return false; } for (int i = 0; i < length; i++) { char c = value.charAt(i); if (c < '0' || c > '9') { return false; } } return true; } static Hashtable parseNameValuePairs(String uri) { int paramStart = uri.indexOf('?'); if (paramStart < 0) { return null; } Hashtable result = new Hashtable(3); paramStart++; int paramEnd; while ((paramEnd = uri.indexOf('&', paramStart)) >= 0) { appendKeyValue(uri, paramStart, paramEnd, result); paramStart = paramEnd + 1; } appendKeyValue(uri, paramStart, uri.length(), result); return result; } private static void appendKeyValue(String uri, int paramStart, int paramEnd, Hashtable result) { int separator = uri.indexOf('=', paramStart); if (separator >= 0) { // key = value String key = uri.substring(paramStart, separator); String value = uri.substring(separator + 1, paramEnd); value = urlDecode(value); result.put(key, value); } // Can't put key, null into a hashtable } static String[] matchPrefixedField(String prefix, String rawText, char endChar, boolean trim) { Vector matches = null; int i = 0; int max = rawText.length(); while (i < max) { i = rawText.indexOf(prefix, i); if (i < 0) { break; } i += prefix.length(); // Skip past this prefix we found to start int start = i; // Found the start of a match here boolean done = false; while (!done) { i = rawText.indexOf((int) endChar, i); if (i < 0) { // No terminating end character? uh, done. Set i such that loop terminates and break i = rawText.length(); done = true; } else if (rawText.charAt(i - 1) == '\\') { // semicolon was escaped so continue i++; } else { // found a match if (matches == null) { matches = new Vector(3); // lazy init } String element = unescapeBackslash(rawText.substring(start, i)); if (trim) { element = element.trim(); } matches.addElement(element); i++; done = true; } } } if (matches == null || matches.isEmpty()) { return null; } return toStringArray(matches); } static String matchSinglePrefixedField(String prefix, String rawText, char endChar, boolean trim) { String[] matches = matchPrefixedField(prefix, rawText, endChar, trim); return matches == null ? null : matches[0]; } static String[] toStringArray(Vector strings) { int size = strings.size(); String[] result = new String[size]; for (int j = 0; j < size; j++) { result[j] = (String) strings.elementAt(j); } return result; } }
false
false
null
null
diff --git a/src/kg/apc/jmeter/charting/GraphPanelChart.java b/src/kg/apc/jmeter/charting/GraphPanelChart.java index da69e62a..77802469 100644 --- a/src/kg/apc/jmeter/charting/GraphPanelChart.java +++ b/src/kg/apc/jmeter/charting/GraphPanelChart.java @@ -1,1073 +1,1080 @@ package kg.apc.jmeter.charting; import java.awt.AlphaComposite; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Composite; import java.awt.Font; import java.awt.FontMetrics; import java.awt.GradientPaint; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.Stroke; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.ClipboardOwner; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.AbstractMap; import java.util.Iterator; import java.util.Map.Entry; import javax.imageio.ImageIO; import javax.swing.BorderFactory; import javax.swing.JComponent; import javax.swing.JFileChooser; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPopupMenu; import javax.swing.border.BevelBorder; import javax.swing.filechooser.FileNameExtensionFilter; import org.apache.jmeter.util.JMeterUtils; import org.apache.jorphan.gui.NumberRenderer; import org.apache.jorphan.logging.LoggingManager; import org.apache.log.Logger; /** * * @author apc */ public class GraphPanelChart extends JComponent implements ClipboardOwner { private static final String AD_TEXT = "http://apc.kg"; private static final String NO_SAMPLES = "Waiting for samples..."; private static final int spacing = 5; /* * Special type of graph were minY is forced to 0 and maxY is forced to 100 * to display percentage charts (eg cpu monitoring) */ public static final int CHART_PERCENTAGE = 0; public static final int CHART_DEFAULT = -1; private static final Logger log = LoggingManager.getLoggerForClass(); private Rectangle legendRect; private Rectangle xAxisRect; private Rectangle yAxisRect; private Rectangle chartRect; private static final Rectangle zeroRect = new Rectangle(); private AbstractMap<String, AbstractGraphRow> rows; private double maxYVal; private double minYVal; private long maxXVal; private long minXVal; private long currentXVal; private static final int gridLinesCount = 10; private NumberRenderer yAxisLabelRenderer; private NumberRenderer xAxisLabelRenderer; private boolean drawCurrentX = false; private int forcedMinX = -1; private int chartType = CHART_DEFAULT; // The stroke used to paint Graph's dashed lines private Stroke dashStroke = new BasicStroke( 1.0f, // Width BasicStroke.CAP_SQUARE, // End cap BasicStroke.JOIN_MITER, // Join style 10.0f, // Miter limit new float[] { 1.0f, 4.0f }, // Dash pattern 0.0f); // Dash phase // The stroke to paint thick Graph rows private Stroke thickStroke = new BasicStroke( AbstractGraphRow.LINE_THICKNESS_BIG, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL); // Message display in graphs. Used for perfmon error messages private String errorMessage = null; // Chart's gradient background end color private Color gradientColor = new Color(229, 236, 246); // Chart's Axis Color. For good results, use gradient color - (30, 30, 30) private Color axisColor = new Color(199, 206, 216); //the composite used to draw bars AlphaComposite barComposite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f); //save file path. We remember last folder used. private static String savePath = null; //limit the maximum number of points when drawing a line, by averaging values //if necessary. If -1 is assigned, no limit. private int maxPoints = -1; // Default draw options - these are default values if no property is entered in user.properties // List of possible properties (TODO: The explaination must be written in readme file) // jmeterPlugin.drawGradient=(true/false) // jmeterPlugin.neverDrawFinalZeroingLines=(true/false) // jmeterPlugin.optimizeYAxis=(true/false) // jmeterPlugin.neverDrawCurrentX=(true/false) // note to Andrey: Feel free to decide the default value! private static boolean drawGradient = true; private static boolean neverDrawFinalZeroingLines = false; private static boolean optimizeYAxis = true; private static boolean neverDrawCurrentX = false; //some of these preference can be overidden by the preference tab: private boolean settingsDrawGradient; private boolean settingsDrawFinalZeroingLines; private boolean settingsDrawCurrentX; public void setSettingsDrawCurrentX(boolean settingsDrawCurrentX) { this.settingsDrawCurrentX = settingsDrawCurrentX; } public void setSettingsDrawFinalZeroingLines(boolean settingsDrawFinalZeroingLines) { this.settingsDrawFinalZeroingLines = settingsDrawFinalZeroingLines; } public void setSettingsDrawGradient(boolean settingsDrawGradient) { this.settingsDrawGradient = settingsDrawGradient; } public boolean isSettingsDrawCurrentX() { return settingsDrawCurrentX; } public boolean isSettingsDrawGradient() { return settingsDrawGradient; } public static boolean isGlobalDrawFinalZeroingLines() { return !neverDrawFinalZeroingLines; } // If user entered configuration items in user.properties, overide default values. static { String cfgDrawGradient = JMeterUtils.getProperty("jmeterPlugin.drawGradient"); if (cfgDrawGradient != null) { GraphPanelChart.drawGradient = "true".equalsIgnoreCase(cfgDrawGradient); } String cfgNeverDrawFinalZeroingLines = JMeterUtils.getProperty("jmeterPlugin.neverDrawFinalZeroingLines"); if (cfgNeverDrawFinalZeroingLines != null) { GraphPanelChart.neverDrawFinalZeroingLines = "true".equalsIgnoreCase(cfgNeverDrawFinalZeroingLines); } String cfgOptimizeYAxis = JMeterUtils.getProperty("jmeterPlugin.optimizeYAxis"); if (cfgOptimizeYAxis != null) { GraphPanelChart.optimizeYAxis = "true".equalsIgnoreCase(cfgOptimizeYAxis); } String cfgNeverDrawFinalCurrentX = JMeterUtils.getProperty("jmeterPlugin.neverDrawCurrentX"); if (cfgNeverDrawFinalCurrentX != null) { GraphPanelChart.neverDrawCurrentX = "true".equalsIgnoreCase(cfgNeverDrawFinalCurrentX); } } /** * Creates new chart object with default parameters */ public GraphPanelChart() { setBackground(Color.white); setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED, Color.lightGray, Color.darkGray)); yAxisLabelRenderer = new NumberRenderer("#.#"); xAxisLabelRenderer = new NumberRenderer("#.#"); legendRect = new Rectangle(); yAxisRect = new Rectangle(); xAxisRect = new Rectangle(); chartRect = new Rectangle(); setDefaultDimensions(); registerPopup(); settingsDrawCurrentX = !neverDrawCurrentX; settingsDrawGradient = drawGradient; settingsDrawFinalZeroingLines = false; } public void setChartType(int type) { chartType = type; } private void drawFinalLines(AbstractGraphRow row, Graphics g, int prevX, int prevY, final double dxForDVal, Stroke oldStroke) { // draw final lines if (row.isDrawLine() && settingsDrawFinalZeroingLines) { if (row.isDrawThickLines()) { ((Graphics2D) g).setStroke(thickStroke); } g.setColor(row.getColor()); g.drawLine(prevX, prevY, (int) (prevX + dxForDVal), chartRect.y + chartRect.height); if (row.isDrawThickLines()) { ((Graphics2D) g).setStroke(oldStroke); } } } private boolean drawMessages(Graphics2D g) { if (errorMessage != null) { g.setColor(Color.RED); g.drawString(errorMessage, getWidth() / 2 - g.getFontMetrics(g.getFont()).stringWidth(errorMessage) / 2, getHeight() / 2); return true; } if (rows.isEmpty()) { g.setColor(Color.BLACK); g.drawString(NO_SAMPLES, getWidth() / 2 - g.getFontMetrics(g.getFont()).stringWidth(NO_SAMPLES) / 2, getHeight() / 2); return true; } return false; } private void getMinMaxDataValues() { maxXVal = 0L; maxYVal = 0L; minXVal = Long.MAX_VALUE; minYVal = Double.MAX_VALUE; Iterator<Entry<String, AbstractGraphRow>> it = rows.entrySet().iterator(); Entry<String, AbstractGraphRow> row = null; AbstractGraphRow rowValue; int barValue = 0; while (it.hasNext()) { row = it.next(); rowValue = row.getValue(); if (!rowValue.isDrawOnChart()) { continue; } if (rowValue.getMaxY() > maxYVal) { maxYVal = rowValue.getMaxY(); } if (rowValue.getMaxX() > maxXVal) { maxXVal = rowValue.getMaxX(); } if (rowValue.getMinX() < minXVal) { minXVal = rowValue.getMinX(); } if (rowValue.getMinY() < minYVal) { //we draw only positives values minYVal = rowValue.getMinY() >= 0 ? rowValue.getMinY() : 0; } if(rowValue.isDrawBar()) { barValue = rowValue.getGranulationValue(); } } if (barValue > 0) { maxXVal += barValue; //find nice X steps double barPerSquare = (double) (maxXVal - minXVal) / (barValue * gridLinesCount); double step = Math.floor(barPerSquare)+1; maxXVal = (long) (minXVal + step * barValue * gridLinesCount); } //maxYVal *= 1 + (double) 1 / (double) gridLinesCount; if (forcedMinX >= 0L) { minXVal = forcedMinX; } //prevent X axis not initialized in case of no row displayed //we use last known row if ((minXVal == Long.MAX_VALUE && maxXVal == 0L && row != null) || (forcedMinX >= 0L && maxXVal == 0L && row != null)) { maxXVal = row.getValue().getMaxX(); if(forcedMinX >= 0L) { minXVal = forcedMinX; } else { minXVal = row.getValue().getMinX(); } minYVal = 0; maxYVal = 10; } else if (optimizeYAxis) { computeChartSteps(); } else { minYVal = 0; } } /** * compute minY and step value to have better readable charts */ private void computeChartSteps() { //if special type if (chartType == GraphPanelChart.CHART_PERCENTAGE) { minYVal = 0; maxYVal = 100; return; } //try to find the best range... //first, avoid special cases where maxY equal or close to minY if (maxYVal - minYVal < 0.1) { maxYVal = minYVal + 1; } //real step double step = (maxYVal - minYVal) / gridLinesCount; int pow = -1; double factor = -1; boolean found = false; double testStep; double testFactor; //find a step close to the real one while (!found) { pow++; //for small range (<10), don't use .5 factor. //we try to find integer steps as it is more easy to read if (pow > 0) { testFactor = 0.5; } else { testFactor = 1; } for (double f = 0; f <= 5; f = f + testFactor) { testStep = Math.pow(10, pow) * f; if (testStep >= step) { factor = f; found = true; break; } } } //first proposal double foundStep = Math.pow(10, pow) * factor; //we shift to the closest lower minval to align with the step minYVal = minYVal - minYVal % foundStep; //check if step is still good with minY trimmed. If not, use next factor. if (minYVal + foundStep * gridLinesCount < maxYVal) { foundStep = Math.pow(10, pow) * (factor + (pow > 0 ? 0.5 : 1)); } //last visual optimization: find the optimal minYVal double trim = 10; while ((minYVal - minYVal % trim) + foundStep * gridLinesCount >= maxYVal && minYVal > 0) { minYVal = minYVal - minYVal % trim; trim = trim * 10; } //final calculation maxYVal = minYVal + foundStep * gridLinesCount; } private void setDefaultDimensions() { chartRect.setBounds(spacing, spacing, getWidth() - spacing * 2, getHeight() - spacing * 2); legendRect.setBounds(zeroRect); xAxisRect.setBounds(zeroRect); yAxisRect.setBounds(zeroRect); } private void calculateYAxisDimensions(FontMetrics fm) { // TODO: middle value labels often wider than max yAxisLabelRenderer.setValue(maxYVal); int axisWidth = fm.stringWidth(yAxisLabelRenderer.getText()) + spacing * 3; yAxisRect.setBounds(chartRect.x, chartRect.y, axisWidth, chartRect.height); chartRect.setBounds(chartRect.x + axisWidth, chartRect.y, chartRect.width - axisWidth, chartRect.height); } private void calculateXAxisDimensions(FontMetrics fm) { // FIXME: first value on X axis may take negative X coord, // we need to handle this and make Y axis wider int axisHeight = fm.getHeight() + spacing; xAxisLabelRenderer.setValue(maxXVal); int axisEndSpace = fm.stringWidth(xAxisLabelRenderer.getText()) / 2; xAxisRect.setBounds(chartRect.x, chartRect.y + chartRect.height - axisHeight, chartRect.width, axisHeight); chartRect.setBounds(chartRect.x, chartRect.y, chartRect.width - axisEndSpace, chartRect.height - axisHeight); yAxisRect.setBounds(yAxisRect.x, yAxisRect.y, yAxisRect.width, chartRect.height); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); BufferedImage image = new BufferedImage(this.getWidth(), this.getHeight(), BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = image.createGraphics(); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); drawPanel(g2d); g.drawImage(image, 0, 0, this); } private void drawPanel(Graphics2D g) { g.setColor(Color.white); if (settingsDrawGradient) { GradientPaint gdp = new GradientPaint(0, 0, Color.white, 0, getHeight(), gradientColor); g.setPaint(gdp); } g.fillRect(0, 0, getWidth(), getHeight()); paintAd(g); if (drawMessages(g)) { return; } setDefaultDimensions(); getMinMaxDataValues(); try { paintLegend(g); calculateYAxisDimensions(g.getFontMetrics(g.getFont())); calculateXAxisDimensions(g.getFontMetrics(g.getFont())); paintYAxis(g); paintXAxis(g); paintChart(g); } catch (Exception e) { log.error("Error in paintComponent", e); } } private void paintLegend(Graphics g) { FontMetrics fm = g.getFontMetrics(g.getFont()); int rectH = fm.getHeight(); int rectW = rectH; Iterator<Entry<String, AbstractGraphRow>> it = rows.entrySet().iterator(); Entry<String, AbstractGraphRow> row; int currentX = chartRect.x; int currentY = chartRect.y; int legendHeight = it.hasNext() ? rectH + spacing : 0; while (it.hasNext()) { row = it.next(); if (!row.getValue().isShowInLegend() || !row.getValue().isDrawOnChart()) { continue; } // wrap row if overflowed if (currentX + rectW + spacing / 2 + fm.stringWidth(row.getKey()) > getWidth()) { currentY += rectH + spacing / 2; legendHeight += rectH + spacing / 2; currentX = chartRect.x; } // draw legend color box g.setColor(row.getValue().getColor()); Composite oldComposite = null; if (row.getValue().isDrawBar()) { oldComposite = ((Graphics2D) g).getComposite(); ((Graphics2D) g).setComposite(barComposite); } g.fillRect(currentX, currentY, rectW, rectH); if (row.getValue().isDrawBar()) { ((Graphics2D) g).setComposite(oldComposite); } g.setColor(Color.black); g.drawRect(currentX, currentY, rectW, rectH); // draw legend item label currentX += rectW + spacing / 2; g.drawString(row.getKey(), currentX, (int) (currentY + rectH * 0.9)); currentX += fm.stringWidth(row.getKey()) + spacing; } legendRect.setBounds(chartRect.x, chartRect.y, chartRect.width, legendHeight); chartRect.setBounds(chartRect.x, chartRect.y + legendHeight + spacing, chartRect.width, chartRect.height - legendHeight - spacing); } private void paintYAxis(Graphics g) { FontMetrics fm = g.getFontMetrics(g.getFont()); String valueLabel; int labelXPos; int gridLineY; // shift 2nd and more lines int shift = 0; // for strokes swapping Stroke oldStroke = ((Graphics2D) g).getStroke(); //draw markers g.setColor(axisColor); for (int n = 0; n <= gridLinesCount; n++) { gridLineY = chartRect.y + (int) ((gridLinesCount - n) * (double) chartRect.height / gridLinesCount); g.drawLine(chartRect.x - 3, gridLineY, chartRect.x + 3, gridLineY); } for (int n = 0; n <= gridLinesCount; n++) { //draw 2nd and more axis dashed and shifted if (n != 0) { ((Graphics2D) g).setStroke(dashStroke); shift = 7; } gridLineY = chartRect.y + (int) ((gridLinesCount - n) * (double) chartRect.height / gridLinesCount); // draw grid line with tick g.setColor(axisColor); g.drawLine(chartRect.x + shift, gridLineY, chartRect.x + chartRect.width, gridLineY); g.setColor(Color.black); // draw label yAxisLabelRenderer.setValue((minYVal * gridLinesCount + n * (maxYVal - minYVal)) / gridLinesCount); valueLabel = yAxisLabelRenderer.getText(); labelXPos = yAxisRect.x + yAxisRect.width - fm.stringWidth(valueLabel) - spacing - spacing / 2; g.drawString(valueLabel, labelXPos, gridLineY + fm.getAscent() / 2); } //restore stroke ((Graphics2D) g).setStroke(oldStroke); } private void paintXAxis(Graphics g) { FontMetrics fm = g.getFontMetrics(g.getFont()); String valueLabel; int labelXPos; int gridLineX; // shift 2nd and more lines int shift = 0; // for strokes swapping Stroke oldStroke = ((Graphics2D) g).getStroke(); g.setColor(axisColor); //draw markers for (int n = 0; n <= gridLinesCount; n++) { gridLineX = chartRect.x + (int) (n * ((double) chartRect.width / gridLinesCount)); g.drawLine(gridLineX, chartRect.y + chartRect.height - 3, gridLineX, chartRect.y + chartRect.height + 3); } for (int n = 0; n <= gridLinesCount; n++) { //draw 2nd and more axis dashed and shifted if (n != 0) { ((Graphics2D) g).setStroke(dashStroke); shift = 7; } gridLineX = chartRect.x + (int) (n * ((double) chartRect.width / gridLinesCount)); // draw grid line with tick g.setColor(axisColor); g.drawLine(gridLineX, chartRect.y + chartRect.height - shift, gridLineX, chartRect.y); g.setColor(Color.black); // draw label xAxisLabelRenderer.setValue(minXVal + n * (double) (maxXVal - minXVal) / gridLinesCount); valueLabel = xAxisLabelRenderer.getText(); labelXPos = gridLineX - fm.stringWidth(valueLabel) / 2; g.drawString(valueLabel, labelXPos, xAxisRect.y + fm.getAscent() + spacing); } //restore stroke ((Graphics2D) g).setStroke(oldStroke); if (drawCurrentX && settingsDrawCurrentX) { gridLineX = chartRect.x + (int) ((currentXVal - minXVal) * (double) chartRect.width / (maxXVal - minXVal)); g.setColor(Color.GRAY); g.drawLine(gridLineX, chartRect.y, gridLineX, chartRect.y + chartRect.height); g.setColor(Color.black); } } private void paintChart(Graphics g) { g.setColor(Color.yellow); Iterator<Entry<String, AbstractGraphRow>> it = rows.entrySet().iterator(); int biggestRowSize = getBiggestRowSize(); while (it.hasNext()) { Entry<String, AbstractGraphRow> row = it.next(); if (row.getValue().isDrawOnChart()) { paintRow(g, row.getValue(), biggestRowSize); } } } /* * Check if the point (x,y) is contained in the chart area + * We check only minX, maxX, and maxY to avoid flickering. + * We take max(chartRect.y, y) as redering value * This is done to prevent line out of range if new point is added * during chart paint. */ private boolean isChartPointValid(int x, int y) { boolean ret = true; //check x if (x < chartRect.x || x > chartRect.x + chartRect.width) { ret = false; } else //check y - if (y < chartRect.y || y > chartRect.y + chartRect.height) + if (y > chartRect.y + chartRect.height) { ret = false; } return ret; } public void setMaxPoints(int maxPoints) { this.maxPoints = maxPoints; } private int getBiggestRowSize() { int max = 1; Iterator<Entry<String, AbstractGraphRow>> it = rows.entrySet().iterator(); while (it.hasNext()) { Entry<String, AbstractGraphRow> row = it.next(); if (row.getValue().isDrawOnChart()) { int size = row.getValue().size(); if ( size > max) { max = size; } } } return max; } private void paintRow(Graphics g, AbstractGraphRow row, int biggestRowSize) { //how many points to average? int factor; if (maxPoints > 0) { factor = (biggestRowSize / maxPoints) + 1; } else { factor = 1; } FontMetrics fm = g.getFontMetrics(g.getFont()); Iterator<Entry<Long, AbstractGraphPanelChartElement>> it = row.iterator(); Entry<Long, AbstractGraphPanelChartElement> element; int radius = row.getMarkerSize(); int x, y; int prevX = settingsDrawFinalZeroingLines ? chartRect.x : -1; int prevY = chartRect.y + chartRect.height; final double dxForDVal = (maxXVal <= minXVal) ? 0 : (double) chartRect.width / (maxXVal - minXVal); final double dyForDVal = (maxYVal <= minYVal) ? 0 : (double) chartRect.height / (maxYVal - minYVal); Stroke oldStroke = null; if (row.isDrawThickLines()) { oldStroke = ((Graphics2D) g).getStroke(); } //for better display, we always draw the first point boolean firstPoint = true; //how many actual points were averaged (basically, to handle last points of the collection) int nbAveragedValues = 0; while (it.hasNext()) { if (!row.isDrawOnChart()) { continue; } double calcPointX = 0; double calcPointY = 0; if (factor == 1 || firstPoint) { firstPoint = false; element = it.next(); calcPointX = element.getKey().doubleValue(); calcPointY = ((AbstractGraphPanelChartElement) element.getValue()).getValue(); } else { nbAveragedValues = 0; for (int i = 0; i < factor; i++) { if (it.hasNext()) { nbAveragedValues++; element = it.next(); calcPointX = calcPointX + element.getKey().doubleValue(); calcPointY = calcPointY + ((AbstractGraphPanelChartElement) element.getValue()).getValue(); } } calcPointX = calcPointX / nbAveragedValues; calcPointY = calcPointY / nbAveragedValues; } x = chartRect.x + (int) ((calcPointX - minXVal) * dxForDVal); int yHeight = (int) ((calcPointY - minYVal) * dyForDVal); y = chartRect.y + chartRect.height - yHeight; + //fix flickering + if( y < chartRect.y) + { + y = chartRect.y; + } if (row.isDrawThickLines()) { ((Graphics2D) g).setStroke(thickStroke); } // draw lines if (row.isDrawLine()) { if (prevX > 0) { g.setColor(row.getColor()); if (isChartPointValid(x, y)) { g.drawLine(prevX, prevY, x, y); } } prevX = x; prevY = y; } // draw bars if (row.isDrawBar()) { g.setColor(row.getColor()); if (isChartPointValid(x, y)) { //x = chartRect.x + (int) ((calcPointX - minXVal) * dxForDVal); int x2 = chartRect.x + (int) ((calcPointX + row.getGranulationValue() - minXVal) * dxForDVal) - x -1; //g.drawRect(x, y, x2, yHeight); Composite oldComposite = ((Graphics2D) g).getComposite(); ((Graphics2D) g).setComposite(barComposite); g.fillRect(x, y-1, x2 , yHeight+1); ((Graphics2D) g).setComposite(oldComposite); } } if (row.isDrawThickLines()) { ((Graphics2D) g).setStroke(oldStroke); } if (row.isDrawValueLabel()) { g.setColor(Color.DARK_GRAY); yAxisLabelRenderer.setValue(calcPointY); g.drawString(yAxisLabelRenderer.getText(), x + row.getMarkerSize() + spacing, y + fm.getAscent() / 2); } // draw markers if (radius != AbstractGraphRow.MARKER_SIZE_NONE) { g.setColor(row.getColor()); if (isChartPointValid(x, y)) { g.fillOval(x - radius, y - radius, (radius) * 2, (radius) * 2); //g.setColor(Color.black); //g.drawOval(x - radius, y - radius, radius * 2, radius * 2); } } } drawFinalLines(row, g, prevX, prevY, dxForDVal, oldStroke); } /** * * @param aRows */ public void setRows(AbstractMap<String, AbstractGraphRow> aRows) { rows = aRows; } /** * @param yAxisLabelRenderer the yAxisLabelRenderer to set */ public void setyAxisLabelRenderer(NumberRenderer yAxisLabelRenderer) { this.yAxisLabelRenderer = yAxisLabelRenderer; } /** * @param xAxisLabelRenderer the xAxisLabelRenderer to set */ public void setxAxisLabelRenderer(NumberRenderer xAxisLabelRenderer) { this.xAxisLabelRenderer = xAxisLabelRenderer; } /** * @param drawFinalZeroingLines the drawFinalZeroingLines to set */ public void setDrawFinalZeroingLines(boolean drawFinalZeroingLines) { settingsDrawFinalZeroingLines = drawFinalZeroingLines && !neverDrawFinalZeroingLines; } /** * @param drawCurrentX the drawCurrentX to set */ public void setDrawCurrentX(boolean drawCurrentX) { this.drawCurrentX = drawCurrentX; } /** * @param currentX the currentX to set */ public void setCurrentX(long currentX) { this.currentXVal = currentX; } /** * * @param i */ public void setForcedMinX(int i) { forcedMinX = i; } //Paint the add the same color of the axis but with transparency private void paintAd(Graphics2D g) { Font oldFont = g.getFont(); g.setFont(g.getFont().deriveFont(10F)); g.setColor(axisColor); Composite oldComposite = g.getComposite(); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.7f)); g.drawString(AD_TEXT, getWidth() - g.getFontMetrics().stringWidth(AD_TEXT) - spacing, g.getFontMetrics().getHeight() - spacing + 1); g.setComposite(oldComposite); g.setFont(oldFont); } /* * Clear error messages */ public void clearErrorMessage() { errorMessage = null; } /* * Set error message if not null and not empty * @param msg the error message to set */ public void setErrorMessage(String msg) { if (msg != null && msg.trim().length() > 0) { errorMessage = msg; } } // Adding a popup menu to copy image in clipboard @Override public void lostOwnership(Clipboard clipboard, Transferable contents) { // do nothing } private Image getImage() { return (Image) getBufferedImage(); } private BufferedImage getBufferedImage() { BufferedImage image = new BufferedImage(this.getWidth(), this.getHeight(), BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = image.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); this.drawPanel(g2); return image; } /** * Thanks to stephane.hoblingre */ private void registerPopup() { JPopupMenu popup = new JPopupMenu(); this.setComponentPopupMenu(popup); JMenuItem itemCopy = new JMenuItem("Copy Image to Clipboard"); JMenuItem itemSave = new JMenuItem("Save Image as..."); itemCopy.addActionListener(new CopyAction()); itemSave.addActionListener(new SaveAction()); popup.add(itemCopy); //popup.addSeparator(); popup.add(itemSave); } private class CopyAction implements ActionListener { @Override public void actionPerformed(final ActionEvent e) { Clipboard clipboard = getToolkit().getSystemClipboard(); Transferable transferable = new Transferable() { @Override public Object getTransferData(DataFlavor flavor) { if (isDataFlavorSupported(flavor)) { return getImage(); } return null; } @Override public DataFlavor[] getTransferDataFlavors() { return new DataFlavor[] { DataFlavor.imageFlavor }; } @Override public boolean isDataFlavorSupported(DataFlavor flavor) { return DataFlavor.imageFlavor.equals(flavor); } }; clipboard.setContents(transferable, GraphPanelChart.this); } } private class SaveAction implements ActionListener { @Override public void actionPerformed(final ActionEvent e) { JFileChooser chooser = savePath != null ? new JFileChooser(new File(savePath)) : new JFileChooser(); chooser.setFileFilter(new FileNameExtensionFilter("PNG Images", "png")); int returnVal = chooser.showSaveDialog(GraphPanelChart.this); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); if (!file.getAbsolutePath().toUpperCase().endsWith(".PNG")) { file = new File(file.getAbsolutePath() + ".png"); } savePath = file.getParent(); boolean doSave = true; if (file.exists()) { int choice = JOptionPane.showConfirmDialog(GraphPanelChart.this, "Do you want to overwrite " + file.getAbsolutePath() + "?", "Save Image as", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); doSave = (choice == JOptionPane.YES_OPTION); } if (doSave) { try { FileOutputStream fos = new FileOutputStream(file); ImageIO.write(getBufferedImage(), "png", fos); fos.flush(); fos.close(); } catch (IOException ex) { JOptionPane.showConfirmDialog(GraphPanelChart.this, "Impossible to write the image to the file:\n" + ex.getMessage(), "Save Image as", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE); } } } } } } diff --git a/src/kg/apc/jmeter/vizualizers/JSettingsPanel.java b/src/kg/apc/jmeter/vizualizers/JSettingsPanel.java index 4c5747e4..dd68b571 100644 --- a/src/kg/apc/jmeter/vizualizers/JSettingsPanel.java +++ b/src/kg/apc/jmeter/vizualizers/JSettingsPanel.java @@ -1,352 +1,352 @@ package kg.apc.jmeter.vizualizers; import javax.swing.ToolTipManager; import kg.apc.jmeter.charting.GraphPanelChart; /** * * @author Stéphane Hoblingre */ public class JSettingsPanel extends javax.swing.JPanel { private SettingsInterface parent = null; private int originalTooltipDisplayTime = 0; /** Creates new form JSettingsPanel */ public JSettingsPanel(SettingsInterface parent, boolean showTimelinePanel, boolean showGradientOption, boolean showCurrentXOption, boolean showFinalZeroingLinesOption, boolean showLimitPointOption) { initComponents(); this.parent = parent; jPanelTimeLine.setVisible(showTimelinePanel); jCheckBoxPaintGradient.setVisible(showGradientOption); jCheckBoxDrawCurrentX.setVisible(showCurrentXOption); jCheckBoxDrawFinalZeroingLines.setVisible(showFinalZeroingLinesOption); jCheckBoxMaxPoints.setVisible(showLimitPointOption); jComboBoxMaxPoints.setVisible(showLimitPointOption); jLabelMaxPoints.setVisible(showLimitPointOption); jLabelInfoMaxPoint.setVisible(showLimitPointOption); originalTooltipDisplayTime=ToolTipManager.sharedInstance().getDismissDelay(); //init default values from global config jCheckBoxPaintGradient.setSelected(parent.getGraphPanelChart().isSettingsDrawGradient()); jCheckBoxDrawCurrentX.setSelected(parent.getGraphPanelChart().isSettingsDrawCurrentX()); if(showFinalZeroingLinesOption) { jCheckBoxDrawFinalZeroingLines.setSelected(GraphPanelChart.isGlobalDrawFinalZeroingLines()); } } private int getValueFromString(String sValue) { int ret; try { ret = Integer.valueOf(sValue); if(ret <= 0) { ret = -1; } } catch (NumberFormatException ex) { ret = -1; } return ret; } public void setGranulationValue(int value) { jComboBoxGranulation.setSelectedItem(Integer.toString(value)); } /** 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; jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jPanel2 = new javax.swing.JPanel(); jPanelTimeLine = new javax.swing.JPanel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jPanel4 = new javax.swing.JPanel(); jComboBoxGranulation = new javax.swing.JComboBox(); jLabelInfoGrpValues = new javax.swing.JLabel(); jPanel5 = new javax.swing.JPanel(); jCheckBoxPaintGradient = new javax.swing.JCheckBox(); jCheckBoxDrawFinalZeroingLines = new javax.swing.JCheckBox(); jPanel6 = new javax.swing.JPanel(); jCheckBoxDrawCurrentX = new javax.swing.JCheckBox(); jCheckBoxMaxPoints = new javax.swing.JCheckBox(); jLabelMaxPoints = new javax.swing.JLabel(); jComboBoxMaxPoints = new javax.swing.JComboBox(); jLabelInfoMaxPoint = new javax.swing.JLabel(); setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED)); setLayout(new java.awt.BorderLayout()); jPanel1.setLayout(new java.awt.GridLayout(1, 0)); jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/kg/apc/jmeter/vizualizers/logoSimple.png"))); // NOI18N jPanel1.add(jLabel1); add(jPanel1, java.awt.BorderLayout.PAGE_END); jPanel2.setLayout(new java.awt.GridBagLayout()); jPanelTimeLine.setBorder(javax.swing.BorderFactory.createTitledBorder("Timeline Settings")); jPanelTimeLine.setLayout(new java.awt.GridBagLayout()); jLabel2.setText("Group values for:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(0, 2, 0, 2); jPanelTimeLine.add(jLabel2, gridBagConstraints); jLabel3.setText("ms"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(0, 2, 0, 2); jPanelTimeLine.add(jLabel3, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.gridwidth = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; jPanelTimeLine.add(jPanel4, gridBagConstraints); jComboBoxGranulation.setEditable(true); - jComboBoxGranulation.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "500", "1000", "2000", "5000", "10000", "30000", "60000" })); + jComboBoxGranulation.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "100", "500", "1000", "2000", "5000", "10000", "30000", "60000" })); jComboBoxGranulation.setPreferredSize(new java.awt.Dimension(80, 20)); jComboBoxGranulation.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jComboBoxGranulationActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(0, 2, 0, 2); jPanelTimeLine.add(jComboBoxGranulation, gridBagConstraints); jLabelInfoGrpValues.setIcon(new javax.swing.ImageIcon(getClass().getResource("/kg/apc/jmeter/vizualizers/information.png"))); // NOI18N - jLabelInfoGrpValues.setToolTipText("<html>You can specify here the duration used internally<br>\nby the plugin to combine the values received during<br>\nthe test. This will result in <b>more readable graphs</b> and<br>\n<b>less resources needs</b>. It <b>cannot be undo</b>.<br>\nYou should only use values <b>greater than 500</b> for good results.<br>\nThis parameter is saved with the test plan."); + jLabelInfoGrpValues.setToolTipText("<html>You can specify here the duration used internally<br>\nby the plugin to combine the values received during<br>\nthe test. This will result in <b>more readable graphs</b> and<br>\n<b>less resources needs</b>. It <b>cannot be undo</b>.<br>\nYou can change the value during the test, but it is not<br>\nrecomended as it may produce inconsistant graphs.<br>\nThis parameter is saved with the test plan."); jLabelInfoGrpValues.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { infoLabelMouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { infoLabelMouseExited(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 2, 0, 2); jPanelTimeLine.add(jLabelInfoGrpValues, 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; jPanel2.add(jPanelTimeLine, gridBagConstraints); jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder("Rendering Options")); jPanel5.setLayout(new java.awt.GridBagLayout()); jCheckBoxPaintGradient.setText("Paint gradient"); jCheckBoxPaintGradient.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jCheckBoxPaintGradientActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; jPanel5.add(jCheckBoxPaintGradient, gridBagConstraints); jCheckBoxDrawFinalZeroingLines.setText("Draw final zeroing lines"); jCheckBoxDrawFinalZeroingLines.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jCheckBoxDrawFinalZeroingLinesActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; jPanel5.add(jCheckBoxDrawFinalZeroingLines, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.gridwidth = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; jPanel5.add(jPanel6, gridBagConstraints); jCheckBoxDrawCurrentX.setText("Draw current X line"); jCheckBoxDrawCurrentX.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jCheckBoxDrawCurrentXActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; jPanel5.add(jCheckBoxDrawCurrentX, gridBagConstraints); jCheckBoxMaxPoints.setText("Limit number of points in row to"); jCheckBoxMaxPoints.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jCheckBoxMaxPointsActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; jPanel5.add(jCheckBoxMaxPoints, gridBagConstraints); jLabelMaxPoints.setText("points"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 3; gridBagConstraints.insets = new java.awt.Insets(0, 2, 0, 2); jPanel5.add(jLabelMaxPoints, gridBagConstraints); jComboBoxMaxPoints.setEditable(true); jComboBoxMaxPoints.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "20", "50", "100", "150", "200" })); jComboBoxMaxPoints.setSelectedIndex(1); jComboBoxMaxPoints.setPreferredSize(new java.awt.Dimension(50, 20)); jComboBoxMaxPoints.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jComboBoxMaxPointsActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 3; gridBagConstraints.insets = new java.awt.Insets(0, 2, 0, 2); jPanel5.add(jComboBoxMaxPoints, gridBagConstraints); jLabelInfoMaxPoint.setIcon(new javax.swing.ImageIcon(getClass().getResource("/kg/apc/jmeter/vizualizers/information.png"))); // NOI18N - jLabelInfoMaxPoint.setToolTipText("<html>This option will <b>dynamically</b> adjust the graph<br>\nrendering so it is <b>more readable</b>. It <b>can be undo</b>.<br>\nThis parameter is not saved with the test plan.<br>"); + jLabelInfoMaxPoint.setToolTipText("<html>This option will <b>dynamically</b> adjust the graph<br>\nrendering so it is <b>more readable</b>. It <b>can be undo</b>.<br>\nYou can change the value during the test.<br>\nThis parameter is not saved with the test plan.<br>"); jLabelInfoMaxPoint.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { infoLabelMouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { infoLabelMouseExited(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 2, 0, 2); jPanel5.add(jLabelInfoMaxPoint, 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; jPanel2.add(jPanel5, gridBagConstraints); add(jPanel2, java.awt.BorderLayout.CENTER); }// </editor-fold>//GEN-END:initComponents private void jComboBoxGranulationActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jComboBoxGranulationActionPerformed {//GEN-HEADEREND:event_jComboBoxGranulationActionPerformed //notify parent if value changed and valid int newValue = getValueFromString((String)jComboBoxGranulation.getSelectedItem()); if(newValue != -1 && parent.getGranulation() != newValue) { parent.setGranulation(newValue); } }//GEN-LAST:event_jComboBoxGranulationActionPerformed private void jCheckBoxPaintGradientActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jCheckBoxPaintGradientActionPerformed {//GEN-HEADEREND:event_jCheckBoxPaintGradientActionPerformed parent.getGraphPanelChart().setSettingsDrawGradient(jCheckBoxPaintGradient.isSelected()); }//GEN-LAST:event_jCheckBoxPaintGradientActionPerformed private void jCheckBoxDrawFinalZeroingLinesActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jCheckBoxDrawFinalZeroingLinesActionPerformed {//GEN-HEADEREND:event_jCheckBoxDrawFinalZeroingLinesActionPerformed parent.getGraphPanelChart().setSettingsDrawFinalZeroingLines(jCheckBoxDrawFinalZeroingLines.isSelected()); }//GEN-LAST:event_jCheckBoxDrawFinalZeroingLinesActionPerformed private void jCheckBoxDrawCurrentXActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jCheckBoxDrawCurrentXActionPerformed {//GEN-HEADEREND:event_jCheckBoxDrawCurrentXActionPerformed parent.getGraphPanelChart().setSettingsDrawCurrentX(jCheckBoxDrawCurrentX.isSelected()); }//GEN-LAST:event_jCheckBoxDrawCurrentXActionPerformed private void jCheckBoxMaxPointsActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jCheckBoxMaxPointsActionPerformed {//GEN-HEADEREND:event_jCheckBoxMaxPointsActionPerformed if(jCheckBoxMaxPoints.isSelected()) { parent.getGraphPanelChart().setMaxPoints(getValueFromString((String)jComboBoxMaxPoints.getSelectedItem())); } else { parent.getGraphPanelChart().setMaxPoints(-1); } }//GEN-LAST:event_jCheckBoxMaxPointsActionPerformed private void jComboBoxMaxPointsActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jComboBoxMaxPointsActionPerformed {//GEN-HEADEREND:event_jComboBoxMaxPointsActionPerformed if(jCheckBoxMaxPoints.isSelected()) { parent.getGraphPanelChart().setMaxPoints(getValueFromString((String)jComboBoxMaxPoints.getSelectedItem())); } }//GEN-LAST:event_jComboBoxMaxPointsActionPerformed private void infoLabelMouseEntered(java.awt.event.MouseEvent evt)//GEN-FIRST:event_infoLabelMouseEntered {//GEN-HEADEREND:event_infoLabelMouseEntered //increase tooltip display duration ToolTipManager.sharedInstance().setDismissDelay(60000); }//GEN-LAST:event_infoLabelMouseEntered private void infoLabelMouseExited(java.awt.event.MouseEvent evt)//GEN-FIRST:event_infoLabelMouseExited {//GEN-HEADEREND:event_infoLabelMouseExited ToolTipManager.sharedInstance().setDismissDelay(originalTooltipDisplayTime); }//GEN-LAST:event_infoLabelMouseExited // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JCheckBox jCheckBoxDrawCurrentX; private javax.swing.JCheckBox jCheckBoxDrawFinalZeroingLines; private javax.swing.JCheckBox jCheckBoxMaxPoints; private javax.swing.JCheckBox jCheckBoxPaintGradient; private javax.swing.JComboBox jComboBoxGranulation; private javax.swing.JComboBox jComboBoxMaxPoints; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabelInfoGrpValues; private javax.swing.JLabel jLabelInfoMaxPoint; private javax.swing.JLabel jLabelMaxPoints; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JPanel jPanel6; private javax.swing.JPanel jPanelTimeLine; // End of variables declaration//GEN-END:variables } diff --git a/src/kg/apc/jmeter/vizualizers/ResponseTimesDistributionGui.java b/src/kg/apc/jmeter/vizualizers/ResponseTimesDistributionGui.java index 61614f5c..963c73b9 100644 --- a/src/kg/apc/jmeter/vizualizers/ResponseTimesDistributionGui.java +++ b/src/kg/apc/jmeter/vizualizers/ResponseTimesDistributionGui.java @@ -1,80 +1,81 @@ package kg.apc.jmeter.vizualizers; import kg.apc.jmeter.charting.AbstractGraphRow; import kg.apc.jmeter.charting.GraphRowSumValues; import org.apache.jmeter.samplers.SampleResult; /** * * @author apc */ public class ResponseTimesDistributionGui extends AbstractGraphPanelVisualizer { /** * */ public ResponseTimesDistributionGui() { super(); + setGranulation(100); //graphPanel.getGraphObject().setChartType(GraphPanelChart.CHART_PERCENTAGE); } private synchronized AbstractGraphRow getNewRow(String label) { AbstractGraphRow row = null; if (!model.containsKey(label)) { row = new GraphRowSumValues(false); row.setLabel(label); row.setColor(colors.getNextColor()); row.setDrawLine(false); row.setDrawBar(true); row.setMarkerSize(AbstractGraphRow.MARKER_SIZE_NONE); model.put(label, row); graphPanel.addRow(row); } else { row = model.get(label); } return row; } private void addThreadGroupRecord(String threadGroupName, long time, int granulation) { AbstractGraphRow row = model.get(threadGroupName); if (row == null) { row = getNewRow(threadGroupName); } row.add(time, 1); row.setGranulationValue(granulation); } public String getLabelResource() { return this.getClass().getSimpleName(); } @Override public String getStaticLabel() { return "Response Times Distribution"; } public void add(SampleResult res) { int granulation = getGranulation(); addThreadGroupRecord(res.getSampleLabel(), res.getTime() - res.getTime() % granulation, granulation); updateGui(null); } @Override protected JSettingsPanel getSettingsPanel() { - return new JSettingsPanel(this, true, true, true, true, true); + return new JSettingsPanel(this, true, true, false, false, false); } }
false
false
null
null
diff --git a/src/main/java/com/pholser/util/properties/PropertyBinder.java b/src/main/java/com/pholser/util/properties/PropertyBinder.java index 949fc80..9c86dac 100644 --- a/src/main/java/com/pholser/util/properties/PropertyBinder.java +++ b/src/main/java/com/pholser/util/properties/PropertyBinder.java @@ -1,166 +1,166 @@ /* The MIT License Copyright (c) 2009-2010 Paul R. Holser, Jr. 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.pholser.util.properties; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import com.pholser.util.properties.internal.SchemaValidator; import com.pholser.util.properties.internal.ValidatedSchema; import static org.apache.commons.io.IOUtils.*; /** * Creates instances of proxies that provide typed access to values in properties files via the <acronym * title="Proxied Interfaces Configured with Annotations">PICA</acronym> technique.</p> * * Inspired by <a href="http://lemnik.wordpress.com/2007/03/28/code-at-runtime-in-java-56/">this blog entry</a>. * * @param <T> the type of bound property accessor objects this binder creates * @author <a href="http://www.pholser.com">Paul Holser</a> */ public final class PropertyBinder<T> { private final ValidatedSchema<T> validatedSchema; private PropertyBinder(Class<T> schema) { validatedSchema = new SchemaValidator().validate(schema); } /** * Creates a new properties file accessor from the given PICA schema. * * The PICA schema is validated to ensure that there are no inconsistencies. Here are the constraints placed * on the PICA schema: * * <ol> * <li>Must be an interface with no superinterfaces.</li> * * <li>Every method maps to a properties file key. It can be marked with {@link BoundProperty} to indicate * the properties file key; if not, the key is the fully qualified name of the PICA interface + '.' + the * method's name.</li> * * <li>It is not required that the method accept zero arguments, but be advised that any arguments the * method declares are ignored.</li> * * <li>The only aggregate return types supported are arrays and {@link java.util.List}.</li> * * <li>The {@link ValuesSeparatedBy} annotation can be applied only to methods with an aggregate return * type, and must specify a well-formed {@linkplain java.util.regex.Pattern regular expression} as a * separator.</li> * * <li>A method's return type must be a <dfn>value type</dfn>, an array of value types, or a List of value * types. A value type is any primitive type (except {@code void}), primitive wrapper type (except * {@link Void}), or type which possesses either: * * <ul> * <li>a {@code public static} method called {@code valueOf} which takes one argument, of type * {@link String}, and whose return type is the type itself</li> * * <li>a {@code public} constructor which takes one argument, of type {@link String}</li> * </ul> * * If a value type has both of these, the {@code valueOf} method takes priority over the constructor. Note * that {@code enum}s have a {@code valueOf} method.</li> * * <li>A List type may be a raw List or a {@code List<?>}. The underlying values are {@code String}s in such * cases.</li> * * <li>If the method specifies a default value via {@link ValuesSeparatedBy}, that value must be convertible * to the return type of the method.</li> * </ol> * * @param <U> the type of bound property accessor objects this binder creates * @param schema the PICA type used to configure the accessor and provide access to properties * @return a new property binder that binds instances of {@code} schema to properties objects * @throws NullPointerException if {@code schema} is {@code null} * @throws IllegalArgumentException if {@code schema}'s configuration is invalid in any way */ public static <U> PropertyBinder<U> forType(Class<U> schema) { return new PropertyBinder<U>(schema); } /** - * Binds the properties purported to be in the given input stream to an instance of this binder's PICA.> + * Binds the properties purported to be in the given input stream to an instance of this binder's PICA. * * @see #bind(File) * @param propertyInput an input stream containing properties to be bound * @return a PICA instance bound to the properties * @throws IOException if there is a problem reading from the input stream * @throws NullPointerException if {@code propertyInput} is {@code null} */ public T bind(InputStream propertyInput) throws IOException { return bind(loadProperties(propertyInput)); } /** * Binds the properties purported to be in the given file to an instance of this binder's PICA. * * After binding, invoking a PICA method returns the value of the property it represents if that property is * present; else the value given by the method's {@link DefaultsTo} marker if present; else {@code null} for * scalar types, a zero-length array for array types, and an {@linkplain java.util.Collection#isEmpty() * empty list} for list types. If the PICA method returns a primitive type and neither a property nor its * default is present, the PICA method will raise {@link NullPointerException}. * * @see #bind(InputStream) * @param propertiesFile a file containing properties to be bound * @return a PICA instance bound to the properties * @throws IOException if there is a problem reading from the file * @throws NullPointerException if {@code propertiesFile} is {@code null} */ public T bind(File propertiesFile) throws IOException { FileInputStream propertyInput = null; try { propertyInput = new FileInputStream(propertiesFile); return bind(propertyInput); } finally { closeQuietly(propertyInput); } } T bind(Properties properties) { Properties copy = (Properties) properties.clone(); return validatedSchema.evaluate(copy); } /** * Gives a typed accessor for {@linkplain System#getProperties() system properties}. * * @return a typed system property accessor */ public static SystemProperties getSystemProperties() { return PropertyBinder.forType(SystemProperties.class).bind(System.getProperties()); } private static Properties loadProperties(InputStream propertyInput) throws IOException { SubstitutableProperties properties = new SubstitutableProperties(); properties.load(propertyInput); return properties; } }
true
false
null
null
diff --git a/source/de/anomic/plasma/plasmaSwitchboardQueue.java b/source/de/anomic/plasma/plasmaSwitchboardQueue.java index 0f33d875e..b664f745d 100644 --- a/source/de/anomic/plasma/plasmaSwitchboardQueue.java +++ b/source/de/anomic/plasma/plasmaSwitchboardQueue.java @@ -1,477 +1,477 @@ // plasmaSwitchboardQueueEntry.java // -------------------------------- // part of YaCy // (C) by Michael Peter Christen; [email protected] // first published on http://www.anomic.de // Frankfurt, Germany, 2005 // // $LastChangedDate$ // $LastChangedRevision$ // $LastChangedBy$ // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Using this software in any meaning (reading, learning, copying, compiling, // running) means that you agree that the Author(s) is (are) not responsible // for cost, loss of data or any harm that may be caused directly or indirectly // by usage of this softare or this documentation. The usage of this software // is on your own risk. The installation and usage (starting/running) of this // software may allow other people or application to access your computer and // any attached devices and is highly dependent on the configuration of the // software which must be done by the user of the software; the author(s) is // (are) also not responsible for proper configuration and usage of the // software, even if provoked by documentation provided together with // the software. // // Any changes to this file according to the GPL as documented in the file // gpl.txt aside this file in the shipment you received can be done to the // lines that follows this copyright notice here, but changes must not be // done inside the copyright notive above. A re-distribution must contain // the intact and unchanged copyright notice. // Contributions and changes to the program code must be marked as such. package de.anomic.plasma; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Date; import de.anomic.index.indexURL; import de.anomic.kelondro.kelondroBase64Order; import de.anomic.kelondro.kelondroException; import de.anomic.kelondro.kelondroRow; import de.anomic.kelondro.kelondroStack; import de.anomic.net.URL; import de.anomic.plasma.cache.IResourceInfo; import de.anomic.server.logging.serverLog; import de.anomic.yacy.yacySeedDB; public class plasmaSwitchboardQueue { private kelondroStack sbQueueStack; private plasmaCrawlProfile profiles; plasmaHTCache htCache; private plasmaCrawlLURL lurls; private File sbQueueStackPath; public plasmaSwitchboardQueue(plasmaHTCache htCache, plasmaCrawlLURL lurls, File sbQueueStackPath, plasmaCrawlProfile profiles) { this.sbQueueStackPath = sbQueueStackPath; this.profiles = profiles; this.htCache = htCache; this.lurls = lurls; initQueueStack(); } private void initQueueStack() { kelondroRow rowdef = new kelondroRow( "String url-" + indexURL.urlStringLength + ", " + // the url "String refhash-" + indexURL.urlHashLength + ", " + // the url's referrer hash "Cardinal modifiedsince-11" + " {b64e}, " + // from ifModifiedSince "byte[] flags-1" + ", " + // flags "String initiator-" + yacySeedDB.commonHashLength + ", " + // the crawling initiator "Cardinal depth-" + indexURL.urlCrawlDepthLength + " {b64e}, " + // the prefetch depth so far, starts at 0 "String profile-" + indexURL.urlCrawlProfileHandleLength + ", " + // the name of the prefetch profile handle "String urldescr-" + indexURL.urlDescrLength); // sbQueueStack = kelondroStack.open(sbQueueStackPath, rowdef); } private void resetQueueStack() { try {sbQueueStack.close();} catch (Exception e) {} if (sbQueueStackPath.exists()) sbQueueStackPath.delete(); initQueueStack(); } public int size() { return sbQueueStack.size(); } public void push(Entry entry) throws IOException { sbQueueStack.push(sbQueueStack.row().newEntry(new byte[][]{ entry.url.toString().getBytes(), (entry.referrerHash == null) ? indexURL.dummyHash.getBytes() : entry.referrerHash.getBytes(), kelondroBase64Order.enhancedCoder.encodeLong((entry.ifModifiedSince == null) ? 0 : entry.ifModifiedSince.getTime(), 11).getBytes(), new byte[]{entry.flags}, (entry.initiator == null) ? indexURL.dummyHash.getBytes() : entry.initiator.getBytes(), kelondroBase64Order.enhancedCoder.encodeLong((long) entry.depth, indexURL.urlCrawlDepthLength).getBytes(), (entry.profileHandle == null) ? indexURL.dummyHash.getBytes() : entry.profileHandle.getBytes(), (entry.anchorName == null) ? "-".getBytes() : entry.anchorName.getBytes() })); } public Entry pop() throws IOException { if (sbQueueStack.size() == 0) return null; kelondroRow.Entry b = sbQueueStack.pot(); if (b == null) return null; return new Entry(b); } public Entry remove(int index) throws IOException { if (sbQueueStack.size() == 0) return null; return new Entry(sbQueueStack.pot(index)); } public Entry get(int index) throws IOException { if ((index < 0) || (index >= sbQueueStack.size())) throw new ArrayIndexOutOfBoundsException(); return new Entry(sbQueueStack.bot(index)); } public ArrayList list() throws IOException { return list(0); } public ArrayList list(int index) throws IOException { if ((index == 0) && (sbQueueStack.size() == 0)) return new ArrayList(0); if ((index < 0) || (index >= sbQueueStack.size())) throw new ArrayIndexOutOfBoundsException(); try { ArrayList list = sbQueueStack.botList(index); kelondroRow.Entry entry; for (int i = 0; i < list.size(); i++) { entry = (kelondroRow.Entry) list.get(i); list.set(i, (entry == null) ? null : new Entry(entry)); } return list; } catch (kelondroException e) { resetQueueStack(); return new ArrayList(); } } public void clear() throws IOException { sbQueueStack.clear(); } public void close() { if (sbQueueStack != null) try { sbQueueStack.close(); } catch (IOException e) { } sbQueueStack = null; } protected void finalize() throws Throwable { try { close(); } catch (Exception e) { throw new IOException("plasmaSwitchboardQueue.finalize()" + e.getMessage()); } super.finalize(); } public Entry newEntry(URL url, String referrer, Date ifModifiedSince, boolean requestWithCookie, String initiator, int depth, String profilehandle, String anchorName) { return new Entry(url, referrer, ifModifiedSince, requestWithCookie, initiator, depth, profilehandle, anchorName); } public class Entry { private URL url; // plasmaURL.urlStringLength private String referrerHash; // plasmaURL.urlHashLength private Date ifModifiedSince; // 6 private byte flags; // 1 private String initiator; // yacySeedDB.commonHashLength private int depth; // plasmaURL.urlCrawlDepthLength private String profileHandle; // plasmaURL.urlCrawlProfileHandleLength private String anchorName; // plasmaURL.urlDescrLength // computed values private plasmaCrawlProfile.entry profileEntry; private IResourceInfo contentInfo; private URL referrerURL; public Entry(URL url, String referrer, Date ifModifiedSince, boolean requestWithCookie, String initiator, int depth, String profileHandle, String anchorName) { this.url = url; this.referrerHash = referrer; this.ifModifiedSince = ifModifiedSince; this.flags = (requestWithCookie) ? (byte) 1 : (byte) 0; this.initiator = initiator; this.depth = depth; this.profileHandle = profileHandle; this.anchorName = (anchorName==null)?"":anchorName.trim(); this.profileEntry = null; this.contentInfo = null; this.referrerURL = null; } public Entry(kelondroRow.Entry row) { long ims = row.getColLong(2); byte flags = row.getColByte(3); try { this.url = new URL(row.getColString(0, "UTF-8")); } catch (MalformedURLException e) { this.url = null; } this.referrerHash = row.getColString(1, "UTF-8"); this.ifModifiedSince = (ims == 0) ? null : new Date(ims); this.flags = ((flags & 1) == 1) ? (byte) 1 : (byte) 0; this.initiator = row.getColString(4, "UTF-8"); this.depth = (int) row.getColLong(5); this.profileHandle = row.getColString(6, "UTF-8"); this.anchorName = row.getColString(7, "UTF-8"); this.profileEntry = null; this.contentInfo = null; this.referrerURL = null; } public Entry(byte[][] row) throws IOException { long ims = (row[2] == null) ? 0 : kelondroBase64Order.enhancedCoder.decodeLong(new String(row[2], "UTF-8")); byte flags = (row[3] == null) ? 0 : row[3][0]; try { this.url = new URL(new String(row[0], "UTF-8")); } catch (MalformedURLException e) { this.url = null; } this.referrerHash = (row[1] == null) ? null : new String(row[1], "UTF-8"); this.ifModifiedSince = (ims == 0) ? null : new Date(ims); this.flags = ((flags & 1) == 1) ? (byte) 1 : (byte) 0; this.initiator = (row[4] == null) ? null : new String(row[4], "UTF-8"); this.depth = (int) kelondroBase64Order.enhancedCoder.decodeLong(new String(row[5], "UTF-8")); this.profileHandle = new String(row[6], "UTF-8"); this.anchorName = (row[7] == null) ? null : (new String(row[7], "UTF-8")).trim(); this.profileEntry = null; this.contentInfo = null; this.referrerURL = null; } public String toString() { StringBuffer str = new StringBuffer(); str.append("url: ") .append(this.url==null ? "null" : this.url.toString()).append(" | ") .append("referrer: ") .append(this.referrerHash==null?"null":this.referrerHash).append(" | ") .append("ifModifiedSince: ").append(this.ifModifiedSince==null?"null":this.ifModifiedSince.toString()).append(" | ") .append("flags: ") .append(Byte.toString(this.flags)).append(" | ") .append("initiator: ") .append(this.initiator==null ? "null" : this.initiator).append(" | ") .append("depth: ") .append(Integer.toString(this.depth)).append(" | ") .append("profile: ") .append(this.profileHandle==null?"null":this.profileHandle).append(" | ") .append("anchorName: ") .append(this.anchorName==null?"null":this.anchorName); return str.toString(); } public URL url() { return url; } public String normalizedURLString() { return url.toNormalform(); } public String urlHash() { return indexURL.urlHash(url); } public boolean requestedWithCookie() { return (flags & 1) == 1; } public File cacheFile() { return htCache.getCachePath(url); } public boolean proxy() { return (initiator == null) || (initiator.equals(indexURL.dummyHash)); } public String initiator() { return initiator; } public int depth() { return depth; } public long size() { if (cacheFile().exists()) return cacheFile().length(); else return 0; } public plasmaCrawlProfile.entry profile() { if (profileEntry == null) profileEntry = profiles.getEntry(profileHandle); return profileEntry; } private IResourceInfo getCachedObjectInfo() { if (this.contentInfo == null) try { this.contentInfo = plasmaSwitchboardQueue.this.htCache.loadResourceInfo(this.url); } catch (Exception e) { serverLog.logSevere("PLASMA", "responseHeader: failed to get header", e); return null; } return this.contentInfo; } public String getMimeType() { IResourceInfo info = this.getCachedObjectInfo(); return (info == null) ? null : info.getMimeType(); } public Date getModificationDate() { IResourceInfo info = this.getCachedObjectInfo(); return (info == null) ? new Date() : info.getModificationDate(); } public URL referrerURL() { if (referrerURL == null) { if ((referrerHash == null) || (referrerHash.equals(indexURL.dummyHash))) return null; try { - referrerURL = lurls.load(referrerHash, null).url(); + plasmaCrawlLURL.Entry entry = lurls.load(referrerHash, null); + if (entry == null) referrerURL = null; else referrerURL = entry.url(); } catch (IOException e) { referrerURL = null; - return null; } } return referrerURL; } public String referrerHash() { return referrerHash; } public String anchorName() { return anchorName; } /** * decide upon header information if a specific file should be indexed * this method returns null if the answer is 'YES'! * if the answer is 'NO' (do not index), it returns a string with the reason * to reject the crawling demand in clear text * * This function is used by plasmaSwitchboard#processResourceStack */ public final String shallIndexCacheForProxy() { if (profile() == null) { return "shallIndexCacheForProxy: profile() is null !"; } // check profile if (!profile().localIndexing()) { return "Indexing_Not_Allowed"; } String nURL = normalizedURLString(); // -CGI access in request // CGI access makes the page very individual, and therefore not usable in caches if (!profile().crawlingQ()) { if (plasmaHTCache.isPOST(nURL)) { return "Dynamic_(POST)"; } if (plasmaHTCache.isCGI(nURL)) { return "Dynamic_(CGI)"; } } // -authorization cases in request // we checked that in shallStoreCache // -ranges in request // we checked that in shallStoreCache // a picture cannot be indexed if (plasmaHTCache.noIndexingURL(nURL)) { return "Media_Content_(forbidden)"; } // -cookies in request // unfortunately, we cannot index pages which have been requested with a cookie // because the returned content may be special for the client if (requestedWithCookie()) { // System.out.println("***not indexed because cookie"); return "Dynamic_(Requested_With_Cookie)"; } if (getCachedObjectInfo() != null) { return this.getCachedObjectInfo().shallIndexCacheForProxy(); } return null; } /** * decide upon header information if a specific file should be indexed * this method returns null if the answer is 'YES'! * if the answer is 'NO' (do not index), it returns a string with the reason * to reject the crawling demand in clear text * * This function is used by plasmaSwitchboard#processResourceStack */ public final String shallIndexCacheForCrawler() { if (profile() == null) { return "shallIndexCacheForCrawler: profile() is null !"; } // check profile if (!profile().localIndexing()) { return "Indexing_Not_Allowed"; } final String nURL = normalizedURLString(); // -CGI access in request // CGI access makes the page very individual, and therefore not usable in caches if (!profile().crawlingQ()) { if (plasmaHTCache.isPOST(nURL)) { return "Dynamic_(POST)"; } if (plasmaHTCache.isCGI(nURL)) { return "Dynamic_(CGI)"; } } // -authorization cases in request // we checked that in shallStoreCache // -ranges in request // we checked that in shallStoreCache // a picture cannot be indexed if (getCachedObjectInfo() != null) { String status = this.getCachedObjectInfo().shallIndexCacheForProxy(); if (status != null) return status; } if (plasmaHTCache.noIndexingURL(nURL)) { return "Media_Content_(forbidden)"; } // -if-modified-since in request // if the page is fresh at the very moment we can index it // -> this does not apply for the crawler // -cookies in request // unfortunately, we cannot index pages which have been requested with a cookie // because the returned content may be special for the client // -> this does not apply for a crawler // -set-cookie in response // the set-cookie from the server does not indicate that the content is special // thus we do not care about it here for indexing // -> this does not apply for a crawler // -pragma in cached response // -> in the crawler we ignore this // look for freshnes information // -expires in cached response // the expires value gives us a very easy hint when the cache is stale // sometimes, the expires date is set to the past to prevent that a page is cached // we use that information to see if we should index it // -> this does not apply for a crawler // -lastModified in cached response // this information is too weak to use it to prevent indexing // even if we can apply a TTL heuristic for cache usage // -cache-control in cached response // the cache-control has many value options. // -> in the crawler we ignore this return null; } } // class Entry } \ No newline at end of file
false
false
null
null
diff --git a/docs/src/main/java/org/geotools/cql/DataExamples.java b/docs/src/main/java/org/geotools/cql/DataExamples.java index 6d5338da1..52d3124f3 100644 --- a/docs/src/main/java/org/geotools/cql/DataExamples.java +++ b/docs/src/main/java/org/geotools/cql/DataExamples.java @@ -1,95 +1,112 @@ /** * */ package org.geotools.cql; +import java.io.IOException; import java.text.SimpleDateFormat; +import org.apache.commons.io.FileUtils; import org.geotools.data.DataUtilities; import org.geotools.feature.simple.SimpleFeatureBuilder; import org.geotools.geometry.jts.JTSFactoryFinder; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.GeometryFactory; import com.vividsolutions.jts.geom.MultiPolygon; import com.vividsolutions.jts.geom.Point; -import com.vividsolutions.jts.geom.Polygon; import com.vividsolutions.jts.io.WKTReader; /** * This utility class provide the data required by the CQL/ECQL examples. * * @author Mauricio Pazos * */ final class DataExamples extends ECQLExamples { private DataExamples(){ // utility class } /** * Creates a feature that represent New York city * @return a Feature * @throws Exception */ static public SimpleFeature createCity() throws Exception { final SimpleFeatureType type = DataUtilities.createType("Location", "geometry:Point:srid=4326," + "cityName:String," + "over65YearsOld:Double," + "under18YearsOld:Double," + "population:Integer," + "lastEarthQuake:Date"); SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(type); GeometryFactory geometryFactory = JTSFactoryFinder .getGeometryFactory(null); Point point = geometryFactory.createPoint(new Coordinate(-17.2053, 11.9517)); featureBuilder.add(point); featureBuilder.add("New York"); featureBuilder.add(22.6); featureBuilder.add(13.4); featureBuilder.add(19541453); SimpleDateFormat dateFormatter = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss'Z'"); featureBuilder.add(dateFormatter.parse("1737-11-30T01:30:00Z")); SimpleFeature feature = featureBuilder.buildFeature(null); return feature; } public static SimpleFeature createCountry() throws Exception { final SimpleFeatureType type = DataUtilities.createType("Location", "geometry:Polygon:srid=4326," + "countryName:String," + "population:Integer" ); SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(type); WKTReader reader = new WKTReader(); - MultiPolygon geometry = (MultiPolygon) reader.read(usaGeomety()); + MultiPolygon geometry = (MultiPolygon) reader.read(usaGeometry()); featureBuilder.add(geometry); featureBuilder.add("USA"); featureBuilder.add(307006550); SimpleFeature feature = featureBuilder.buildFeature(null); return feature; } - - static private String usaGeomety(){ - return "MULTIPOLYGON(((-134.975006 58.645828,-134.921387 58.687767,-134.930695 58.777351,-134.951111 58.815128,-135.000305 58.805550,-135.018616 58.777912,-135.027435 58.742146,-135.059723 58.752632,-135.145432 58.843117,-135.131210 58.881416,-135.233063 59.128326,-135.283340 59.203465,-135.315002 59.221657,-135.359650 59.261524,-135.356064 59.330379,-135.347549 59.366879,-135.335144 59.394836,-135.325409 59.453049,-135.347839 59.464157,-135.398743 59.368076,-135.459717 59.290825,-135.428619 59.256943,-135.360260 59.209438,-135.343887 59.189018,-135.303391 59.092838,-135.365952 59.126877,-135.384323 59.157768,-135.394333 59.180130,-135.415558 59.199020,-135.468597 59.218880,-135.488312 59.223877,-135.546677 59.225334,-135.445694 59.128605,-135.396347 59.070698,-135.390152 58.961658,-135.326111 58.866661,-135.312500 58.848328,-135.244629 58.721378,-135.188049 58.662491,-135.169739 58.645828,-135.185272 58.622490,-135.180557 58.560688,-135.164459 58.543747,-135.091675 58.436653,-135.072784 58.397217,-135.049438 58.340546,-135.050766 58.304577,-135.085541 58.233047,-135.156952 58.207214,-135.274872 58.233742,-135.321243 58.249718,-135.344147 58.264999,-135.368317 58.292221,-135.402710 58.346725,-135.407654 58.382214,-135.470901 58.471447,-135.509583 58.475197,-135.609711 58.420273,-135.755280 58.395546,-135.910355 58.381104,-135.887512 58.451103,-135.847626 58.467907,-135.836533 58.538189,-135.871643 58.601936,-135.888916 58.612495,-135.929993 58.656097,-136.065689 58.818325,-135.945114 58.861046,-135.851379 58.876656,-135.765945 58.895962,-135.803757 58.909019,-135.833069 58.910271,-135.927536 58.901852,-135.956116 58.889435,-136.045837 58.891106,-136.069122 58.944660,-136.087448 58.984665,-136.100555 59.011383,-136.143204 59.031799,-136.164108 59.027424,-136.143890 59.015549,-136.108276 58.929329,-136.094437 58.862492,-136.103607 58.830547,-136.129852 58.778187,-136.167099 58.754719,-136.236511 58.751728,-136.469025 58.829578,-136.580841 58.915825,-136.655563 58.966240,-136.683899 58.912209,-136.766968 58.941658,-136.883759 58.991520,-137.038620 59.067909,-137.064301 59.061867,-137.050827 59.035202,-136.977478 58.988884,-137.006546 58.931297,-137.040695 58.906033,-137.114014 58.846798,-137.118591 58.822704,-137.045837 58.861107,-137.028625 58.873878,-136.986618 58.887882,-136.908051 58.888885,-136.734985 58.868050,-136.578049 58.839436,-136.558624 58.832214,-136.538055 58.823051,-136.504944 58.788795,-136.548187 58.772007,-136.567352 58.793953,-136.584167 58.808327,-136.635757 58.814297,-136.582214 58.769157,-136.490036 58.747158,-136.378601 58.719017,-136.342911 58.680336,-136.464157 58.614716,-136.488312 58.609718,-136.519241 58.610271,-136.484848 58.592907,-136.460541 58.594711,-136.376648 58.619987,-136.328888 58.641937,-136.287094 58.661797,-136.255569 58.649994,-136.189163 58.614857,-136.122498 58.564438,-136.080841 58.511665,-136.044464 58.427490,-136.028336 58.385273,-136.050842 58.360970,-136.082901 58.340267,-136.254456 58.307770,-136.278305 58.327179,-136.271942 58.357216,-136.302216 58.381378,-136.479431 58.415825,-136.536606 58.359020,-136.480545 58.338112,-136.480286 58.359436,-136.445694 58.368290,-136.412338 58.364769,-136.384445 58.350391,-136.354431 58.337494,-136.367355 58.298534,-136.495972 58.308601,-136.531952 58.333744,-136.582489 58.351105,-136.647781 58.334503,-136.629425 58.315689,-136.600815 58.303947,-136.560410 58.261799,-136.572784 58.239990,-136.598526 58.221172,-136.620270 58.216660,-136.658905 58.216518,-136.687363 58.226795,-136.704987 58.238045,-136.834717 58.356590,-136.861664 58.379852,-136.949982 58.396103,-136.990417 58.402351,-137.018341 58.402489,-137.056870 58.395618,-137.148071 58.415825,-137.265015 58.456100,-137.386414 58.506386,-137.526672 58.567772,-137.585541 58.593605,-137.574707 58.612495,-137.535004 58.625267,-137.442490 58.653046,-137.461121 58.670273,-137.491089 58.679298,-137.603058 58.648605,-137.675552 58.657490,-137.694458 58.677078,-137.749146 58.708046,-137.772934 58.719990,-137.833893 58.748047,-137.871170 58.764023,-137.910553 58.784996,-137.927505 58.805828,-137.917847 58.833813,-137.926392 58.861382,-137.945694 58.886940,-137.964996 58.904709,-138.021683 58.934853,-138.042511 58.945267,-138.179718 59.019440,-138.200287 59.029716,-138.389175 59.104023,-138.470825 59.110687,-138.515289 59.105270,-138.544998 59.105827,-138.574707 59.109993,-138.599533 59.123219,-138.553619 59.124710,-138.498322 59.119713,-138.439224 59.184643,-138.460266 59.192768,-138.523071 59.185547,-138.624420 59.166939,-138.651123 59.160820,-138.760010 59.196098,-138.792511 59.207771,-138.950836 59.263054,-138.978607 59.269440,-138.998871 59.273880,-139.080841 59.285828,-139.161957 59.303604,-139.195969 59.318466,-139.160568 59.324856,-139.230270 59.379021,-139.255280 59.377769,-139.290833 59.359299,-139.334991 59.358604,-139.404938 59.378437,-139.439972 59.391602,-139.409943 59.385941,-139.375671 59.376392,-139.333603 59.393429,-139.435822 59.424770,-139.513672 59.434772,-139.710541 59.495827,-139.730560 59.546387,-139.635010 59.580826,-139.590271 59.613884,-139.530853 59.676102,-139.524170 59.740410,-139.575974 59.789997,-139.609863 59.855270,-139.615128 59.893600,-139.481247 59.985058,-139.457489 59.983604,-139.435822 59.973602,-139.360809 59.913605,-139.316956 59.869987,-139.312393 59.715435,-139.329498 59.600201,-139.290009 59.572773,-139.262573 59.572979,-139.224426 59.616104,-139.259735 59.685265,-139.277817 59.743031,-139.270798 59.800823,-139.218216 59.831959,-139.183212 59.837292,-139.147552 59.839790,-139.048477 59.845268,-139.004883 59.837212,-138.983185 59.821243,-138.965698 59.809715,-138.937500 59.804993,-138.899734 59.805336,-138.986938 59.843048,-139.041382 59.857773,-139.126663 59.867661,-139.174088 59.868828,-139.202484 59.872742,-139.272797 59.894714,-139.360062 59.955547,-139.379166 59.981380,-139.398071 59.995274,-139.500000 60.033051,-139.541672 60.030548,-139.585815 60.003326,-139.681946 59.931664,-139.778076 59.858330,-139.919159 59.799721,-139.999146 59.780823,-140.086945 59.759163,-140.145569 59.742218,-140.231110 59.711102,-140.259460 59.706100,-140.310547 59.700272,-140.379700 59.698326,-140.403351 59.698044,-140.455841 59.701103,-140.612762 59.713882,-140.838898 59.739433,-140.877762 59.745827,-140.932770 59.763054,-141.012787 59.786942,-141.042511 59.793884,-141.210815 59.832771,-141.376648 59.866386,-141.395844 59.908882,-141.354706 59.913605,-141.273407 59.944431,-141.260162 59.973461,-141.256958 59.995968,-141.260559 60.018883,-141.281952 60.073883,-141.384857 60.137909,-141.413635 60.137497,-141.473770 60.112526,-141.455765 60.079231,-141.418823 60.064575,-141.380890 60.032215,-141.400574 60.018326,-141.425842 60.011108,-141.610535 59.963882,-141.640839 59.959435,-141.730957 59.953327,-141.845551 59.998745,-141.879425 60.009995,-141.898895 60.014717,-141.930573 60.020546,-141.978882 60.026382,-142.154724 60.042221,-142.536682 60.088882,-142.654999 60.103607,-142.717224 60.109993,-142.768341 60.110550,-142.821930 60.105270,-142.884460 60.097771,-142.915833 60.093880,-143.005859 60.079994,-143.045837 60.073883,-143.131927 60.065269,-143.164185 60.062210,-143.186676 60.060547,-143.215698 60.060688,-143.273346 60.061661,-143.320557 60.059990,-143.412781 60.054993,-143.671661 60.035828,-143.739441 60.026939,-143.786819 60.017357,-143.835281 60.001106,-143.868591 59.992352,-143.900574 59.991104,-143.932510 59.996658,-143.965561 60.008190,-144.006851 60.043049,-144.030853 60.062210,-144.154999 60.122215,-144.253632 60.190826,-144.340698 60.199436,-144.378220 60.185616,-144.445694 60.172630,-144.574158 60.185822,-144.620544 60.197769,-144.642151 60.213497,-144.655426 60.240479,-144.703461 60.278740,-144.791107 60.299721,-144.831116 60.300545,-144.872772 60.299992,-144.902802 60.285271,-144.920288 60.289436,-144.931534 60.297356,-144.914734 60.378876,-144.833069 60.517212,-144.753632 60.627487,-144.613739 60.680477,-144.611389 60.715546,-144.663055 60.708046,-144.687775 60.703602,-144.708618 60.696938,-144.753906 60.678047,-144.857208 60.618599,-144.959991 60.543884,-145.097000 60.437073,-145.230133 60.365410,-145.248764 60.357494,-145.288467 60.350689,-145.349426 60.352219,-145.375824 60.356800,-145.480270 60.395199,-145.496246 60.420616,-145.544464 60.439987,-145.653625 60.467491,-145.675293 60.470825,-145.723190 60.472073,-145.761963 60.468048,-145.859436 60.491661,-145.767380 60.539162,-145.739441 60.556938,-145.625366 60.667004,-145.658554 60.669365,-145.687927 60.653881,-145.717773 60.644997,-145.830551 60.623600,-145.865921 60.624828,-145.887787 60.675552,-145.999146 60.634995,-146.215286 60.632351,-146.244171 60.635967,-146.261612 60.654434,-146.155060 60.698990,-146.135223 60.705494,-146.103897 60.714489,-146.016876 60.745338,-146.038055 60.795689,-146.060699 60.785690,-146.141373 60.760353,-146.175644 60.742062,-146.426392 60.696655,-146.457764 60.692215,-146.493317 60.688324,-146.644028 60.694084,-146.689102 60.743397,-146.603333 60.761383,-146.527802 60.772491,-146.506134 60.775269,-146.465897 60.774364,-146.428894 60.774712,-146.254730 60.810272,-146.125259 60.845406,-146.148071 60.860691,-146.234848 60.890480,-146.261826 60.870407,-146.277802 60.853882,-146.310272 60.835270,-146.363312 60.820549,-146.393616 60.815269,-146.393204 60.839714,-146.432770 60.829163,-146.454987 60.819717,-146.477783 60.817497,-146.518906 60.817009,-146.549164 60.821381,-146.690704 60.878532,-146.729996 60.918186,-146.755432 60.952492,-146.640015 61.070549,-146.611160 61.080410,-146.425568 61.084991,-146.321930 61.084160,-146.295013 61.084160,-146.244019 61.088600,-146.272797 61.116936,-146.296814 61.129295,-146.412781 61.135826,-146.579300 61.131794,-146.601379 61.125408,-146.785828 61.042496,-146.846390 61.004440,-146.857346 60.985962,-146.880005 60.971378,-146.944031 60.944714,-146.969162 60.939991,-147.022858 60.956242,-146.988190 60.978951,-146.980194 61.000687,-147.048340 61.009720,-147.091949 61.011940,-147.208893 60.986938,-147.253952 60.934364,-147.366943 60.887772,-147.537003 60.917374,-147.541687 60.977768,-147.526123 61.033333,-147.510284 61.093048,-147.519180 61.151447,-147.550964 61.153183,-147.573334 61.139854,-147.616638 60.959991,-147.604431 60.895691,-147.668060 60.853050,-147.749420 60.837494,-147.787231 60.821663,-147.860413 60.831387,-147.892517 60.846382,-147.914520 60.889893,-147.959625 60.915363,-148.050278 60.947353,-147.924164 61.070995,-147.757782 61.184433,-147.715683 61.275406,-147.737762 61.274433,-147.759460 61.260826,-147.959167 61.116383,-147.995621 61.076382,-148.014587 61.052254,-148.040222 61.036880,-148.071518 61.017773,-148.120041 61.054214,-148.139389 61.079212,-148.188049 61.094711,-148.247772 61.092766,-148.275574 61.089298,-148.382492 61.064438,-148.404175 61.054436,-148.442291 60.988464,-148.417786 60.983047,-148.396393 60.986107,-148.374695 60.996101,-148.354431 61.006943,-148.325409 61.025478,-148.264038 61.055550,-148.242493 61.062210,-148.199432 61.068329,-148.163956 61.057018,-148.172638 61.017216,-148.304031 60.847908,-148.344574 60.812492,-148.373459 60.808464,-148.401672 60.822075,-148.434738 60.836800,-148.468323 60.839714,-148.601257 60.826942,-148.692368 60.788120,-148.671936 60.784164,-148.639999 60.788883,-148.597351 60.802078,-148.566956 60.807495,-148.459290 60.797489,-148.529358 60.782295,-148.586105 60.769302,-148.631104 60.750275,-148.648621 60.738045,-148.670563 60.714439,-148.700134 60.673882,-148.660278 60.671246,-148.584167 60.710129,-148.576462 60.733322,-148.495743 60.763298,-148.442001 60.769882,-148.394165 60.777771,-148.229721 60.765827,-148.252411 60.741833,-148.251648 60.702827,-148.204575 60.617489,-148.328323 60.536869,-148.399445 60.554993,-148.430832 60.578640,-148.481094 60.578117,-148.509186 60.566383,-148.608887 60.519714,-148.647247 60.497490,-148.680420 60.472767,-148.687149 60.451588,-148.673065 60.446938,-148.577789 60.496384,-148.549438 60.510277,-148.496948 60.529434,-148.448257 60.540413,-148.337769 60.506386,-148.285828 60.490273,-148.261139 60.483047,-148.235275 60.512218,-148.187500 60.554436,-148.135834 60.580826,-148.085480 60.600132,-147.958893 60.510277,-147.937851 60.451378,-147.949875 60.431660,-148.004028 60.411240,-148.042786 60.399853,-148.112762 60.400543,-148.141968 60.379158,-148.167236 60.348877,-148.236572 60.300743,-148.310272 60.262772,-148.366089 60.247215,-148.426590 60.181030,-148.336670 60.201103,-148.298325 60.218494,-148.273422 60.235325,-148.246246 60.243286,-148.199982 60.253883,-148.113388 60.228321,-148.098877 60.205967,-148.133194 60.166382,-148.157639 60.147076,-148.178345 60.136799,-148.211121 60.125824,-148.254440 60.116940,-148.287979 60.124645,-148.289688 60.155441,-148.324310 60.163189,-148.365067 60.123947,-148.375549 60.061104,-148.401123 59.986656,-148.438522 59.948460,-148.656677 59.952908,-148.761398 59.962006,-148.892792 59.949997,-149.020020 59.957771,-149.070557 59.961662,-149.112518 59.983669,-149.070129 60.021870,-149.043411 60.045895,-149.077484 60.056381,-149.107758 60.051102,-149.147369 60.039997,-149.201660 59.989784,-149.210266 59.952774,-149.232773 59.902905,-149.264191 59.872074,-149.275299 59.867493,-149.290771 59.875061,-149.296112 59.973045,-149.295563 60.004440,-149.371506 60.116241,-149.419739 60.116241,-149.433899 60.092491,-149.438675 60.051453,-149.530136 59.925964,-149.563477 59.904575,-149.628052 59.821938,-149.593048 59.789162,-149.551117 59.755554,-149.523682 59.726795,-149.550278 59.720127,-149.586670 59.739433,-149.666885 59.812492,-149.663330 59.832771,-149.645142 59.871658,-149.645569 59.892494,-149.655579 59.916664,-149.691879 59.954716,-149.734283 59.954678,-149.758911 59.835823,-149.764740 59.779991,-149.745972 59.715824,-149.750824 59.659153,-149.786407 59.665962,-149.806320 59.684711,-149.888611 59.752220,-149.919861 59.774017,-150.027786 59.796314,-150.034790 59.773254,-149.974426 59.746658,-149.918259 59.713116,-149.934998 59.690269,-149.959442 59.664993,-150.013641 59.627487,-150.249863 59.494995,-150.296967 59.479988,-150.344711 59.466518,-150.381668 59.469364,-150.379425 59.495544,-150.359711 59.533051,-150.291382 59.606102,-150.224670 59.715477,-150.252808 59.706940,-150.279175 59.686104,-150.299988 59.662491,-150.333618 59.618324,-150.357483 59.589432,-150.486725 59.463882,-150.538376 59.518353,-150.539734 59.547493,-150.500748 59.591240,-150.541687 59.591660,-150.616943 59.554436,-150.628601 59.534721,-150.606659 59.518326,-150.585190 59.485016,-150.603058 59.432213,-150.677780 59.419254,-150.722504 59.421471,-150.736603 59.395077,-150.752228 59.381935,-150.873322 59.327492,-150.892502 59.293327,-150.885818 59.254574,-150.907501 59.243324,-150.951385 59.238327,-150.996643 59.274162,-151.040985 59.295826,-151.142242 59.290550,-151.180847 59.281380,-151.097870 59.230373,-151.120682 59.211800,-151.154175 59.208046,-151.176941 59.209991,-151.266968 59.219986,-151.357483 59.241661,-151.397781 59.258469,-151.419312 59.257633,-151.483063 59.231934,-151.554169 59.201660,-151.576157 59.173012,-151.607208 59.167213,-151.723328 59.160820,-151.746094 59.162491,-151.900574 59.219711,-151.976242 59.275826,-151.983047 59.302422,-151.899170 59.408043,-151.862213 59.423607,-151.838318 59.431938,-151.683075 59.476936,-151.663055 59.480820,-151.637238 59.480270,-151.591095 59.478325,-151.485535 59.471375,-151.453064 59.467491,-151.448532 59.508675,-151.435074 59.535408,-151.351517 59.558601,-151.272522 59.579163,-151.216095 59.594711,-150.997894 59.780827,-151.017792 59.792496,-151.053680 59.792290,-151.111115 59.774712,-151.199982 59.744156,-151.434860 59.656796,-151.469223 59.636730,-151.575104 59.646263,-151.628052 59.654991,-151.729584 59.674854,-151.757233 59.683876,-151.780853 59.692490,-151.835968 59.719437,-151.864151 59.739437,-151.878311 59.759995,-151.879578 59.782494,-151.724716 60.014717,-151.668900 60.064716,-151.646393 60.080826,-151.568878 60.124710,-151.508362 60.155823,-151.489441 60.166939,-151.453339 60.189987,-151.427368 60.211102,-151.404449 60.240273,-151.302643 60.388329,-151.289032 60.448879,-151.277512 60.510273,-151.278275 60.543049,-151.307785 60.568050,-151.332977 60.587078,-151.372223 60.658325,-151.382507 60.666935,-151.416534 60.708881,-151.406738 60.728111,-151.250565 60.775406,-151.141693 60.783051,-151.088318 60.784721,-151.047775 60.789162,-150.857758 60.877769,-150.669464 60.963882,-150.438904 61.030273,-150.404175 61.036800,-150.370819 61.037216,-150.337280 61.029785,-150.322510 60.999161,-150.300278 60.975822,-150.277512 60.959576,-150.219437 60.933743,-150.155273 60.924713,-150.045288 60.911102,-149.904175 60.945267,-149.878876 60.953323,-149.854706 60.965549,-149.836395 60.973602,-149.815277 60.974434,-149.767242 60.970268,-149.731934 60.966660,-149.561401 60.938324,-149.428070 60.915710,-149.364731 60.908546,-149.228058 60.891937,-149.170563 60.885551,-149.149445 60.881935,-149.119995 60.875549,-149.091583 60.869171,-149.052505 60.852005,-149.029739 60.851658,-149.046051 60.881519,-149.096390 60.914852,-149.153625 60.941933,-149.183075 60.948326,-149.209991 60.947769,-149.401169 60.956768,-149.615814 60.990273,-149.691940 61.011665,-149.720001 61.021935,-149.803329 61.054714,-149.829437 61.072773,-149.849991 61.083328,-149.943329 61.109993,-150.062012 61.157768,-149.995178 61.216324,-149.820282 61.320549,-149.794464 61.335266,-149.706940 61.383606,-149.617767 61.406654,-149.529587 61.422352,-149.485809 61.431938,-149.252045 61.492493,-149.422791 61.508327,-149.606934 61.490829,-149.634857 61.487354,-149.687500 61.474850,-149.769455 61.438881,-149.882217 61.380131,-149.911530 61.342979,-149.948639 61.299213,-149.963379 61.269463,-149.994583 61.258923,-150.071381 61.244995,-150.104156 61.249718,-150.136963 61.254440,-150.162506 61.255829,-150.279449 61.255554,-150.330002 61.250969,-150.357758 61.247215,-150.399170 61.246384,-150.453339 61.247490,-150.477478 61.249435,-150.506104 61.256248,-150.545410 61.285275,-150.626373 61.286385,-150.728043 61.245827,-150.749146 61.238884,-150.872223 61.208885,-150.892242 61.204712,-150.929245 61.204647,-151.001129 61.185547,-151.026398 61.177216,-151.068344 61.152908,-151.081940 61.135826,-151.137787 61.069160,-151.161255 61.053467,-151.197983 61.042080,-151.307495 61.030273,-151.445694 61.016941,-151.485001 61.011387,-151.528351 60.998047,-151.583618 60.976936,-151.740814 60.904709,-151.800140 60.854992,-151.804718 60.833878,-151.788345 60.807072,-151.771118 60.788048,-151.730286 60.759163,-151.709717 60.731865,-151.729782 60.717350,-151.773071 60.720406,-151.814453 60.734161,-151.848312 60.740547,-151.927216 60.718323,-152.038910 60.669716,-152.054718 60.653046,-152.057220 60.647491,-152.104706 60.602493,-152.166946 60.573608,-152.225052 60.557354,-152.327774 60.491520,-152.339294 60.467213,-152.333603 60.436310,-152.301178 60.410961,-152.336121 60.364159,-152.421783 60.293259,-152.549164 60.252777,-152.630280 60.229431,-152.728333 60.243881,-152.818604 60.264999,-152.883347 60.296436,-152.912231 60.308044,-152.942780 60.310272,-152.967773 60.311104,-153.006683 60.311378,-153.028625 60.308327,-153.078888 60.298187,-153.102585 60.278358,-153.081116 60.279160,-153.052505 60.289719,-153.005692 60.294163,-152.966095 60.290550,-152.936874 60.281315,-152.928299 60.242458,-152.895020 60.221931,-152.864716 60.209435,-152.829453 60.200130,-152.807220 60.197769,-152.768616 60.189365,-152.685547 60.144440,-152.596100 60.094437,-152.577286 60.073257,-152.587494 60.046383,-152.614716 60.017494,-152.716309 59.916592,-152.826111 59.881382,-152.872208 59.876240,-152.944870 59.878048,-152.990677 59.886314,-153.029175 59.887772,-153.225830 59.865131,-153.277573 59.818951,-153.254593 59.816383,-153.235397 59.823746,-153.210144 59.828606,-153.053619 59.833603,-153.001953 59.819298,-153.000580 59.791107,-153.042648 59.709438,-153.157501 59.664711,-153.204712 59.647217,-153.226105 59.643883,-153.322510 59.629990,-153.348328 59.628601,-153.402939 59.652214,-153.368042 59.703323,-153.330002 59.725060,-153.346649 59.736382,-153.420563 59.766106,-153.440735 59.719223,-153.469986 59.658047,-153.592773 59.554710,-153.612625 59.551521,-153.765015 59.520546,-153.720688 59.472492,-153.743332 59.437210,-153.797516 59.426102,-153.941376 59.399437,-154.082764 59.374435,-154.110809 59.373604,-154.143631 59.376099,-154.119431 59.359997,-154.099976 59.349434,-154.079437 59.345825,-154.067230 59.345543,-153.996796 59.353882,-154.066956 59.322495,-154.108749 59.305687,-154.131378 59.286942,-154.256958 59.132767,-154.180344 59.029438,-154.146942 59.025963,-154.116669 59.040691,-154.087906 59.063049,-154.063339 59.074303,-154.040558 59.079437,-154.017792 59.078049,-153.921661 59.068054,-153.711670 59.070549,-153.673065 59.053604,-153.632629 59.015205,-153.598465 58.998608,-153.565002 58.988884,-153.538071 58.986244,-153.516266 58.989296,-153.488037 58.999226,-153.423477 58.980824,-153.331390 58.929161,-153.261185 58.859573,-153.447784 58.714439,-153.608612 58.634720,-153.689728 58.617493,-153.763916 58.609993,-153.905289 58.583050,-153.926041 58.511520,-153.959579 58.489994,-153.999146 58.490829,-154.068878 58.491936,-154.102692 58.480061,-154.069733 58.420273,-154.035004 58.404160,-154.005096 58.382004,-154.059586 58.356937,-154.118866 58.350273,-154.148697 58.353409,-154.179993 58.356384,-154.206238 58.352497,-154.322784 58.306656,-154.354233 58.278328,-154.337769 58.259720,-154.285278 58.267494,-154.209991 58.296524,-154.185349 58.317215,-154.154449 58.311886,-154.114639 58.280407,-154.235672 58.130688,-154.326660 58.106102,-154.384232 58.110340,-154.443054 58.144440,-154.497772 58.092766,-154.570480 58.024784,-154.597778 58.023323,-154.637100 58.032635,-154.735809 58.019157,-154.782776 58.002220,-154.825287 58.020271,-154.894745 58.029018,-154.965546 58.029434,-155.033401 58.014610,-155.048340 57.957497,-155.066116 57.891800,-155.083893 57.880962,-155.256958 57.829163,-155.294998 57.749088,-155.311127 57.734436,-155.389587 57.717281,-155.464172 57.750000,-155.557098 57.792358,-155.583313 57.794441,-155.606934 57.789303,-155.623749 57.778049,-155.706665 57.641663,-155.734436 57.551384,-155.754181 57.545830,-155.799316 57.540829,-155.815689 57.559017,-155.840271 57.564438,-155.964996 57.536385,-156.038605 57.508888,-156.030640 57.441654,-156.066406 57.432213,-156.098038 57.434299,-156.123871 57.450615,-156.183197 57.476101,-156.206238 57.476238,-156.489990 57.331108,-156.501129 57.287216,-156.422516 57.303047,-156.402802 57.306938,-156.355621 57.309017,-156.334991 57.284439,-156.341660 57.170830,-156.366104 57.144161,-156.452789 57.083328,-156.552292 56.978878,-156.680145 56.996105,-156.759460 56.991379,-156.851654 56.921940,-156.890991 56.956799,-156.940826 56.962494,-156.984436 56.908600,-157.087494 56.823608,-157.185196 56.773602,-157.206665 56.770546,-157.220673 56.772491,-157.292358 56.798882,-157.311111 56.818325,-157.340820 56.838043,-157.362915 56.850132,-157.404037 56.860825,-157.427933 56.857494,-157.454849 56.844852,-157.583328 56.707352,-157.554871 56.678883,-157.502151 56.671066,-157.479706 56.669441,-157.454926 56.638050,-157.470123 56.620270,-157.501541 56.613247,-157.679855 56.608467,-157.710968 56.629921,-157.752563 56.675060,-157.787231 56.678329,-157.816101 56.672218,-157.915634 56.645477,-157.943192 56.628048,-157.970612 56.607422,-158.050842 56.576942,-158.115677 56.560581,-158.122391 56.528950,-158.064453 56.536110,-158.020020 56.547634,-157.974991 56.562077,-157.945694 56.570827,-157.925293 56.574165,-157.889450 56.568047,-157.843521 56.551243,-157.836868 56.509995,-157.882629 56.467491,-157.981110 56.488186,-158.114990 56.511383,-158.141541 56.512356,-158.160767 56.496731,-158.130753 56.487316,-158.136185 56.462074,-158.199158 56.451939,-158.257935 56.455826,-158.283325 56.465546,-158.308609 56.472630,-158.336395 56.476517,-158.428482 56.440128,-158.445557 56.419991,-158.518799 56.351768,-158.542282 56.343437,-158.568787 56.332935,-158.609711 56.307076,-158.650574 56.278744,-158.637421 56.258743,-158.542389 56.252075,-158.559998 56.269993,-158.537094 56.296951,-158.514404 56.313908,-158.486053 56.324699,-158.447784 56.340271,-158.332489 56.320274,-158.215408 56.277252,-158.253357 56.250134,-158.279724 56.241104,-158.333893 56.227768,-158.333664 56.174160,-158.276947 56.184990,-158.244720 56.195541,-158.205002 56.215130,-158.183075 56.229988,-158.126450 56.235199,-158.207642 56.182491,-158.357208 56.145546,-158.399582 56.175129,-158.499451 56.096935,-158.489441 56.043053,-158.500305 56.003883,-158.505280 55.988884,-158.512238 55.991936,-158.585007 56.042545,-158.600403 56.100964,-158.537781 56.150543,-158.484222 56.179779,-158.499588 56.194019,-158.539185 56.193321,-158.601105 56.188042,-158.655853 56.109718,-158.657776 56.087494,-158.645569 56.021549,-158.644318 55.994995,-158.675354 55.954231,-158.752609 55.957664,-158.730682 55.974571,-158.742554 56.002495,-158.773895 56.009163,-158.849854 56.011246,-158.868881 55.998745,-158.905273 55.959435,-158.939728 55.929161,-159.021393 55.920273,-159.074432 55.921104,-159.138062 55.914154,-159.361450 55.874363,-159.470551 55.822769,-159.510559 55.791382,-159.503769 55.762493,-159.547928 55.659710,-159.560837 55.641106,-159.629974 55.589432,-159.667236 55.577217,-159.699982 55.566940,-159.720001 55.563324,-159.730835 55.563049,-159.741364 55.608604,-159.676941 55.684990,-159.624023 55.812073,-159.644592 55.825275,-159.712082 55.843185,-159.748047 55.848602,-159.842636 55.850269,-159.975555 55.815544,-160.036118 55.789715,-160.056519 55.762634,-160.030838 55.741447,-160.027237 55.721516,-160.065002 55.696655,-160.144180 55.660271,-160.280579 55.636940,-160.309723 55.636383,-160.420563 55.629990,-160.439728 55.570831,-160.477280 55.492493,-160.507782 55.478043,-160.540634 55.480061,-160.592560 55.558949,-160.633057 55.566666,-160.759354 55.533810,-160.675903 55.517284,-160.657303 55.500408,-160.669098 55.466797,-160.698883 55.455269,-160.762787 55.447769,-160.790009 55.447075,-160.810272 55.451660,-160.835968 55.464714,-160.839783 55.490269,-160.834167 55.510899,-160.855835 55.520271,-160.875824 55.521103,-160.899445 55.518883,-160.928345 55.512772,-160.947357 55.502769,-160.974091 55.474850,-160.997223 55.445545,-161.025574 55.427216,-161.079437 55.407494,-161.248886 55.347908,-161.509903 55.368393,-161.483734 55.483463,-161.402802 55.554710,-161.362061 55.571243,-161.334167 55.550827,-161.313477 55.538048,-161.286133 55.530548,-161.173065 55.516525,-161.145279 55.530270,-161.404877 55.629990,-161.440826 55.634995,-161.484436 55.633331,-161.508362 55.631104,-161.562500 55.622765,-161.611786 55.609993,-161.714783 55.506729,-161.703461 55.402630,-161.821930 55.294998,-161.927155 55.224781,-161.954437 55.231934,-162.000854 55.236382,-162.021393 55.236107,-162.043198 55.230125,-162.012512 55.185547,-161.968048 55.131519,-161.959442 55.125824,-161.958939 55.111797,-161.975281 55.099159,-162.060410 55.072701,-162.087769 55.078880,-162.121643 55.097630,-162.135498 55.113949,-162.115814 55.128876,-162.098038 55.159153,-162.166672 55.150616,-162.217072 55.100998,-162.196320 55.049023,-162.217346 55.027908,-162.248871 55.018600,-162.270844 55.015549,-162.445038 55.036427,-162.467636 55.044163,-162.497360 55.062077,-162.522995 55.091728,-162.516052 55.112980,-162.488586 55.118462,-162.478607 55.167213,-162.504730 55.212494,-162.568466 55.294437,-162.636383 55.297356,-162.670151 55.287079,-162.714081 55.241241,-162.714569 55.210129,-162.690826 55.193321,-162.595551 55.123878,-162.566940 54.957977,-162.650848 55.000690,-162.729431 54.951519,-162.753601 54.940407,-162.783066 54.934296,-162.860260 54.929718,-162.873886 54.930965,-162.916962 54.950546,-162.960266 54.981102,-162.975403 55.002495,-162.974152 55.031937,-163.018219 55.081589,-163.116653 55.125549,-163.179443 55.139576,-163.238464 55.096172,-163.218872 55.033333,-163.206390 55.013329,-163.180267 55.003120,-163.141968 54.994713,-163.074722 54.974018,-163.056259 54.964020,-163.053085 54.932663,-163.237213 54.836937,-163.330551 54.808186,-163.352905 54.809715,-163.383469 54.858604,-163.334656 54.874783,-163.278381 54.942955,-163.258636 54.973320,-163.282227 54.992359,-163.326248 55.117077,-163.307083 55.130131,-163.238037 55.153877,-163.181396 55.173050,-163.119446 55.184158,-163.076660 55.187767,-162.993469 55.179852,-162.966095 55.164154,-162.940277 55.177490,-162.886597 55.243881,-162.886520 55.267494,-162.791107 55.301384,-162.626923 55.354439,-162.577362 55.339989,-162.548904 55.342491,-162.491089 55.372768,-162.507645 55.444084,-162.545837 55.455269,-162.480560 55.506104,-162.425018 55.549164,-162.260559 55.673050,-162.235535 55.686653,-162.089172 55.759720,-162.018890 55.783051,-161.840820 55.867210,-161.807632 55.883739,-161.776672 55.893188,-161.391693 55.959435,-161.365402 55.950691,-161.244141 55.942490,-161.068329 55.934990,-161.014175 55.912769,-161.021881 55.887352,-160.941101 55.819443,-160.870819 55.768326,-160.847778 55.753326,-160.806946 55.727211,-160.679581 55.695824,-160.662155 55.734642,-160.703888 55.761665,-160.731659 55.773048,-160.755722 55.774853,-160.790146 55.877560,-160.768616 55.878326,-160.745544 55.871376,-160.700974 55.856380,-160.662506 55.853325,-160.638336 55.855553,-160.556946 55.863609,-160.505569 55.867905,-160.472412 55.838810,-160.477005 55.815895,-160.467636 55.795135,-160.287231 55.770271,-160.250076 55.771519,-160.239639 55.844158,-160.336395 55.869438,-160.458038 55.906937,-160.479156 55.915543,-160.528076 55.935547,-160.574020 55.993740,-160.453186 56.164158,-160.431946 56.185547,-160.422791 56.205551,-160.392517 56.244438,-160.371933 56.265827,-160.346954 56.285553,-160.194458 56.373604,-160.108337 56.410545,-160.051468 56.423744,-159.976654 56.454712,-159.944443 56.471657,-159.921677 56.489437,-159.888474 56.514992,-159.862762 56.528603,-159.837219 56.540833,-159.715271 56.581940,-159.577209 56.615829,-159.549438 56.619438,-159.512238 56.621101,-159.479706 56.622215,-159.422791 56.634995,-159.398621 56.643051,-159.293610 56.684433,-159.263626 56.700546,-159.235535 56.728043,-159.166962 56.760277,-159.035004 56.804993,-158.975830 56.782768,-158.811401 56.780548,-158.639038 56.762913,-158.647369 56.831520,-158.666534 56.845688,-158.689102 56.871311,-158.699432 56.979988,-158.682785 57.012630,-158.650848 57.051102,-158.635559 57.066666,-158.615540 57.084435,-158.449738 57.215271,-158.423615 57.234993,-158.401947 57.250275,-158.385284 57.261665,-158.356659 57.279991,-158.285278 57.324165,-158.259460 57.334160,-158.198059 57.351387,-158.158905 57.359436,-158.133911 57.361107,-158.115265 57.358047,-158.093323 57.379433,-158.065826 57.404709,-157.944992 57.488743,-157.785278 57.549854,-157.741669 57.562210,-157.682175 57.563412,-157.667511 57.528328,-157.641388 57.483879,-157.581665 57.474709,-157.554993 57.473045,-157.508057 57.473045,-157.397919 57.492771,-157.392944 57.559574,-157.444229 57.545273,-157.436813 57.520271,-157.469727 57.497215,-157.574951 57.527218,-157.629974 57.609718,-157.686249 57.614437,-157.704163 57.637352,-157.706940 57.664993,-157.689850 57.757774,-157.674164 57.784164,-157.646393 57.852493,-157.639465 57.874161,-157.629974 57.913322,-157.623322 57.978325,-157.611374 58.084023,-157.586945 58.128048,-157.566650 58.149162,-157.543884 58.167351,-157.397156 58.200645,-157.319305 58.208466,-157.185349 58.189640,-157.163757 58.170895,-157.139038 58.164436,-157.158829 58.194225,-157.208328 58.209995,-157.349335 58.235161,-157.429489 58.224178,-157.543198 58.266243,-157.565826 58.307076,-157.559860 58.363605,-157.551392 58.387772,-157.488190 58.481796,-157.468735 58.498466,-157.225006 58.641106,-157.072495 58.739437,-157.071655 58.764160,-156.975418 58.917614,-156.945847 58.926697,-156.896973 58.971657,-156.855270 58.999992,-156.781815 59.151241,-156.805267 59.141106,-156.836670 59.123047,-156.865326 59.102352,-156.882492 59.058258,-156.875809 59.033741,-156.880341 59.012909,-157.075287 58.889992,-157.111938 58.874435,-157.193466 58.849991,-157.222778 58.843605,-157.256409 58.838882,-157.279724 58.836105,-157.373047 58.818604,-157.678070 58.741661,-157.801666 58.706100,-157.992645 58.648186,-158.054718 58.630547,-158.092499 58.621376,-158.122772 58.615273,-158.154724 58.609718,-158.190964 58.606800,-158.229858 58.613884,-158.296387 58.637215,-158.318329 58.645828,-158.345963 58.725891,-158.372208 58.751659,-158.400009 58.764576,-158.442230 58.776100,-158.499725 58.784855,-158.529587 58.792496,-158.559235 58.808186,-158.563339 58.839436,-158.526733 58.849228,-158.509460 58.869713,-158.492203 58.911518,-158.488113 59.000755,-158.366669 59.024158,-158.175415 59.008327,-158.131241 58.994228,-158.093872 58.963882,-158.074020 58.918671,-158.055267 58.896942,-158.020142 58.873116,-157.992767 58.904991,-158.074295 58.994019,-158.091949 59.006104,-158.110535 59.017212,-158.129425 59.028328,-158.153625 59.034439,-158.244415 59.047688,-158.265411 59.047939,-158.286163 59.050770,-158.364914 59.067356,-158.448624 59.098717,-158.466614 59.113968,-158.496643 59.138603,-158.538620 59.173744,-158.548050 59.142490,-158.519470 59.111664,-158.531952 59.068718,-158.497192 59.043964,-158.616089 58.921104,-158.636414 58.910820,-158.696121 58.882771,-158.733505 58.885994,-158.729019 58.919994,-158.744781 58.991795,-158.821243 58.968464,-158.792786 58.951660,-158.772644 58.898327,-158.778900 58.773880,-158.796814 58.750687,-158.828751 58.729851,-158.854843 58.725685,-158.882782 58.736660,-158.881317 58.763050,-158.846375 58.771935,-158.821808 58.777489,-158.808640 58.801868,-158.839584 58.815544,-158.865814 58.811241,-158.887512 58.801659,-158.911392 58.767075,-158.907227 58.724434,-158.756821 58.504166,-158.737350 58.497631,-158.710892 58.492771,-158.795837 58.415825,-158.818329 58.406654,-158.838318 58.402489,-158.897522 58.395546,-158.987762 58.408600,-159.031403 58.418602,-159.062912 58.428604,-159.123322 58.486107,-159.167786 58.543610,-159.345551 58.719437,-159.361115 58.732765,-159.429718 58.782768,-159.467773 58.804710,-159.602783 58.898605,-159.620895 58.944088,-159.733612 58.934158,-159.752502 58.925827,-159.793335 58.849159,-159.812363 58.805687,-159.855255 58.784996,-159.914307 58.770409,-159.959442 58.808044,-159.987900 58.840965,-160.154724 58.891937,-160.226929 58.909714,-160.255280 58.919159,-160.318756 58.953049,-160.298401 58.974365,-160.258896 58.988255,-160.269165 59.008331,-160.322769 59.058327,-160.394867 59.059994,-160.485260 59.028328,-160.682770 58.940826,-160.778076 58.892769,-160.838898 58.869156,-160.870956 58.883255,-160.896667 58.885551,-160.980621 58.869854,-161.001404 58.856659,-161.029175 58.843048,-161.053070 58.834160,-161.126373 58.807770,-161.197235 58.794716,-161.250854 58.790550,-161.287231 58.770828,-161.356796 58.728325,-161.374435 58.711102,-161.380890 58.669228,-161.361115 58.663322,-161.347260 58.665817,-161.426666 58.647491,-161.632202 58.599159,-161.710541 58.613327,-161.819458 58.626938,-162.078400 58.619850,-162.125275 58.633331,-162.165970 58.655128,-162.043060 58.676659,-161.994720 58.680550,-161.952347 58.668461,-161.937714 58.647633,-161.911133 58.648048,-161.882904 58.655548,-161.853882 58.668602,-161.699158 58.763325,-161.655853 58.802906,-161.685425 58.821522,-161.715683 58.822773,-161.753082 58.818054,-161.791809 58.866520,-161.794739 58.901104,-161.792786 59.017212,-161.758362 59.022491,-161.716934 59.034161,-161.615829 59.072079,-161.568405 59.106659,-161.624008 59.137077,-161.656128 59.124157,-161.699860 59.113327,-161.731934 59.109993,-161.761551 59.109299,-161.821945 59.115688,-161.852783 59.114159,-161.887192 59.091484,-161.854156 59.060822,-161.870132 59.061657,-161.891693 59.066940,-161.917236 59.081799,-161.955261 59.112213,-161.994019 59.147076,-162.026123 59.231102,-161.955826 59.380688,-161.822784 59.448601,-161.753479 59.469433,-161.709641 59.496937,-161.780304 59.560547,-161.888062 59.684433,-161.930573 59.733047,-161.976654 59.784439,-162.053619 59.854164,-162.095276 59.891937,-162.199722 60.010132,-162.236526 60.063606,-162.236099 60.092770,-162.199982 60.151100,-162.158630 60.219986,-162.156052 60.244923,-162.201111 60.239712,-162.234161 60.211662,-162.269455 60.164158,-162.329849 60.134995,-162.354996 60.145828,-162.369583 60.169434,-162.384186 60.332497,-162.311951 60.442215,-162.227783 60.533333,-162.221924 60.581665,-162.110535 60.631935,-162.084167 60.641106,-162.053482 60.644855,-162.026672 60.643467,-161.977905 60.642216,-161.953323 60.648602,-161.879425 60.702217,-161.907227 60.708046,-162.121368 60.691101,-162.261673 60.616379,-162.279724 60.599159,-162.369720 60.471657,-162.418884 60.393608,-162.463898 60.368050,-162.551392 60.334717,-162.569458 60.316383,-162.563629 60.253883,-162.554718 60.231102,-162.496109 60.213745,-162.454163 60.190617,-162.448334 60.169716,-162.475830 60.050133,-162.491364 60.023323,-162.510696 60.000828,-162.542236 59.988045,-162.579163 59.983047,-162.758911 59.957497,-162.970825 59.900826,-163.100555 59.862770,-163.139740 59.852776,-163.173340 59.846657,-163.339172 59.822769,-163.364166 59.819717,-163.429993 59.813606,-163.659454 59.794994,-163.755280 59.796387,-163.843048 59.799721,-163.946381 59.809715,-164.006409 59.816666,-164.065277 59.824165,-164.099854 59.832912,-164.138199 59.847630,-164.157501 59.859718,-164.174316 59.877628,-164.199982 59.915543,-164.214218 59.950058,-164.197784 59.961937,-164.167496 59.966518,-164.123596 59.968597,-164.094223 59.977768,-164.189178 60.022766,-164.213898 60.031380,-164.254730 60.044159,-164.346954 60.062210,-164.417496 60.087906,-164.491089 60.154709,-164.646118 60.244995,-164.660904 60.266937,-164.646973 60.283882,-164.678070 60.295830,-164.744171 60.291176,-164.775024 60.291382,-164.821655 60.300270,-164.948059 60.327774,-165.006943 60.346104,-165.035553 60.359993,-165.138397 60.440960,-165.095978 60.455269,-165.029068 60.465649,-164.971237 60.514717,-164.979645 60.540409,-165.009460 60.547493,-165.040283 60.546104,-165.065826 60.542496,-165.096375 60.534996,-165.149445 60.516937,-165.185425 60.502357,-165.207077 60.498188,-165.248596 60.497215,-165.269470 60.499161,-165.366104 60.509720,-165.385559 60.517212,-165.422440 60.552147,-165.369858 60.580967,-165.265564 60.595268,-165.011398 60.697491,-164.985825 60.724087,-164.904999 60.819717,-164.848602 60.868599,-164.761963 60.899162,-164.741089 60.904160,-164.710144 60.909019,-164.659317 60.911659,-164.643616 60.896416,-164.683746 60.863323,-164.692429 60.838326,-164.655853 60.819992,-164.634735 60.818054,-164.429993 60.801659,-164.270920 60.782906,-164.249069 60.699322,-164.282745 60.690990,-164.320557 60.657768,-164.385559 60.611801,-164.437424 60.559155,-164.412369 60.552769,-164.392380 60.557354,-164.326797 60.607006,-164.252563 60.642742,-164.213608 60.644825,-164.152237 60.656242,-164.124283 60.667492,-164.109009 60.702042,-164.038345 60.758053,-163.980286 60.775826,-163.951385 60.780548,-163.865265 60.774158,-163.805893 60.736900,-163.819031 60.709023,-163.834030 60.690685,-163.832291 60.622696,-163.786819 60.577702,-163.745270 60.578049,-163.675430 60.586239,-163.650299 60.592491,-163.594147 60.614998,-163.539734 60.637772,-163.458466 60.675133,-163.427155 60.702702,-163.412506 60.757214,-163.517242 60.800133,-163.638199 60.824856,-163.755981 60.845406,-163.846100 60.846939,-163.888840 60.854317,-163.860764 60.870049,-163.810547 60.883881,-163.769318 60.883533,-163.744461 60.871239,-163.717224 60.864998,-163.695282 60.863609,-163.668610 60.865547,-163.644470 60.869438,-163.555130 60.897106,-163.673050 60.990685,-163.741653 60.992214,-163.892517 60.918327,-163.930695 60.894905,-163.962936 60.867996,-164.046112 60.856941,-164.079712 60.858330,-164.101517 60.863331,-164.159180 60.868050,-164.182220 60.868324,-164.398621 60.865829,-164.437775 60.863052,-164.546112 60.850548,-164.561798 60.852077,-164.596939 60.876030,-164.585480 60.902493,-164.613739 60.924019,-164.636963 60.928879,-164.894730 60.952633,-164.941803 60.952770,-164.972626 60.944431,-164.992767 60.930687,-165.028625 60.913044,-165.073746 60.907696,-165.126801 60.918880,-165.150299 60.928047,-165.186874 60.971382,-165.156128 60.994713,-165.126511 61.005692,-165.097229 61.011108,-165.050735 61.014549,-164.947235 61.019157,-164.859161 61.072220,-164.822083 61.103050,-164.965546 61.115829,-165.006241 61.098289,-164.996231 61.073326,-165.027298 61.062435,-165.072784 61.066101,-165.113190 61.080547,-165.154144 61.126545,-165.120621 61.147129,-165.095825 61.198601,-165.093597 61.227486,-165.138611 61.256660,-165.124420 61.227486,-165.164459 61.171085,-165.200211 61.165882,-165.244980 61.155685,-165.366867 61.201797,-165.292511 61.251389,-165.155991 61.412910,-165.105148 61.413639,-165.059677 61.416840,-164.992096 61.471268,-164.958359 61.478188,-164.853180 61.493393,-164.763336 61.536110,-164.747223 61.548050,-164.692230 61.600273,-164.719360 61.625336,-164.762512 61.626938,-164.807220 61.584435,-164.935318 61.524887,-164.972076 61.519386,-165.017242 61.500000,-165.075562 61.432213,-165.154190 61.433327,-165.197647 61.406517,-165.287720 61.325966,-165.270844 61.311935,-165.307495 61.258049,-165.403580 61.202454,-165.386536 61.179577,-165.366241 61.172497,-165.345261 61.162354,-165.366440 61.072563,-165.386688 61.068604,-165.419739 61.070549,-165.493591 61.075272,-165.532013 61.083118,-165.600601 61.114510,-165.634995 61.166382,-165.644257 61.243950,-165.615540 61.276520,-165.702209 61.300270,-165.740814 61.306938,-165.762238 61.308601,-165.816940 61.307629,-165.838196 61.309296,-165.856796 61.318050,-165.873596 61.332630,-165.897522 61.360275,-165.920685 61.401379,-165.884460 61.429993,-165.830292 61.442490,-165.792862 61.445335,-165.764526 61.485409,-165.793060 61.519714,-165.815979 61.534302,-165.893814 61.554714,-165.937225 61.555550,-165.962219 61.554710,-165.986389 61.550545,-166.089203 61.520130,-166.068283 61.496868,-166.116806 61.492073,-166.170837 61.545830,-166.197357 61.590267,-166.147705 61.713776,-166.151535 61.656239,-166.137238 61.634720,-166.087494 61.636383,-166.060547 61.638885,-165.826950 61.681240,-165.851807 61.688877,-165.933899 61.703880,-166.008698 61.731796,-166.039185 61.756939,-166.092697 61.815964,-165.756134 61.841377,-165.633331 61.846939,-165.680832 61.907215,-165.704712 61.921524,-165.719147 61.938042,-165.752914 61.986099,-165.756134 62.015274,-165.744446 62.046242,-165.701538 62.115967,-165.677078 62.137352,-165.624146 62.164711,-165.566406 62.199158,-165.429718 62.307213,-165.309174 62.403603,-165.267242 62.434715,-165.247223 62.446098,-165.119293 62.512218,-165.071808 62.532772,-165.043335 62.538189,-165.001129 62.537498,-164.897522 62.531380,-164.653900 62.429993,-164.686401 62.380272,-164.636414 62.417496,-164.677795 62.464996,-164.776672 62.490273,-164.847763 62.569332,-164.791840 62.589104,-164.746338 62.598270,-164.689178 62.614159,-164.649460 62.631245,-164.628876 62.642494,-164.493362 62.746731,-164.658356 62.674438,-164.746216 62.658157,-164.786041 62.652348,-164.878601 62.735550,-164.887512 62.781380,-164.876801 62.838047,-164.811676 62.927631,-164.754181 62.982491,-164.698273 63.019230,-164.662094 63.027493,-164.562500 63.032768,-164.451935 63.030548,-164.377472 63.020546,-164.343735 63.008469,-164.318054 63.009647,-164.326935 63.043610,-164.364838 63.067772,-164.449829 63.078220,-164.528412 63.084854,-164.584518 63.134090,-164.401123 63.214993,-164.305573 63.239159,-164.279449 63.243050,-164.152237 63.259583,-163.994293 63.252911,-163.745544 63.218323,-163.725281 63.214714,-163.676117 63.165543,-163.579163 63.139992,-163.539734 63.128326,-163.372772 63.056656,-163.328613 63.033607,-163.111664 63.051933,-163.067093 63.058880,-162.906677 63.128876,-162.875549 63.142769,-162.641388 63.247772,-162.621368 63.259438,-162.495682 63.340546,-162.362762 63.446655,-162.305984 63.540623,-162.270569 63.542496,-162.240128 63.540691,-162.080841 63.506660,-162.034180 63.482491,-162.083069 63.451660,-162.142242 63.425270,-162.105835 63.431938,-161.961121 63.450546,-161.729431 63.462212,-161.590546 63.453049,-161.567780 63.450829,-161.441528 63.457771,-161.301392 63.476936,-161.263062 63.482765,-161.216949 63.491661,-161.195557 63.496658,-161.175842 63.502495,-161.151672 63.512497,-160.818054 63.716385,-160.790436 63.736660,-160.772247 63.765831,-160.764328 63.793190,-160.770844 63.848606,-160.781250 63.874573,-160.815552 63.919716,-160.846100 63.950829,-160.874146 63.983330,-160.929443 64.049988,-160.942078 64.071098,-160.948334 64.099716,-160.957077 64.145821,-160.954163 64.177483,-160.948334 64.199417,-161.051941 64.282486,-161.090820 64.300537,-161.168060 64.346649,-161.178955 64.375114,-161.189026 64.414154,-161.396118 64.428314,-161.420837 64.429703,-161.457779 64.427483,-161.496811 64.409706,-161.522781 64.388741,-161.529175 64.418869,-161.463455 64.509438,-161.443878 64.518326,-161.385193 64.536438,-161.338593 64.525269,-161.307220 64.519440,-161.219727 64.505829,-161.196106 64.503326,-161.118042 64.500549,-161.089172 64.501389,-161.058044 64.503601,-161.017166 64.510475,-160.807571 64.626518,-160.787231 64.658600,-160.782791 64.719154,-160.871643 64.793869,-160.958893 64.834152,-161.058044 64.866653,-161.089722 64.881088,-161.111115 64.893326,-161.147858 64.919144,-161.123596 64.920822,-161.094452 64.913315,-161.064453 64.911926,-160.997421 64.938454,-161.038605 64.941360,-161.174576 64.938034,-161.197922 64.933037,-161.311127 64.863602,-161.370468 64.805878,-161.379166 64.786377,-161.425705 64.770828,-161.516418 64.759720,-161.552490 64.764435,-161.637238 64.780273,-161.666412 64.787766,-161.690277 64.798599,-161.744446 64.795822,-161.840820 64.768875,-161.910828 64.742752,-161.932877 64.721230,-161.896545 64.726234,-161.870270 64.739006,-161.831390 64.751099,-161.797363 64.754990,-161.891678 64.710960,-161.929443 64.705826,-161.986664 64.702774,-162.030014 64.703674,-162.072510 64.713463,-162.107773 64.716240,-162.187225 64.682205,-162.208344 64.670822,-162.232834 64.651649,-162.404724 64.582214,-162.493896 64.555122,-162.521118 64.545532,-162.553894 64.531662,-162.582779 64.516800,-162.606384 64.497353,-162.619354 64.472000,-162.613037 64.446785,-162.631653 64.387497,-162.760010 64.343597,-162.790283 64.336105,-162.816528 64.411659,-162.875000 64.508331,-162.957489 64.550812,-163.170013 64.655258,-163.224152 64.654915,-163.265289 64.639435,-163.313904 64.618317,-163.352631 64.590683,-163.309723 64.561646,-163.282776 64.552765,-163.158905 64.515137,-163.121658 64.513191,-163.089157 64.520126,-163.040558 64.518318,-163.043610 64.491364,-163.138748 64.412689,-163.191315 64.410469,-163.211945 64.418869,-163.249161 64.447067,-163.265152 64.467209,-163.279037 64.484428,-163.424713 64.534149,-163.490540 64.552765,-163.563629 64.566376,-163.608612 64.572220,-163.668060 64.577209,-163.821930 64.589157,-163.851654 64.587204,-163.894745 64.581940,-163.935547 64.572769,-163.973740 64.564285,-164.001114 64.562065,-164.115265 64.570831,-164.279037 64.583878,-164.312775 64.584427,-164.350677 64.580688,-164.392792 64.571930,-164.541962 64.532761,-164.583069 64.521103,-164.643585 64.519073,-164.665283 64.523041,-164.685547 64.527206,-164.932648 64.532623,-164.961105 64.498596,-164.905838 64.456100,-164.844711 64.460403,-164.816650 64.466934,-164.778488 64.468597,-164.807770 64.459427,-164.859985 64.450821,-164.905273 64.446930,-165.028625 64.443863,-165.040558 64.444977,-165.072510 64.449997,-165.146118 64.463043,-165.217499 64.477768,-165.260284 64.484711,-165.281952 64.488037,-165.336670 64.495819,-165.380554 64.501938,-165.480835 64.514999,-165.515289 64.518326,-165.656128 64.530548,-165.831390 64.546097,-166.121368 64.574707,-166.155273 64.579437,-166.187500 64.584427,-166.208038 64.588593,-166.236938 64.596100,-166.348328 64.629150,-166.373871 64.639160,-166.402786 64.655960,-166.458344 64.701096,-166.489639 64.736580,-166.466019 64.803970,-166.418884 64.816086,-166.405273 64.834991,-166.387238 64.888458,-166.422241 64.919144,-166.515289 64.949150,-166.539185 64.945526,-166.696671 64.995888,-166.703323 65.018608,-166.705688 65.038872,-166.722488 65.055397,-166.745270 65.065536,-166.765015 65.070541,-166.819153 65.079437,-166.846939 65.088043,-166.892227 65.112762,-166.919739 65.131363,-166.937775 65.146942,-166.959793 65.179909,-166.952911 65.221649,-166.935822 65.243866,-166.911545 65.263191,-166.872345 65.281654,-166.848755 65.277000,-166.864441 65.256653,-166.903625 65.238312,-166.920013 65.226654,-166.936111 65.202621,-166.936676 65.180267,-166.924515 65.149292,-166.809998 65.122208,-166.788055 65.118866,-166.751404 65.116379,-166.684448 65.116653,-166.611664 65.121094,-166.564453 65.126083,-166.539307 65.134155,-166.468460 65.191093,-166.482071 65.232895,-166.367905 65.270401,-166.211670 65.256653,-166.184723 65.251801,-166.152298 65.241791,-166.119446 65.236374,-166.054169 65.250023,-166.154724 65.293594,-166.174438 65.298325,-166.206390 65.304153,-166.239716 65.309143,-166.626923 65.364151,-166.798340 65.376083,-166.823059 65.377762,-166.922821 65.376366,-166.830841 65.354988,-166.799438 65.353317,-166.764038 65.354843,-166.733597 65.343880,-166.798615 65.346375,-166.823334 65.348038,-166.856659 65.353043,-166.920013 65.365265,-166.972229 65.375809,-167.048065 65.388596,-167.071655 65.391098,-167.217773 65.402481,-167.291382 65.403595,-167.412506 65.412766,-167.462357 65.420120,-167.590271 65.453598,-167.618515 65.477348,-167.735260 65.516388,-167.863312 65.549988,-167.915833 65.561920,-167.959717 65.568878,-167.983307 65.571106,-168.038895 65.574577,-168.073196 65.583885,-168.092773 65.598877,-168.129837 65.648666,-168.131958 65.662956,-168.126373 65.669983,-168.102203 65.686646,-168.073196 65.702072,-168.047791 65.712769,-167.939453 65.748596,-167.908615 65.755547,-167.849991 65.761658,-167.871643 65.734985,-167.930847 65.715546,-167.952789 65.709427,-167.992493 65.702209,-168.024033 65.692894,-168.049164 65.676376,-168.062988 65.649429,-168.046677 65.635963,-168.020020 65.635826,-167.988312 65.642212,-167.859985 65.678864,-167.559723 65.723602,-167.501511 65.737549,-167.507156 65.769012,-167.551254 65.775337,-167.571030 65.793663,-167.512238 65.829437,-167.490540 65.835541,-167.430573 65.854706,-167.281113 65.889992,-167.222641 65.866234,-167.197647 65.859703,-167.160431 65.856789,-167.120544 65.860535,-167.046112 65.876083,-166.937775 65.911926,-166.880966 65.937820,-166.931396 65.958603,-166.962845 65.970055,-166.908630 65.993591,-166.696655 66.068878,-166.609436 66.093048,-166.586945 66.098877,-166.291687 66.173599,-166.259888 66.180122,-166.237488 66.181931,-166.211121 66.181091,-166.165283 66.174423,-166.136688 66.167480,-166.100327 66.152763,-166.143677 66.148392,-166.080841 66.124420,-166.058044 66.121094,-165.806671 66.103043,-165.780304 66.102203,-165.726791 66.105263,-165.511292 66.157135,-165.656815 66.196503,-165.713898 66.209427,-165.748322 66.214706,-165.773621 66.216385,-165.830566 66.215546,-165.870880 66.221443,-165.887375 66.236511,-165.869019 66.258049,-165.853333 66.271103,-165.834717 66.283600,-165.798615 66.303040,-165.757095 66.321236,-165.642242 66.360809,-165.466400 66.400269,-165.324158 66.425812,-165.152802 66.444145,-165.117767 66.443863,-165.083313 66.438583,-165.015564 66.423874,-164.741943 66.524155,-164.712250 66.540840,-164.416412 66.587769,-164.361938 66.593880,-164.290558 66.598038,-164.159729 66.602478,-163.933624 66.608597,-163.838593 66.604706,-163.774719 66.599716,-163.704712 66.589432,-163.683075 66.584991,-163.661682 66.580276,-163.642365 66.566719,-163.702209 66.567764,-163.828064 66.588043,-163.853882 66.589981,-163.931793 66.578049,-163.911682 66.570541,-163.878342 66.568741,-163.829712 66.567764,-163.798477 66.564705,-163.778336 66.556511,-163.756409 66.515541,-163.766266 66.483315,-163.790009 66.460686,-163.821106 66.448593,-163.854294 66.435532,-163.894165 66.392487,-163.890152 66.331932,-163.869141 66.308594,-163.857483 66.276237,-163.944595 66.231239,-163.979980 66.223312,-164.025848 66.221375,-164.091095 66.214432,-164.173996 66.190674,-164.062225 66.189423,-163.990814 66.191650,-163.948059 66.195251,-163.888489 66.160545,-163.835968 66.115669,-163.804718 66.101929,-163.734985 66.083328,-163.713898 66.078873,-163.656403 66.070541,-163.627472 66.070831,-163.536133 66.079987,-163.443054 66.086380,-163.342499 66.087204,-163.302795 66.076385,-163.262924 66.070274,-163.163635 66.065536,-163.126526 66.066513,-163.016968 66.080276,-162.791962 66.100540,-162.762238 66.099152,-162.703888 66.084427,-162.561676 66.047485,-162.378738 66.032349,-162.355255 66.033325,-162.328888 66.035538,-162.301941 66.039703,-162.241089 66.051926,-162.209167 66.060532,-162.136414 66.069717,-162.055695 66.068741,-161.982758 66.050537,-161.935272 66.035812,-161.897430 66.007217,-161.854980 65.977768,-161.816406 65.974991,-161.840546 66.008461,-161.768341 66.086380,-161.727478 66.110260,-161.679993 66.138046,-161.659042 66.152763,-161.620544 66.198029,-161.596954 66.226929,-161.575134 66.251656,-161.523346 66.268600,-161.485535 66.270264,-161.397797 66.270264,-161.363602 66.261307,-161.336105 66.234291,-161.305557 66.226509,-161.255554 66.221649,-161.194458 66.223045,-161.151672 66.231651,-161.130417 66.240540,-161.105270 66.243866,-161.078537 66.234077,-161.091949 66.170532,-161.117905 66.130127,-161.177017 66.123444,-161.149445 66.115814,-161.116394 66.118042,-161.091095 66.122482,-161.056732 66.137901,-161.015564 66.183868,-161.002792 66.207077,-161.000610 66.246651,-161.019165 66.267212,-161.123047 66.337486,-161.158630 66.346649,-161.286133 66.366928,-161.496368 66.398880,-161.520020 66.402206,-161.548065 66.402771,-161.728745 66.403603,-161.872223 66.371094,-161.890289 66.311371,-161.859848 66.284569,-161.876526 66.272766,-161.913483 66.276649,-161.961533 66.335541,-161.951385 66.353180,-161.928955 66.376503,-161.903625 66.398880,-161.876938 66.429848,-161.869720 66.454163,-161.869568 66.486649,-161.878601 66.508606,-161.900436 66.530128,-161.930008 66.551231,-162.180573 66.692749,-162.223877 66.710541,-162.243866 66.716095,-162.278076 66.721924,-162.302216 66.724991,-162.378876 66.731659,-162.484711 66.734703,-162.504745 66.740120,-162.633759 66.865814,-162.633820 66.897415,-162.606110 66.910545,-162.512238 66.918594,-162.329575 66.955750,-162.302643 66.945534,-162.117218 66.800095,-162.074646 66.702965,-162.077850 66.663521,-161.920837 66.559982,-161.885010 66.538040,-161.833618 66.516937,-161.805573 66.507767,-161.630280 66.456100,-161.594299 66.447197,-161.572510 66.447205,-161.458603 66.459290,-161.342499 66.482758,-161.299591 66.501938,-161.277802 66.513611,-161.238892 66.532211,-161.207642 66.538322,-161.186127 66.538589,-161.054443 66.480820,-161.020142 66.462769,-160.936951 66.421921,-160.817642 66.376923,-160.783340 66.371094,-160.747223 66.370819,-160.713623 66.373032,-160.677216 66.372620,-160.638336 66.365265,-160.533325 66.373596,-160.260834 66.393600,-160.235001 66.398048,-160.215134 66.427063,-160.209305 66.521378,-160.240265 66.644150,-160.264191 66.647491,-160.312073 66.649994,-160.334167 66.648605,-160.506943 66.617058,-160.520981 66.595680,-160.549179 66.587067,-160.671387 66.598038,-160.698746 66.603317,-160.719162 66.612900,-160.744308 66.632072,-160.785004 66.651093,-160.816101 66.658600,-160.838593 66.662766,-160.871109 66.665543,-160.948746 66.663872,-161.140289 66.647491,-161.173203 66.639015,-161.196106 66.627762,-161.232697 66.581863,-161.240738 66.553833,-161.280304 66.539978,-161.313477 66.534431,-161.381378 66.532761,-161.497284 66.533318,-161.716644 66.628311,-161.812775 66.674988,-161.872208 66.704567,-161.897797 66.728317,-161.888336 66.799988,-161.800293 66.899719,-161.721100 66.950676,-161.644180 66.963745,-161.616943 66.958038,-161.593872 66.953873,-161.568329 66.951660,-161.531815 66.950958,-161.498535 66.960464,-161.510849 66.984283,-161.537231 66.992752,-161.667786 67.020538,-161.690826 67.024704,-161.816101 67.047211,-161.860550 67.051651,-161.899170 67.051086,-162.258057 67.019440,-162.460800 66.998146,-162.442383 67.030884,-162.423050 67.050377,-162.403885 67.068130,-162.352478 67.120819,-162.341797 67.156685,-162.383606 67.163742,-162.412643 67.159149,-162.377136 67.145615,-162.401947 67.112762,-162.470230 67.062378,-162.559509 67.010406,-162.652359 67.010826,-162.686600 67.030228,-162.720276 67.051926,-162.752777 67.054565,-162.777802 67.053040,-162.816650 67.045822,-162.952789 67.030273,-163.013062 67.030548,-163.039185 67.032761,-163.143616 67.049713,-163.231659 67.058868,-163.257782 67.060806,-163.463318 67.080276,-163.665009 67.100815,-163.699982 67.106369,-163.727203 67.112206,-163.756683 67.125671,-163.769745 67.149719,-163.777924 67.175117,-163.775833 67.206512,-163.774734 67.229286,-163.781830 67.269157,-163.793335 67.300812,-163.826813 67.360954,-163.957657 67.494713,-163.987762 67.521652,-164.020020 67.546936,-164.048615 67.565811,-164.100830 67.597214,-164.124146 67.609985,-164.161133 67.623871,-164.251129 67.650818,-164.312225 67.668320,-164.498047 67.727768,-164.552490 67.755554,-164.710068 67.828743,-164.759293 67.821419,-164.796387 67.826935,-165.098602 67.943039,-165.209991 67.986374,-165.243042 68.001099,-165.271667 68.011108,-165.341095 68.033325,-165.361389 68.039154,-165.392792 68.047760,-165.479980 68.068329,-165.550842 68.080276,-165.586395 68.086105,-165.610809 68.089706,-165.688599 68.097488,-165.726379 68.101089,-165.794464 68.105545,-165.820557 68.108032,-165.861526 68.115128,-165.888916 68.121643,-165.919159 68.130814,-165.976517 68.151375,-165.999420 68.165268,-166.016113 68.179153,-166.036545 68.199432,-166.073608 68.218597,-166.101379 68.229431,-166.130554 68.239700,-166.218048 68.269714,-166.256958 68.283051,-166.293335 68.293457,-166.344452 68.303864,-166.379150 68.310532,-166.427490 68.318054,-166.608612 68.337204,-166.647247 68.341095,-166.674713 68.342758,-166.750305 68.342484,-166.793060 68.344147,-166.823624 68.348732,-166.757416 68.366074,-166.454559 68.418060,-166.513336 68.405243,-166.753189 68.361923,-166.715820 68.355820,-166.663330 68.351089,-166.589172 68.350266,-166.548477 68.353180,-166.372604 68.416763,-166.388596 68.434097,-166.302216 68.498596,-166.243866 68.553864,-166.225830 68.572495,-166.198334 68.696640,-166.189041 68.754440,-166.193405 68.789635,-166.204712 68.812195,-166.227203 68.845535,-166.232422 68.872337,-166.207489 68.883461,-166.168335 68.883881,-166.093597 68.882202,-165.881378 68.869980,-165.815277 68.863037,-165.730560 68.857208,-165.445831 68.860260,-165.309998 68.867203,-164.950287 68.888046,-164.800293 68.900543,-164.745544 68.905258,-164.713318 68.909424,-164.561127 68.921097,-164.411957 68.925537,-164.359711 68.928314,-164.324707 68.930542,-164.271942 68.935532,-164.239716 68.939423,-164.158630 68.955261,-164.107483 68.966385,-163.993317 68.991653,-163.904175 69.016937,-163.702789 69.085541,-163.645294 69.106934,-163.599731 69.125259,-163.560898 69.145058,-163.526398 69.166092,-163.506409 69.178864,-163.488892 69.192200,-163.441681 69.221649,-163.364990 69.268600,-163.342773 69.280823,-163.308624 69.296097,-163.281677 69.307205,-163.240540 69.341240,-163.216949 69.379700,-163.199982 69.404984,-163.179306 69.420677,-163.157928 69.420822,-163.257385 69.300987,-163.156952 69.352203,-163.120270 69.384720,-163.065002 69.509018,-163.063751 69.561798,-163.002502 69.675117,-162.973190 69.673866,-162.940399 69.694077,-162.939987 69.717216,-162.961945 69.723183,-162.982758 69.725266,-163.022858 69.730675,-163.003906 69.752777,-162.958878 69.780266,-162.841675 69.831940,-162.767517 69.859711,-162.671936 69.896103,-162.575287 69.938034,-162.514175 69.970825,-162.497635 69.984566,-162.480621 70.013245,-162.350967 70.110405,-162.286133 70.133606,-162.245270 70.147491,-162.196381 70.165543,-162.086670 70.216385,-162.062775 70.228592,-162.041672 70.244568,-162.016968 70.268463,-161.993622 70.283737,-161.961655 70.299843,-161.942230 70.307205,-161.882645 70.319016,-161.858887 70.318054,-161.766968 70.257225,-161.851898 70.209427,-161.867218 70.177475,-161.903900 70.174423,-161.941254 70.177063,-161.984009 70.189842,-162.013901 70.191093,-162.035004 70.187195,-162.070969 70.175117,-162.114212 70.154297,-161.864990 70.161377,-161.809830 70.180374,-161.785339 70.195877,-161.691833 70.230545,-161.640839 70.250549,-161.604294 70.255829,-161.474152 70.251389,-161.340820 70.254715,-161.306396 70.258041,-161.216644 70.271927,-161.173889 70.279434,-160.900574 70.335815,-160.875000 70.341370,-160.851654 70.347763,-160.773621 70.370529,-160.750580 70.377472,-160.475830 70.474701,-160.353607 70.523041,-160.334717 70.530548,-160.315552 70.537766,-160.163910 70.589706,-159.929092 70.586929,-159.924179 70.529846,-159.944458 70.515274,-160.070694 70.482208,-160.111115 70.479706,-160.193893 70.470123,-160.160141 70.462486,-160.096100 70.463608,-160.018616 70.471924,-160.006134 70.419983,-159.981659 70.368317,-159.836121 70.268326,-159.885986 70.394577,-159.863052 70.437622,-159.819458 70.484421,-159.760773 70.473732,-159.692505 70.466385,-159.654449 70.471603,-159.557220 70.491653,-159.400848 70.504990,-159.305649 70.530678,-159.564728 70.524429,-159.657547 70.503578,-159.729980 70.493317,-159.747223 70.497765,-159.846298 70.561020,-159.858459 70.591377,-159.918884 70.625259,-159.944992 70.633736,-159.976654 70.636383,-159.996643 70.635269,-160.036255 70.629974,-160.121582 70.612343,-160.110123 70.631371,-160.023071 70.662766,-159.947510 70.686371,-159.923889 70.692749,-159.819153 70.719986,-159.672363 70.796089,-159.628601 70.806366,-159.522797 70.828049,-159.303345 70.864151,-159.170975 70.877480,-159.208893 70.869431,-159.249146 70.867477,-159.300568 70.862198,-159.338333 70.856369,-159.367889 70.846100,-159.348328 70.841095,-159.234161 70.845543,-159.190842 70.852898,-159.164719 70.849297,-159.146896 70.822906,-159.194458 70.813599,-159.269745 70.812195,-159.307770 70.809708,-159.336395 70.804703,-159.445419 70.778183,-159.416656 70.765549,-159.295837 70.725540,-159.223877 70.704437,-159.109161 70.759995,-158.991089 70.787201,-158.920837 70.796371,-158.839447 70.792206,-158.690430 70.785400,-158.643341 70.787766,-158.611938 70.791931,-158.539169 70.810539,-158.502228 70.832214,-158.413055 70.834717,-158.353333 70.828873,-158.234985 70.824707,-158.161407 70.824997,-158.053345 70.829292,-157.979431 70.837494,-157.880463 70.856354,-157.786682 70.878586,-157.764191 70.884995,-157.544159 70.951385,-157.471924 70.976089,-157.275299 71.048874,-157.230835 71.068459,-157.191101 71.089157,-157.125275 71.129700,-157.081940 71.156647,-157.047379 71.182068,-157.024170 71.198029,-157.001404 71.210815,-156.841949 71.288315,-156.786407 71.311371,-156.756409 71.322220,-156.698334 71.338318,-156.596725 71.351440,-156.546661 71.305252,-156.440292 71.262360,-156.338898 71.264435,-156.275146 71.267906,-156.250000 71.266388,-156.193604 71.258331,-156.139191 71.249710,-156.107071 71.243179,-156.047012 71.208046,-155.986389 71.192474,-155.921661 71.198593,-155.846100 71.203049,-155.806946 71.204987,-155.765991 71.202217,-155.638062 71.184563,-155.592499 71.168320,-155.543350 71.111504,-155.550293 71.085686,-155.735809 71.000000,-155.830551 70.979980,-155.894318 70.972481,-155.957214 70.973038,-155.996094 70.972488,-156.086243 70.967903,-156.177292 70.917763,-156.140564 70.913879,-156.083740 70.920403,-156.058044 70.919983,-155.987350 70.900543,-155.946243 70.847694,-155.982971 70.826035,-155.973602 70.755829,-155.953613 70.756653,-155.902786 70.770546,-155.912949 70.788589,-155.925003 70.807480,-155.910706 70.822632,-155.887650 70.829025,-155.653900 70.844711,-155.616943 70.844437,-155.536667 70.931297,-155.391953 71.001801,-155.293182 71.017685,-155.247986 70.996925,-155.214996 70.987343,-155.186676 70.994148,-155.178757 71.017761,-155.198334 71.040260,-155.256348 71.066849,-155.274109 71.086433,-155.197784 71.118317,-155.094437 71.150131,-155.074432 71.148880,-155.048660 71.121414,-155.041397 71.047203,-155.083817 71.021935,-155.062088 71.010269,-155.015289 71.022072,-155.001785 71.101265,-154.974426 71.117065,-154.923615 71.110535,-154.821106 71.094986,-154.614151 71.021378,-154.595749 71.001930,-154.658066 70.915260,-154.680298 70.884155,-154.612625 70.827621,-154.568054 70.824432,-154.547791 70.824997,-154.421112 70.832764,-154.384186 70.832214,-154.351105 70.830276,-154.302917 70.822906,-154.253342 70.794563,-154.203613 70.776520,-154.164734 70.780273,-154.129974 70.789429,-154.001389 70.839432,-153.966385 70.855263,-153.937927 70.879562,-153.915009 70.889160,-153.883057 70.892487,-153.862762 70.893051,-153.728058 70.894150,-153.623047 70.889984,-153.590271 70.887772,-153.502228 70.887207,-153.384155 70.895264,-153.357208 70.900406,-153.322235 70.912766,-153.286957 70.921646,-153.250839 70.927208,-153.222504 70.928589,-153.201935 70.928864,-153.166962 70.927200,-152.945007 70.902206,-152.736664 70.833878,-152.734711 70.881927,-152.646973 70.886108,-152.610260 70.885269,-152.544464 70.880539,-152.511414 70.878036,-152.480560 70.874985,-152.435272 70.869980,-152.379150 70.861649,-152.277222 70.840546,-152.247223 70.833603,-152.217224 70.813042,-152.373596 70.747757,-152.508896 70.687614,-152.492691 70.646095,-152.435272 70.622208,-152.403900 70.612198,-152.371933 70.605957,-152.229858 70.594986,-152.184723 70.596649,-152.164459 70.596939,-152.130280 70.595261,-152.093613 70.590683,-152.077362 70.578392,-152.104584 70.568604,-152.315552 70.575546,-152.416656 70.581375,-152.493881 70.587212,-152.522247 70.587494,-152.543884 70.583878,-152.619461 70.558388,-152.525284 70.543594,-152.495285 70.544708,-152.351379 70.552765,-152.226379 70.548874,-152.099976 70.552200,-152.059311 70.555954,-152.033066 70.567619,-152.000137 70.569717,-151.736649 70.558594,-151.770294 70.498039,-151.803894 70.493317,-151.906387 70.482765,-151.966095 70.465263,-151.970261 70.445671,-151.881927 70.440262,-151.828064 70.441360,-151.798340 70.445251,-151.738312 70.445816,-151.613190 70.445251,-151.521942 70.439423,-151.475555 70.434708,-151.386963 70.424149,-151.358612 70.420258,-151.334442 70.414993,-151.273346 70.394440,-151.229858 70.372963,-151.179596 70.374420,-151.197510 70.394989,-151.207001 70.422409,-151.176529 70.442963,-151.015015 70.460815,-150.779999 70.502213,-150.615829 70.506378,-150.525574 70.505264,-150.367722 70.475571,-150.396957 70.430672,-150.311951 70.426376,-150.124146 70.437065,-149.959167 70.487480,-149.906128 70.507217,-149.879990 70.514999,-149.543060 70.511658,-149.469147 70.499710,-149.383331 70.480545,-149.359009 70.489571,-149.320831 70.499146,-149.174713 70.490814,-149.045624 70.464157,-148.992493 70.442749,-148.822235 70.411102,-148.802216 70.410812,-148.768066 70.412766,-148.737762 70.416092,-148.694031 70.413734,-148.672241 70.410812,-148.595276 70.395538,-148.519318 70.366508,-148.498398 70.343246,-148.499313 70.321373,-148.372757 70.310677,-148.341370 70.316940,-148.302643 70.331238,-148.270416 70.349770,-148.222778 70.359146,-148.139587 70.354851,-148.112213 70.346939,-148.081665 70.329987,-147.815002 70.267761,-147.763336 70.225540,-147.714996 70.214432,-147.689728 70.209152,-147.634460 70.207214,-147.489990 70.204712,-147.336121 70.199707,-147.269470 70.193314,-147.186661 70.167343,-147.156250 70.163742,-147.023895 70.163040,-146.980270 70.164429,-146.762238 70.181656,-146.538605 70.194427,-146.457764 70.191650,-146.261688 70.179428,-146.169724 70.173317,-146.125702 70.164146,-146.103470 70.154572,-146.080292 70.152206,-145.991806 70.148743,-145.963898 70.148880,-145.904449 70.150543,-145.803619 70.150269,-145.748047 70.128036,-145.686676 70.108032,-145.600830 70.081665,-145.425293 70.041092,-145.196655 70.001938,-145.024872 69.987068,-145.003906 69.983597,-144.981659 69.977478,-144.952209 69.968323,-144.878052 69.983047,-144.707489 69.972214,-144.672241 69.972488,-144.640289 69.974426,-144.611938 69.977768,-144.587219 69.982483,-144.566101 69.988876,-144.518616 70.010963,-144.386673 70.039429,-144.339722 70.038879,-144.201111 70.039978,-144.162918 70.043037,-144.137711 70.055397,-144.065002 70.079163,-144.041962 70.084717,-143.731094 70.096519,-143.704712 70.088318,-143.666397 70.083466,-143.603043 70.087212,-143.520294 70.097214,-143.411407 70.096939,-143.301392 70.072769,-143.294037 70.112480,-143.215546 70.110260,-143.024719 70.085266,-142.888199 70.075409,-142.642517 70.016098,-142.523071 69.963608,-142.423065 69.919144,-142.369446 69.890274,-142.261673 69.847488,-142.221176 69.849495,-142.163635 69.853317,-142.118881 69.851234,-142.098602 69.847488,-142.066650 69.837769,-142.035339 69.820122,-141.947784 69.794983,-141.879150 69.795532,-141.782227 69.786377,-141.731110 69.775543,-141.707764 69.769714,-141.565826 69.728317,-141.534180 69.718597,-141.493347 69.698875,-141.457367 69.671654,-141.434738 69.656097,-141.382080 69.639709,-141.360809 69.636383,-141.326935 69.633331,-141.290283 69.632202,-141.260284 69.634430,-141.219711 69.670265,-141.246368 69.677765,-141.310699 69.688522,-141.264328 69.689423,-141.241089 69.686646,-141.154175 69.673309,-141.002991 69.642365,-141.000854 69.532211,-141.000580 69.432480,-141.000854 68.965546,-141.001678 68.532761,-141.001953 68.232758,-141.001953 68.065811,-141.001953 67.865814,-141.000000 67.732758,-141.000580 67.532486,-141.002228 67.299149,-141.001678 67.066376,-141.000580 66.866089,-141.000854 66.666382,-141.001678 66.499420,-141.001953 66.099426,-141.001953 65.699417,-141.000305 65.232758,-141.000305 65.166092,-141.001953 65.132751,-141.000305 64.199707,-141.000305 63.966385,-141.001953 63.832771,-141.001404 63.099998,-141.000305 62.733047,-141.001678 60.966385,-141.000305 60.933052,-141.001129 60.399437,-141.000580 60.366661,-140.995544 60.307213,-140.946381 60.297775,-140.521393 60.222214,-140.497498 60.251244,-140.471924 60.283882,-140.450836 60.309715,-140.005585 60.193878,-139.979431 60.187767,-139.913055 60.220825,-139.866394 60.244438,-139.771667 60.292496,-139.676666 60.340546,-139.519470 60.344711,-139.066879 60.344715,-139.082214 60.287498,-139.129456 60.201103,-139.155273 60.154991,-139.186401 60.095551,-139.161407 60.070274,-139.116394 60.041382,-139.047791 59.997490,-138.971924 59.978600,-138.690277 59.906937,-138.675018 59.866936,-138.667007 59.838394,-138.650986 59.810131,-138.615814 59.774162,-138.538605 59.732208,-138.491089 59.708328,-138.303619 59.613052,-138.117767 59.516663,-137.910278 59.408043,-137.590820 59.238602,-137.566101 59.186935,-137.545288 59.143051,-137.499146 59.041382,-137.483734 58.990269,-137.497223 58.964157,-137.506317 58.937904,-137.497635 58.914436,-137.471802 58.906654,-137.445007 58.907494,-137.423889 58.912766,-137.392792 58.928329,-137.338898 58.965546,-137.314178 58.981102,-137.296112 58.989990,-137.251678 59.006104,-137.033081 59.077492,-136.969727 59.098328,-136.941956 59.109436,-136.888336 59.131935,-136.808899 59.165268,-136.719727 59.165268,-136.611389 59.164711,-136.583893 59.163322,-136.558350 59.186378,-136.486526 59.255829,-136.462631 59.295963,-136.462494 59.372215,-136.464172 59.414154,-136.463623 59.469711,-136.371643 59.452492,-136.296524 59.473598,-136.233887 59.525826,-136.239166 59.561378,-136.298340 59.583603,-136.345123 59.601662,-136.310547 59.612495,-136.207764 59.639435,-136.160004 59.646660,-136.120819 59.651657,-136.071381 59.657494,-135.949158 59.669159,-135.823334 59.705551,-135.506134 59.793884,-135.473602 59.801933,-135.336121 59.726654,-135.177490 59.636940,-135.154175 59.627213,-135.126511 59.622211,-135.097229 59.621376,-135.014465 59.567497,-135.015015 59.540550,-135.017792 59.498878,-135.028137 59.469296,-135.063324 59.458046,-135.079712 59.444710,-135.091675 59.426941,-134.951935 59.279991,-134.738892 59.250275,-134.688049 59.243324,-134.673477 59.207493,-134.650848 59.185547,-134.566406 59.130547,-134.532227 59.132210,-134.466736 59.129089,-134.382782 59.053604,-134.325562 58.971100,-134.327499 58.925476,-134.238327 58.854439,-134.087494 58.808327,-133.826935 58.726097,-133.808350 58.709991,-133.735809 58.644714,-133.558899 58.528046,-133.429993 58.459160,-133.387909 58.412064,-133.408905 58.400269,-133.430298 58.359993,-133.361115 58.280548,-133.306122 58.257217,-133.233612 58.211380,-133.211395 58.196381,-133.189865 58.180130,-133.136963 58.135826,-133.108398 58.085754,-133.091248 58.040554,-133.070831 58.012215,-133.055557 57.997074,-133.038605 57.982906,-132.994995 57.951660,-132.964722 57.933327,-132.933197 57.909435,-132.877350 57.859440,-132.815903 57.798046,-132.795975 57.771381,-132.786667 57.751938,-132.762848 57.720127,-132.619446 57.583328,-132.498199 57.470409,-132.471924 57.451103,-132.451111 57.435265,-132.374435 57.375130,-132.354156 57.354439,-132.226654 57.204712,-132.261398 57.168880,-132.324234 57.089157,-132.221100 57.068054,-132.027496 57.036385,-132.036682 57.013054,-132.061951 56.959717,-132.091949 56.893608,-132.103058 56.866661,-131.861725 56.795830,-131.858032 56.718880,-131.824371 56.598396,-131.611115 56.602219,-131.578888 56.603325,-131.548615 56.599438,-131.314453 56.509995,-131.290009 56.500549,-131.213318 56.469158,-131.164734 56.445267,-131.144470 56.434715,-131.125824 56.424164,-131.062775 56.400826,-130.920013 56.382492,-130.847229 56.374435,-130.774445 56.366104,-130.755859 56.353050,-130.720551 56.325554,-130.627197 56.258606,-130.560715 56.250000,-130.532776 56.246384,-130.484711 56.239433,-130.461945 56.235268,-130.447510 56.206383,-130.365265 56.123878,-130.229156 56.090271,-130.088593 56.118050,-130.053894 56.075554,-130.014465 56.024853,-130.014740 55.909988,-130.015076 55.909180,-130.026810 55.894993,-130.103745 55.821384,-130.135406 55.808739,-130.174438 55.757217,-130.143890 55.541382,-130.047516 55.379990,-129.993652 55.281036,-130.077499 55.225685,-130.101929 55.205551,-130.135559 55.171379,-130.164734 55.126381,-130.220001 55.053879,-130.242218 55.026100,-130.277222 54.983604,-130.365967 54.904434,-130.498047 54.831383,-130.579437 54.796104,-130.709259 54.767876,-130.718262 54.798561,-130.706390 54.844711,-130.742661 54.955093,-130.750000 54.872356,-130.738312 54.852219,-130.750961 54.820984,-130.808472 54.771519,-130.837769 54.767284,-130.868866 54.771935,-130.893890 54.780548,-130.910553 54.791939,-130.930969 54.821796,-130.937225 54.855553,-130.932495 54.871933,-130.928619 54.932770,-130.934586 54.958324,-130.984985 54.989433,-131.007797 55.000202,-130.982208 55.051102,-130.964722 55.063049,-130.835419 55.103882,-130.800674 55.106659,-130.702789 55.116936,-130.553207 55.223461,-130.474152 55.325932,-130.504456 55.315826,-130.549744 55.282211,-130.565002 55.267494,-130.585007 55.229572,-130.599426 55.214157,-130.727783 55.126381,-130.812653 55.141800,-130.873459 55.115688,-130.894318 55.097076,-130.920425 55.089020,-130.964722 55.084991,-131.010071 55.087975,-131.058762 55.127487,-131.066452 55.186447,-131.049988 55.204994,-130.931534 55.284645,-130.880371 55.289173,-130.794159 55.286659,-130.642227 55.287216,-130.616104 55.294300,-130.658966 55.344849,-130.685547 55.338188,-130.717010 55.307766,-130.861267 55.310062,-130.871918 55.336937,-130.874695 55.413048,-130.872223 55.509720,-130.869019 55.547077,-130.866638 55.578049,-130.870544 55.604439,-130.886398 55.707909,-130.912506 55.741104,-131.025848 55.834717,-131.113739 55.901379,-131.169464 55.941658,-131.164230 55.985142,-131.141403 56.002602,-131.094818 56.022102,-131.055847 56.056381,-131.012787 56.106522,-131.074432 56.094154,-131.142380 56.050827,-131.171402 56.031994,-131.207214 56.011410,-131.326675 55.964302,-131.370132 55.961384,-131.404037 55.994579,-131.478607 55.975266,-131.546387 55.951935,-131.732635 55.885967,-131.756256 55.879711,-131.802643 55.881798,-131.881378 55.863609,-131.900574 55.855270,-131.874847 55.838463,-131.852631 55.834019,-131.820557 55.830551,-131.759109 55.814091,-131.817230 55.663322,-131.836945 55.635826,-131.923615 55.534439,-131.954987 55.501106,-131.962494 55.498604,-132.024719 55.527771,-132.062790 55.543331,-132.112762 55.554993,-132.143066 55.567497,-132.168060 55.584438,-132.186935 55.606243,-132.245270 55.723877,-132.171448 55.799786,-132.104721 55.805546,-132.048340 55.822220,-132.071381 55.862770,-132.054657 55.942833,-132.021255 55.956520,-131.975967 55.955826,-131.947495 55.964504,-131.940842 56.010479,-131.961655 56.055202,-131.966644 56.081383,-131.956787 56.164921,-131.769745 56.196938,-131.825287 56.213326,-131.900848 56.226933,-131.919174 56.239990,-131.933319 56.257774,-131.959732 56.296520,-131.968323 56.325756,-131.993042 56.357773,-132.037094 56.373463,-132.066101 56.378326,-132.186127 56.422768,-132.341660 56.523323,-132.351059 56.543255,-132.337982 56.598061,-132.315735 56.633373,-132.363434 56.625351,-132.409302 56.608837,-132.438644 56.604252,-132.493866 56.611107,-132.523895 56.618465,-132.551117 56.637703,-132.524445 56.714714,-132.505859 56.726097,-132.465271 56.745544,-132.415833 56.772217,-132.364975 56.817146,-132.385696 56.822357,-132.422638 56.811310,-132.458893 56.782211,-132.498901 56.750690,-132.535004 56.755829,-132.574158 56.765831,-132.643066 56.788887,-132.688049 56.808044,-132.768890 56.843880,-132.856110 56.931381,-132.842911 56.966103,-132.779648 56.958813,-132.765228 56.981728,-132.804138 57.083813,-132.847565 57.060200,-132.905273 57.033051,-133.127197 57.079994,-133.142242 57.116661,-133.123764 57.151447,-133.168259 57.162975,-133.255844 57.116241,-133.283752 57.099228,-133.314728 57.101936,-133.340546 57.110550,-133.387634 57.129017,-133.401398 57.135826,-133.437637 57.140411,-133.488586 57.166100,-133.508362 57.193604,-133.497986 57.255203,-133.468048 57.280548,-133.444153 57.282494,-133.317993 57.281132,-133.289185 57.276714,-133.242493 57.275269,-133.083893 57.321938,-133.065964 57.346794,-133.113617 57.328331,-133.229843 57.313881,-133.351013 57.328659,-133.407501 57.338043,-133.441315 57.355412,-133.506821 57.484295,-133.460876 57.540878,-133.435501 57.554840,-133.412231 57.556549,-133.332565 57.575897,-133.317856 57.590057,-133.357483 57.591934,-133.447983 57.582630,-133.481567 57.575966,-133.504486 57.571049,-133.549164 57.565826,-133.599365 57.574509,-133.659409 57.627663,-133.640564 57.696381,-133.561111 57.708881,-133.166946 57.573189,-133.121735 57.544090,-133.085831 57.518326,-133.041733 57.503468,-133.006424 57.513950,-133.133331 57.586380,-133.180573 57.616936,-133.201111 57.620270,-133.320282 57.661377,-133.358887 57.677216,-133.517792 57.745827,-133.544525 57.768883,-133.554443 57.824715,-133.544342 57.908150,-133.429031 57.907001,-133.264191 57.875549,-133.131104 57.853329,-133.183334 57.891380,-133.445557 57.918602,-133.525848 57.923607,-133.557648 57.923603,-133.591064 57.911049,-133.640564 57.870827,-133.620468 57.825062,-133.632782 57.796661,-133.658905 57.784580,-133.700607 57.791523,-133.804169 57.897217,-133.813019 57.972935,-133.760635 58.029938,-133.697235 58.103329,-133.680206 58.145962,-133.748962 58.132908,-133.807770 58.047493,-133.829300 58.008713,-133.879868 57.991543,-133.913345 57.980129,-133.975555 58.013885,-134.012512 58.040550,-134.059723 58.078880,-134.069458 58.101105,-134.086044 58.189018,-134.051941 58.253326,-133.995270 58.340271,-134.008957 58.389935,-133.928482 58.491383,-133.902786 58.505692,-133.879974 58.509438,-133.858337 58.509438,-133.817505 58.503193,-133.793747 58.506107,-133.774033 58.514996,-133.859436 58.521660,-133.881104 58.521378,-133.924713 58.512215,-133.972702 58.497837,-134.043884 58.393211,-134.099228 58.240269,-134.149246 58.200478,-134.180557 58.197071,-134.239777 58.208675,-134.383636 58.286942,-134.489304 58.346519,-134.518478 58.355690,-134.539734 58.359161,-134.575012 58.352219,-134.640564 58.356102,-134.757645 58.381969,-134.771118 58.435822,-134.773483 58.460548,-134.947357 58.631939,-134.975006 58.645828)),((-164.770020 66.530823,-164.779602 66.525681,-164.864166 66.505264,-164.876923 66.502777,-165.047791 66.477203,-165.364441 66.426376,-165.468460 66.412903,-165.454163 66.421371,-165.433319 66.427475,-165.420837 66.429977,-165.144745 66.481369,-165.117493 66.486099,-165.019745 66.501663,-164.763550 66.536163,-164.770020 66.530823)),((-166.210541 66.208878,-166.287781 66.190262,-166.567230 66.122757,-166.587769 66.116379,-166.663223 66.105293,-166.598328 66.133606,-166.466095 66.174988,-166.443604 66.180817,-166.382477 66.194138,-166.321106 66.207489,-166.255585 66.219711,-166.222778 66.223038,-166.181122 66.223038,-166.171539 66.219017,-166.210541 66.208878)),((-168.873322 63.152771,-169.149185 63.199570,-169.206955 63.203667,-169.278351 63.195267,-169.321152 63.184574,-169.512390 63.094711,-169.562790 63.057903,-169.575302 63.041939,-169.582565 63.015465,-169.594757 62.979706,-169.643097 62.947769,-169.670425 62.944149,-169.749619 62.962490,-169.758087 63.008881,-169.735840 63.057213,-169.789734 63.112206,-169.805298 63.125259,-169.893372 63.151791,-169.967377 63.153446,-169.922195 63.128006,-169.973358 63.151932,-170.082214 63.192757,-170.151428 63.182487,-170.258087 63.199501,-170.224365 63.206310,-170.211823 63.250965,-170.234009 63.278946,-170.509445 63.375263,-170.568604 63.390831,-170.607834 63.397556,-170.640717 63.394993,-170.785995 63.422077,-170.806961 63.429989,-170.833572 63.453182,-170.862915 63.461376,-171.006104 63.435818,-170.959381 63.428513,-170.853180 63.418488,-170.828064 63.414986,-170.627502 63.378052,-170.595001 63.371933,-170.543640 63.359711,-170.485840 63.341103,-170.466766 63.334183,-170.401123 63.303879,-170.363800 63.284119,-170.341888 63.271126,-170.315857 63.253876,-170.296112 63.238045,-170.318909 63.254715,-170.362213 63.282494,-170.403900 63.304436,-170.481491 63.338528,-170.551147 63.360550,-170.581970 63.368050,-170.814911 63.410965,-170.863251 63.418510,-170.960846 63.427773,-171.018341 63.431107,-171.101608 63.431656,-171.241364 63.398872,-171.264740 63.392357,-171.283508 63.379990,-171.304443 63.358330,-171.325867 63.339989,-171.426941 63.317772,-171.455002 63.314575,-171.549164 63.327766,-171.683075 63.363884,-171.709442 63.371368,-171.738892 63.380547,-171.802521 63.416374,-171.824738 63.443047,-171.850830 63.508606,-171.840973 63.574295,-171.805725 63.638184,-171.764313 63.646664,-171.741653 63.666378,-171.724457 63.750267,-171.729172 63.789371,-171.663223 63.790199,-171.630310 63.774437,-171.633911 63.752140,-171.643768 63.709564,-171.540009 63.613880,-171.465576 63.606659,-171.374695 63.604706,-171.351105 63.607491,-171.317444 63.620335,-171.346237 63.629154,-171.374725 63.629356,-171.325317 63.633881,-171.272278 63.628876,-171.210297 63.620827,-171.186157 63.617203,-171.107330 63.602768,-171.063324 63.585258,-170.974457 63.573318,-170.929993 63.571106,-170.908920 63.572212,-170.781143 63.614849,-170.736053 63.636097,-170.711121 63.652901,-170.485840 63.703316,-170.457764 63.703606,-170.329163 63.696091,-170.300018 63.694153,-170.282379 63.681866,-170.192505 63.635262,-170.169891 63.627903,-170.139191 63.623604,-170.102997 63.620964,-170.066101 63.595543,-170.051392 63.575829,-170.032257 63.533875,-169.923370 63.478600,-169.844452 63.451378,-169.716553 63.437904,-169.653900 63.436646,-169.597260 63.421097,-169.572784 63.408321,-169.560074 63.372345,-169.524445 63.354156,-169.488892 63.348595,-169.454193 63.345680,-169.416824 63.348183,-169.253632 63.337494,-169.203766 63.304573,-169.170013 63.298187,-169.134460 63.296944,-169.109955 63.298325,-169.074097 63.314156,-169.100006 63.326241,-169.131104 63.330269,-169.158936 63.330269,-169.212097 63.340191,-169.189453 63.344147,-169.045868 63.341370,-168.962799 63.336098,-168.896698 63.330269,-168.717224 63.305817,-168.700867 63.290543,-168.716553 63.230541,-168.797241 63.171654,-168.815323 63.162621,-168.850006 63.155266,-168.873322 63.152771)),((-162.349426 63.588600,-162.377472 63.544441,-162.562500 63.538605,-162.607208 63.543884,-162.680695 63.556656,-162.693054 63.561661,-162.703613 63.571663,-162.701660 63.581665,-162.676666 63.603325,-162.663345 63.613747,-162.652222 63.619156,-162.640839 63.621658,-162.561951 63.635269,-162.420288 63.637497,-162.397522 63.635269,-162.376923 63.631378,-162.340897 63.596241,-162.349426 63.588600)),((-148.029724 60.927773,-148.022797 60.925552,-147.964157 60.902493,-147.939453 60.884163,-147.931396 60.874435,-147.912369 60.817284,-147.928894 60.806938,-148.018341 60.789719,-148.106659 60.791664,-148.122070 60.794716,-148.133621 60.802773,-148.134323 60.827496,-148.125275 60.861382,-148.104431 60.914715,-148.065002 60.926102,-148.042236 60.928604,-148.029724 60.927773)),((-148.138336 60.756104,-148.123322 60.749718,-148.108322 60.734989,-148.094574 60.677494,-148.098053 60.665966,-148.119141 60.652214,-148.145004 60.640968,-148.157501 60.642494,-148.223053 60.698601,-148.230682 60.711662,-148.232086 60.723598,-148.214172 60.754440,-148.194458 60.758049,-148.169159 60.759163,-148.154999 60.758888,-148.138336 60.756104)),((-145.780579 60.573883,-145.917511 60.527489,-146.056396 60.488045,-146.129425 60.470268,-146.246948 60.454994,-146.259460 60.454712,-146.319717 60.457493,-146.328064 60.463608,-146.318893 60.496796,-146.304718 60.510551,-146.294464 60.515831,-146.278625 60.518883,-146.196960 60.524712,-146.104706 60.539162,-145.963745 60.582912,-145.941956 60.588882,-145.767792 60.616386,-145.751328 60.593044,-145.765564 60.580826,-145.780579 60.573883)),((-172.280029 60.302773,-172.313324 60.326935,-172.330429 60.335686,-172.343872 60.339432,-172.356384 60.340546,-172.382507 60.341660,-172.486664 60.341103,-172.517548 60.336372,-172.543335 60.328873,-172.561951 60.324715,-172.586945 60.323875,-172.599152 60.324997,-172.726532 60.369015,-172.737213 60.374161,-172.748077 60.388596,-172.768097 60.399437,-172.834442 60.428040,-172.936707 60.467484,-172.981384 60.478600,-173.000610 60.483040,-173.051010 60.495819,-173.033630 60.549431,-173.011414 60.563042,-172.948639 60.597626,-172.927826 60.604156,-172.914886 60.601517,-172.914185 60.585541,-172.925278 60.573460,-172.928482 60.561653,-172.920563 60.548882,-172.900574 60.525269,-172.885040 60.512497,-172.874695 60.504166,-172.864197 60.495827,-172.844452 60.484993,-172.749176 60.449425,-172.733063 60.443604,-172.594177 60.401093,-172.576660 60.396103,-172.554749 60.392769,-172.520294 60.388329,-172.481689 60.386101,-172.455704 60.389854,-172.434723 60.396378,-172.423615 60.397484,-172.392548 60.394993,-172.379730 60.390831,-172.208084 60.315128,-172.235260 60.306931,-172.256439 60.304153,-172.280029 60.302773)),((-147.633636 60.422493,-147.690002 60.411102,-147.729980 60.390686,-147.711945 60.376099,-147.696671 60.377075,-147.685272 60.381660,-147.651123 60.391937,-147.623047 60.388325,-147.629425 60.367767,-147.635559 60.356941,-147.723602 60.209991,-147.757507 60.167908,-147.770844 60.164436,-147.789444 60.165550,-147.826111 60.182213,-147.909729 60.234718,-147.898346 60.283607,-147.875824 60.332214,-147.856659 60.371658,-147.817780 60.431664,-147.779861 60.478737,-147.699020 60.510410,-147.626511 60.473045,-147.615829 60.429852,-147.625275 60.424164,-147.633636 60.422493)),((-146.096954 60.392769,-146.168060 60.381378,-146.310272 60.351662,-146.347229 60.343323,-146.415833 60.323326,-146.457489 60.309990,-146.473602 60.304436,-146.517242 60.284996,-146.576660 60.245544,-146.597351 60.238880,-146.617065 60.241104,-146.627777 60.246101,-146.666962 60.267769,-146.677902 60.283325,-146.629669 60.308659,-146.598984 60.319992,-146.555664 60.335663,-146.535080 60.342075,-146.485550 60.365688,-146.587753 60.367516,-146.601837 60.364433,-146.619659 60.354893,-146.607361 60.351391,-146.616760 60.345352,-146.630005 60.345268,-146.698761 60.350269,-146.715820 60.358887,-146.722824 60.376236,-146.715546 60.391663,-146.705566 60.407768,-146.696106 60.416939,-146.618179 60.471657,-146.603592 60.478184,-146.580841 60.482491,-146.535706 60.481518,-146.439453 60.463051,-146.365829 60.443741,-146.363052 60.411934,-146.353882 60.407494,-146.339996 60.407211,-146.310272 60.412491,-146.290283 60.416100,-146.200836 60.431938,-146.167236 60.435265,-146.154724 60.435547,-146.140839 60.434990,-146.124985 60.432217,-146.080551 60.403740,-146.096954 60.392769)),((-166.109161 60.410271,-166.110275 60.402069,-166.065308 60.329433,-166.029480 60.323044,-165.979187 60.318604,-165.922806 60.319298,-165.909622 60.334854,-165.872314 60.344360,-165.795319 60.337212,-165.775879 60.332207,-165.710846 60.308037,-165.684341 60.296520,-165.674713 60.275551,-165.679749 60.211655,-165.688324 60.153870,-165.669464 60.059151,-165.639496 59.996094,-165.607101 59.969154,-165.585556 59.973248,-165.543076 59.980263,-165.555435 59.928738,-165.574158 59.913181,-165.612213 59.902206,-165.661438 59.904709,-165.728882 59.909981,-165.786682 59.902206,-165.886719 59.873871,-166.118179 59.851246,-166.176544 59.863045,-166.209198 59.857491,-166.231766 59.839504,-166.194138 59.825542,-166.145905 59.820129,-166.108887 59.805267,-166.088089 59.770924,-166.122528 59.755272,-166.167267 59.753319,-166.193481 59.757210,-166.253113 59.795429,-166.296265 59.817268,-166.412231 59.851929,-166.440277 59.855274,-166.475830 59.850822,-166.598083 59.850407,-166.958649 59.974991,-166.997772 59.998871,-167.079590 59.992626,-167.130447 59.998875,-167.161133 60.013329,-167.263367 60.066093,-167.316437 60.095543,-167.418060 60.189423,-167.404022 60.205826,-167.356384 60.222481,-167.316986 60.229706,-167.275879 60.231934,-167.201935 60.233330,-167.174469 60.231377,-167.071960 60.223877,-166.931671 60.207497,-166.894745 60.205826,-166.833069 60.206726,-166.794525 60.239849,-166.804581 60.269573,-166.688629 60.322220,-166.495850 60.378876,-166.459869 60.384438,-166.425598 60.380260,-166.316101 60.374985,-166.200317 60.392220,-166.150864 60.430546,-166.118118 60.421452,-166.109161 60.410271)),((-145.088043 60.399437,-145.115540 60.314159,-145.126526 60.305687,-145.141388 60.304436,-145.216644 60.310547,-145.244720 60.317772,-145.280838 60.332355,-145.258911 60.344994,-145.113037 60.409431,-145.098328 60.415543,-145.084442 60.414436,-145.088043 60.399437)),((-147.978607 60.371933,-147.983887 60.353882,-148.010559 60.301659,-148.020432 60.289165,-148.033630 60.285553,-148.079437 60.282768,-148.091949 60.282494,-148.104431 60.283333,-148.140442 60.304993,-148.142654 60.317215,-148.133636 60.329994,-148.084717 60.360825,-148.071655 60.368050,-148.026672 60.379715,-148.000000 60.385269,-147.986099 60.385269,-147.978607 60.371933)),((-146.937775 60.286385,-146.963898 60.258888,-146.984711 60.241661,-147.092773 60.193047,-147.129974 60.177490,-147.181244 60.158741,-147.214172 60.144440,-147.227203 60.137215,-147.238892 60.129158,-147.482498 59.944019,-147.487350 59.933327,-147.480560 59.923187,-147.531128 59.851936,-147.713898 59.814438,-147.849976 59.776939,-147.860809 59.775826,-147.871918 59.776100,-147.887360 59.778603,-147.910278 59.792564,-147.893555 59.842770,-147.792236 59.930824,-147.671661 60.006386,-147.604431 60.027214,-147.475555 60.078606,-147.445831 60.091103,-147.431396 60.097488,-147.404175 60.111382,-147.381790 60.129505,-147.375275 60.145546,-147.336945 60.178879,-147.202209 60.268883,-147.209305 60.292492,-147.201111 60.346657,-147.193604 60.353325,-147.157501 60.369713,-147.131927 60.377213,-147.112213 60.380821,-147.094864 60.380268,-146.922791 60.306797,-146.937775 60.286385)),((-148.036957 60.184158,-148.077484 60.128044,-148.086945 60.108604,-148.088882 60.091656,-148.104156 60.073326,-148.154877 60.040272,-148.208618 60.023048,-148.229156 60.019714,-148.251404 60.017494,-148.286957 60.020546,-148.307083 60.027634,-148.300293 60.055550,-148.224426 60.108330,-148.056534 60.193737,-148.035843 60.187004,-148.036957 60.184158)),((-147.876648 60.103882,-147.944458 60.076385,-148.120270 59.995411,-148.138763 59.998188,-148.141129 60.016106,-148.099426 60.061104,-147.963745 60.153324,-147.888474 60.115131,-147.876648 60.103882)),((-147.823883 60.049164,-147.829987 60.039719,-147.847778 60.020271,-147.880829 59.995827,-147.893890 59.988327,-147.915009 59.978600,-147.930298 59.972488,-148.022934 59.947628,-148.042236 59.947350,-148.043762 59.958603,-148.028900 59.975548,-148.000305 59.995544,-147.883331 60.067215,-147.850128 60.081524,-147.819870 60.070969,-147.817078 60.059711,-147.823883 60.049164)),((-144.238037 59.987770,-144.255585 59.983047,-144.303894 59.966103,-144.333618 59.952774,-144.411133 59.916382,-144.420837 59.907211,-144.455261 59.882767,-144.542236 59.829720,-144.562775 59.819443,-144.589294 59.809021,-144.601379 59.810822,-144.556808 59.861385,-144.523621 59.883049,-144.503906 59.894440,-144.442505 59.925270,-144.372498 59.958603,-144.351379 59.968597,-144.278900 59.999161,-144.261414 60.003883,-144.231659 60.008606,-144.210907 60.003815,-144.220551 59.993050,-144.238037 59.987770)),((-153.393066 59.402489,-153.354431 59.380821,-153.345840 59.361938,-153.372498 59.344994,-153.386688 59.338326,-153.406815 59.331387,-153.503632 59.325829,-153.515839 59.326103,-153.533905 59.330551,-153.552078 59.338047,-153.552216 59.364716,-153.518753 59.385136,-153.442505 59.410545,-153.431946 59.412209,-153.403076 59.406937,-153.393066 59.402489)),((-150.609711 59.380821,-150.612213 59.368599,-150.622498 59.353325,-150.631927 59.344437,-150.642517 59.336380,-150.654449 59.328880,-150.688339 59.308464,-150.714447 59.305824,-150.764313 59.317913,-150.775986 59.325825,-150.690979 59.404160,-150.677490 59.406380,-150.666656 59.404991,-150.638336 59.399162,-150.619278 59.391663,-150.609711 59.380821)),((-161.113098 58.655273,-161.060272 58.701797,-161.042236 58.709991,-160.947784 58.740273,-160.936127 58.741936,-160.884186 58.746384,-160.864166 58.750832,-160.847229 58.756386,-160.775299 58.783333,-160.759460 58.792217,-160.746368 58.802216,-160.689789 58.814716,-160.902496 58.578331,-160.911682 58.569717,-160.925568 58.563049,-160.943878 58.558044,-160.956940 58.556938,-161.088043 58.556934,-161.086121 58.585823,-161.113098 58.655273)),((-152.342224 58.593323,-152.376923 58.563324,-152.452911 58.495270,-152.464447 58.484436,-152.477203 58.477486,-152.493866 58.472214,-152.505585 58.471375,-152.526672 58.473877,-152.545288 58.477486,-152.622482 58.501526,-152.633743 58.509441,-152.658066 58.545410,-152.560822 58.580826,-152.478607 58.607216,-152.399994 58.631104,-152.381927 58.635551,-152.368591 58.635826,-152.348602 58.629295,-152.339996 58.602219,-152.342224 58.593323)),((-152.695831 58.053322,-152.771667 57.998329,-152.782516 57.993603,-152.852219 57.992908,-152.913910 58.010826,-153.006821 58.039299,-153.032501 58.049721,-153.038055 58.053604,-153.069733 58.090546,-153.138062 58.101105,-153.148621 58.102219,-153.168884 58.111938,-153.220825 58.153603,-153.230408 58.166103,-153.221252 58.193600,-153.209991 58.204437,-153.197510 58.211662,-153.176529 58.216522,-153.089722 58.199158,-153.012512 58.179161,-152.915283 58.166382,-152.902237 58.167492,-152.948059 58.195408,-153.016113 58.222763,-153.071533 58.237492,-153.104309 58.261665,-153.050980 58.300133,-153.037506 58.303604,-153.012787 58.303604,-152.797775 58.282772,-152.791382 58.374161,-152.788055 58.412209,-152.719452 58.455551,-152.654175 58.478043,-152.638611 58.479713,-152.546661 58.460548,-152.406952 58.363186,-152.351379 58.420547,-152.301941 58.424164,-152.281952 58.421104,-151.983047 58.343601,-151.965683 58.323326,-151.963058 58.278049,-151.972778 58.233047,-151.991364 58.215828,-152.061401 58.166939,-152.080292 58.156380,-152.099991 58.149574,-152.116089 58.147491,-152.191681 58.174438,-152.222916 58.202633,-152.218887 58.212074,-152.217773 58.223881,-152.240967 58.262218,-152.274185 58.262218,-152.303619 58.252777,-152.313614 58.247913,-152.367355 58.194298,-152.320984 58.151798,-152.293625 58.153046,-152.277222 58.129436,-152.403900 58.119987,-152.488586 58.124435,-152.594147 58.132492,-152.598602 58.121658,-152.626373 58.078606,-152.656128 58.060272,-152.695831 58.053322)),((-133.874146 57.489159,-133.864716 57.458328,-134.002930 57.487492,-134.049164 57.491104,-134.056259 57.465546,-133.988724 57.452496,-133.889725 57.424366,-133.862625 57.365547,-133.943192 57.302979,-133.972504 57.301102,-134.043060 57.329437,-134.064102 57.353466,-134.171249 57.380894,-134.099976 57.296104,-134.076691 57.269020,-134.163910 57.189156,-134.477707 57.029087,-134.576385 57.027214,-134.593872 57.037216,-134.620270 57.110828,-134.613312 57.224991,-134.496124 57.371243,-134.345963 57.328884,-134.316452 57.331524,-134.342911 57.387077,-134.382492 57.380131,-134.459290 57.391106,-134.526672 57.442490,-134.556671 57.472214,-134.570831 57.487354,-134.549789 57.488464,-134.509033 57.487423,-134.352982 57.541313,-134.382492 57.548122,-134.465546 57.533051,-134.503906 57.520271,-134.554169 57.507771,-134.573334 57.505829,-134.589432 57.537495,-134.610260 57.561661,-134.632355 57.579998,-134.657639 57.602913,-134.705841 57.717491,-134.712631 57.740826,-134.697296 57.780270,-134.700821 57.825829,-134.786057 58.105896,-134.912506 58.205269,-134.953049 58.299297,-134.972076 58.366936,-134.950134 58.405476,-134.796967 58.308601,-134.705338 58.214504,-134.692291 58.167702,-134.668335 58.159851,-134.637222 58.160824,-134.601654 58.171940,-134.555267 58.185822,-134.451935 58.176800,-134.398895 58.157211,-134.356934 58.145130,-134.334854 58.143742,-134.295837 58.151932,-134.201935 58.163879,-134.173126 58.159779,-134.162079 58.125195,-134.136414 58.051659,-134.078064 58.008331,-134.003632 57.936104,-133.913910 57.812767,-133.895020 57.756660,-133.875824 57.672768,-133.893341 57.655266,-133.960266 57.684433,-133.982208 57.733879,-133.996368 57.768600,-134.068329 57.830551,-134.091995 57.848606,-134.109573 57.876801,-134.140015 57.954437,-134.154602 57.992077,-134.175980 58.013466,-134.238739 58.066799,-134.288605 58.077217,-134.319580 58.030968,-134.271118 57.873604,-134.246887 57.857216,-134.181671 57.814438,-134.005859 57.648331,-133.931458 57.562214,-133.922363 57.532772,-133.894470 57.504997,-133.874146 57.489159)),((-134.515839 58.338043,-134.507233 58.336105,-134.475281 58.323883,-134.454437 58.313324,-134.275848 58.212494,-134.261398 58.198673,-134.276398 58.190826,-134.365540 58.206100,-134.427490 58.220268,-134.438599 58.222488,-134.451111 58.223877,-134.477356 58.223461,-134.494980 58.220127,-134.508911 58.217766,-134.555573 58.220825,-134.583191 58.225960,-134.608032 58.237770,-134.627197 58.248604,-134.638611 58.256386,-134.655426 58.270683,-134.682648 58.299576,-134.671112 58.311661,-134.655579 58.316666,-134.583893 58.338600,-134.566956 58.340828,-134.556122 58.340828,-134.515839 58.338043)),((-135.123596 57.774437,-135.199158 57.775826,-135.231232 57.779713,-135.267517 57.791664,-135.337769 57.825272,-135.555847 57.902771,-135.718048 57.943878,-135.822083 57.980404,-135.844574 57.989853,-135.880341 57.992489,-135.796249 57.930687,-135.728333 57.916664,-135.647247 57.901657,-135.557495 57.870270,-135.382477 57.806938,-135.359985 57.797218,-135.317780 57.757217,-135.296967 57.731659,-135.233063 57.721100,-135.167511 57.727211,-135.098602 57.743324,-135.045288 57.751106,-134.957489 57.760830,-134.931122 57.759438,-134.912842 57.749855,-134.844238 57.596451,-134.854492 57.458740,-134.988312 57.450546,-135.059296 57.459507,-135.086929 57.477215,-135.119720 57.497490,-135.273895 57.559715,-135.455261 57.629715,-135.564728 57.672493,-135.622223 57.704437,-135.644745 57.714157,-135.666962 57.723602,-135.697235 57.736382,-135.730560 57.747772,-135.750854 57.753052,-135.800873 57.759892,-135.687500 57.641663,-135.570755 57.585754,-135.552490 57.534164,-135.545914 57.465755,-135.601929 57.414154,-135.688049 57.362770,-135.729431 57.366379,-135.835419 57.387077,-135.951935 57.469154,-136.001526 57.518047,-135.969574 57.518051,-135.906387 57.496937,-135.886124 57.480965,-135.865265 57.468048,-135.804718 57.437210,-135.782166 57.434574,-135.794586 57.459297,-135.837769 57.484436,-135.896393 57.509995,-135.951935 57.531105,-136.029999 57.567215,-136.062622 57.600792,-135.994720 57.600273,-135.951324 57.611595,-135.991364 57.631378,-136.075287 57.647217,-136.125549 57.698875,-136.201935 57.747215,-136.353058 57.833054,-136.372971 57.836658,-136.403748 57.822735,-136.356033 57.937843,-136.361252 57.966381,-136.337341 57.988880,-136.305573 57.986660,-136.215546 57.931381,-136.054016 57.845963,-136.033554 57.846935,-136.060547 57.867210,-136.099426 57.888329,-136.203888 57.950272,-136.373047 58.053322,-136.394745 58.068882,-136.418335 58.089714,-136.431671 58.110828,-136.347900 58.220406,-136.269455 58.216587,-136.227783 58.148880,-136.167236 58.098045,-136.180069 58.176174,-136.134583 58.220406,-135.959305 58.201797,-135.923203 58.228462,-135.812851 58.274017,-135.779312 58.275131,-135.742767 58.256104,-135.584991 58.196655,-135.508057 58.175617,-135.483459 58.158047,-135.513687 58.103882,-135.610199 58.042355,-135.656677 58.044441,-135.700562 58.055408,-135.778961 58.042564,-135.707764 57.978325,-135.647247 57.962212,-135.618317 57.961662,-135.558624 58.000275,-135.541382 58.012772,-135.488892 58.068329,-135.452423 58.120129,-135.406540 58.137493,-135.099426 58.094154,-134.935837 58.031937,-134.920563 58.017078,-134.905289 57.982349,-134.911255 57.919994,-134.970001 57.885269,-135.018616 57.889160,-135.167511 57.936378,-135.198746 57.936867,-135.144745 57.893883,-135.120819 57.881798,-135.083069 57.874435,-135.048615 57.868881,-135.019867 57.852909,-134.964722 57.809578,-135.005280 57.779541,-135.044739 57.780273,-135.089447 57.781940,-135.123596 57.774437)),((-153.258057 58.136383,-153.239990 58.121658,-153.212494 58.105270,-153.185272 58.092491,-153.055847 58.035553,-152.968597 58.015831,-152.906677 58.001389,-152.891525 57.990620,-152.903900 57.985825,-152.961670 57.981102,-152.974701 57.980820,-152.986389 57.981102,-153.045288 57.989990,-153.063904 57.993607,-153.210541 58.030273,-153.343597 58.039162,-153.355255 58.038048,-153.369705 58.040413,-153.415695 58.060688,-153.320282 58.134720,-153.305267 58.140549,-153.284729 58.143883,-153.269043 58.142078,-153.258057 58.136383)),((-136.454437 58.088600,-136.391388 58.046944,-136.340546 58.018326,-136.330429 58.007496,-136.354462 58.000854,-136.375977 57.984051,-136.385437 57.956745,-136.380280 57.914711,-136.415833 57.864159,-136.425018 57.854164,-136.441940 57.845825,-136.532776 57.918053,-136.546661 57.960823,-136.555557 58.017078,-136.541809 58.064713,-136.488190 58.091934,-136.473602 58.093605,-136.454437 58.088600)),((-153.597778 57.598877,-153.585587 57.605442,-153.611374 57.637909,-153.678757 57.670132,-153.710403 57.680130,-153.746643 57.687492,-153.789597 57.694435,-153.858337 57.700546,-153.895004 57.703949,-153.927368 57.728046,-153.937225 57.779713,-153.929321 57.808327,-153.903625 57.831665,-153.752228 57.897217,-153.732071 57.902489,-153.643066 57.866104,-153.571106 57.829300,-153.558197 57.811657,-153.555099 57.753464,-153.545151 57.686520,-153.531403 57.658325,-153.506195 57.628464,-153.320511 57.727249,-153.406036 57.788815,-153.450134 57.791729,-153.473465 57.810341,-153.470673 57.840893,-153.213043 57.788330,-153.193054 57.837494,-153.150574 57.863884,-153.096649 57.837769,-153.051178 57.830269,-153.173889 57.925270,-153.196106 57.941101,-153.230560 57.949997,-153.262650 57.956242,-153.294861 57.994438,-153.258621 58.002357,-153.230560 57.991661,-153.187500 57.973602,-153.116943 57.949997,-153.032776 57.933601,-152.999756 57.946354,-152.949982 57.947212,-152.840820 57.924438,-152.813477 57.909573,-152.830688 57.894020,-152.879791 57.880203,-152.909592 57.834854,-152.920563 57.757771,-152.877487 57.728874,-152.857285 57.749161,-152.860535 57.794022,-152.849915 57.834644,-152.801392 57.858810,-152.691681 57.880547,-152.623596 57.927494,-152.592224 57.930550,-152.497772 57.909988,-152.477219 57.903183,-152.353607 57.838326,-152.329926 57.818916,-152.383911 57.789993,-152.425568 57.777489,-152.448059 57.768883,-152.478882 57.751389,-152.551605 57.704227,-152.435272 57.604713,-152.425018 57.603607,-152.405426 57.616798,-152.338593 57.633049,-152.163544 57.626099,-152.152298 57.608189,-152.216400 57.557495,-152.335770 57.427494,-152.361801 57.423050,-152.524445 57.436104,-152.652496 57.465546,-152.731018 57.504162,-152.926941 57.516937,-153.024460 57.471241,-153.036987 57.433289,-153.001801 57.443600,-152.976578 57.459229,-152.840408 57.472351,-152.804443 57.468597,-152.773071 57.458328,-152.631256 57.401936,-152.600784 57.373634,-152.633911 57.317772,-152.681946 57.282768,-152.704163 57.273880,-152.825562 57.269157,-152.847900 57.270409,-152.897369 57.303467,-152.906952 57.327080,-153.166885 57.346031,-153.174866 57.302494,-153.079300 57.287636,-153.058746 57.290550,-153.034729 57.298328,-153.004318 57.292633,-152.977203 57.279991,-152.956528 57.255756,-152.984161 57.241661,-153.067490 57.216656,-153.098053 57.212212,-153.140289 57.215828,-153.169586 57.219852,-153.255981 57.228878,-153.301666 57.210274,-153.370819 57.178879,-153.373871 57.169991,-153.425842 57.130272,-153.504456 57.063465,-153.551392 57.073326,-153.580551 57.081108,-153.602066 57.081799,-153.727356 57.060963,-153.749512 57.044231,-153.696381 57.049164,-153.594711 57.046524,-153.554169 56.980267,-153.606384 56.935963,-153.633057 56.932770,-153.725281 56.878044,-153.773895 56.838326,-153.913910 56.765549,-153.962082 56.743050,-153.985962 56.738464,-154.138885 56.741657,-154.120544 56.789993,-154.073059 56.841377,-153.949448 56.907352,-153.901398 56.922913,-153.859512 56.933327,-153.805573 56.973320,-153.827209 57.010277,-153.850266 57.020271,-153.868317 56.994156,-153.876923 56.975685,-153.898209 56.962631,-153.945969 56.956661,-153.966949 56.958324,-153.960129 56.993744,-153.904175 57.063602,-153.816406 57.098877,-153.738739 57.128738,-153.792084 57.152905,-153.954391 57.067989,-154.007507 57.035271,-154.025009 57.017910,-154.052917 56.979855,-154.077774 56.965965,-154.099716 56.964855,-154.134323 56.994991,-154.095001 57.050270,-154.078064 57.067909,-154.051682 57.081104,-154.020554 57.107666,-154.124420 57.143051,-154.145020 57.144997,-154.246094 57.146942,-154.320831 57.147774,-154.345001 57.147774,-154.473190 57.122108,-154.481659 57.092770,-154.458755 57.061798,-154.439453 57.052631,-154.380005 57.046104,-154.355698 57.053188,-154.334442 57.071938,-154.315491 57.096657,-154.275284 57.114574,-154.242767 57.118324,-154.106094 57.115479,-154.106232 57.083328,-154.159454 56.959438,-154.243042 56.874157,-154.282227 56.854439,-154.297791 56.848877,-154.301666 56.902840,-154.333328 56.930824,-154.358337 56.944710,-154.383911 56.958046,-154.403900 56.967766,-154.458038 56.978043,-154.528122 56.995964,-154.523621 57.031105,-154.517792 57.053879,-154.515427 57.075134,-154.527649 57.147491,-154.539185 57.184433,-154.609573 57.260967,-154.692368 57.279160,-154.729568 57.275547,-154.771194 57.271450,-154.799454 57.283329,-154.727783 57.422218,-154.639191 57.504997,-154.616638 57.518600,-154.516968 57.578606,-154.348328 57.645271,-154.249420 57.664436,-154.207214 57.666664,-154.029999 57.651382,-154.002029 57.640755,-153.930435 57.523743,-153.922501 57.499298,-153.918884 57.472214,-153.912506 57.447212,-153.902786 57.427769,-153.890442 57.409714,-153.801117 57.335823,-153.784729 57.324165,-153.760300 57.309853,-153.731110 57.298328,-153.635010 57.275967,-153.651962 57.287495,-153.671951 57.289856,-153.742432 57.318741,-153.809021 57.403599,-153.835266 57.548050,-153.869522 57.643326,-153.754028 57.649715,-153.669739 57.638603,-153.648621 57.633049,-153.597778 57.598877)),((-153.457214 57.969154,-153.353333 57.936378,-153.272522 57.901104,-153.261139 57.889717,-153.232208 57.856384,-153.220551 57.841660,-153.214447 57.830826,-153.210556 57.809994,-153.223877 57.808044,-153.248871 57.814995,-153.279449 57.824165,-153.295288 57.829437,-153.453888 57.883881,-153.535080 57.930893,-153.525711 57.956245,-153.481934 57.971100,-153.470551 57.972214,-153.457214 57.969154)),((-135.089172 56.593880,-135.105820 56.595337,-135.202148 56.685684,-135.174164 56.718880,-135.154449 56.741661,-135.124298 56.827770,-135.155426 56.823883,-135.200836 56.808884,-135.223053 56.801102,-135.263351 56.783886,-135.298340 56.786659,-135.367355 56.832214,-135.356796 56.958050,-135.356583 57.071732,-135.378052 57.098602,-135.405426 57.165165,-135.361389 57.191795,-135.338257 57.245201,-135.457489 57.247490,-135.505005 57.242767,-135.551941 57.257500,-135.635284 57.313324,-135.667526 57.345787,-135.645569 57.364857,-135.618454 57.364441,-135.519165 57.349998,-135.478333 57.363884,-135.546661 57.412491,-135.515717 57.504997,-135.439728 57.544441,-135.416107 57.551521,-135.392105 57.553883,-135.351944 57.548046,-135.157776 57.475548,-134.975540 57.386105,-134.945419 57.364857,-134.836105 57.250271,-134.797791 57.167351,-134.784454 57.120544,-134.726105 56.988884,-134.684448 56.896660,-134.644165 56.796944,-134.618881 56.728741,-134.612488 56.682495,-134.607483 56.601940,-134.609985 56.575554,-134.625000 56.537498,-134.622223 56.472488,-134.621094 56.385551,-134.622482 56.250000,-134.654587 56.166103,-134.761688 56.221375,-134.882751 56.345543,-134.994720 56.466385,-135.047501 56.530968,-135.029938 56.575203,-135.000000 56.585743,-134.940002 56.600548,-134.846802 56.683605,-134.876862 56.685825,-135.051941 56.606941,-135.089172 56.593880)),((-134.818878 57.401657,-134.823059 57.390549,-134.809586 57.361240,-134.787643 57.344437,-134.794937 57.299713,-134.809448 57.296661,-134.821930 57.303879,-134.864441 57.329437,-134.973114 57.409016,-134.940552 57.422218,-134.888062 57.428329,-134.876648 57.427773,-134.812378 57.415131,-134.818878 57.401657)),((-135.700287 57.316940,-135.645294 57.295830,-135.626373 57.287914,-135.611938 57.278603,-135.589722 57.263329,-135.576935 57.250549,-135.554871 57.226658,-135.546249 57.132214,-135.566650 57.082214,-135.625824 57.006107,-135.719727 56.993607,-135.795837 56.986382,-135.826935 56.985825,-135.837906 56.990826,-135.825409 57.079994,-135.815964 57.089157,-135.783630 57.101105,-135.762924 57.105965,-135.752502 57.110550,-135.714447 57.141106,-135.712769 57.162907,-135.748871 57.164711,-135.807510 57.168327,-135.819580 57.175129,-135.845840 57.319302,-135.833466 57.325829,-135.760559 57.331665,-135.710541 57.323608,-135.700287 57.316940)),((-170.280609 57.104996,-170.269196 57.132904,-170.270599 57.144295,-170.304993 57.150536,-170.317505 57.151093,-170.353882 57.144707,-170.407242 57.161514,-170.413239 57.171383,-170.411423 57.183739,-170.397812 57.197479,-170.386963 57.201653,-170.316650 57.213608,-170.150574 57.228325,-170.139771 57.216927,-170.162933 57.166927,-170.248871 57.129433,-170.280609 57.104996)),((-152.894745 57.135826,-152.917084 57.123878,-153.102203 57.084160,-153.209442 57.041939,-153.218613 57.023464,-153.229431 57.012497,-153.249039 56.999439,-153.311111 56.988880,-153.337494 56.998047,-153.399750 57.055824,-153.406677 57.069717,-153.275848 57.196796,-153.234161 57.205826,-153.223053 57.206940,-153.175293 57.184158,-152.966095 57.175827,-152.955841 57.174713,-152.891388 57.159714,-152.882767 57.146938,-152.894745 57.135826)),((-133.051666 56.977486,-132.972763 56.924435,-132.926529 56.851521,-132.945557 56.742767,-132.924713 56.659988,-132.933762 56.629784,-132.970001 56.608604,-133.009308 56.600685,-133.126236 56.666382,-133.187500 56.716660,-133.203613 56.750832,-133.216660 56.781799,-133.242630 56.805965,-133.347214 56.837627,-133.332489 56.761940,-133.305573 56.731377,-133.186401 56.637497,-133.114166 56.621658,-133.095276 56.613747,-133.088043 56.554436,-133.082703 56.532631,-133.131516 56.471100,-133.156265 56.456104,-133.186951 56.451801,-133.304993 56.471657,-133.426941 56.473320,-133.467224 56.452217,-133.505157 56.435406,-133.575562 56.433601,-133.638885 56.439362,-133.657928 56.462631,-133.662231 56.523048,-133.635010 56.596798,-133.667297 56.638256,-133.693756 56.650688,-133.706940 56.683464,-133.691681 56.750275,-133.681946 56.794159,-133.699310 56.829578,-133.739716 56.807140,-133.870819 56.869019,-133.881760 56.898067,-133.832642 56.882214,-133.806396 56.876102,-133.748596 56.874161,-133.741318 56.894993,-133.885559 56.950546,-134.018066 57.014717,-134.008133 57.054577,-133.908051 57.080276,-133.842773 57.081108,-133.761139 57.069443,-133.629700 57.050270,-133.500000 57.028328,-133.438324 57.013329,-133.317780 56.993881,-133.296127 56.997631,-133.167236 57.001663,-133.080963 56.993740,-133.051666 56.977486)),((-133.862213 56.277489,-133.895294 56.300270,-133.916779 56.319653,-133.947617 56.351063,-133.971069 56.358524,-133.973404 56.344082,-133.965454 56.317131,-133.968750 56.303364,-133.976700 56.288822,-133.984253 56.269043,-133.973495 56.266232,-133.954971 56.276024,-133.943604 56.280273,-133.922516 56.279434,-133.911957 56.274574,-133.902924 56.266243,-133.896973 56.254166,-133.890839 56.233604,-133.887787 56.220543,-133.914459 56.148880,-133.946106 56.089157,-133.959152 56.082497,-133.977768 56.082912,-134.016663 56.095268,-134.033768 56.103470,-134.036819 56.113880,-134.012512 56.190269,-134.025970 56.273911,-134.036591 56.305199,-134.056656 56.311657,-134.066254 56.302773,-134.095825 56.131798,-134.087219 56.083881,-134.102203 56.011940,-134.109436 55.997078,-134.126099 55.997631,-134.161957 56.022217,-134.220825 56.066666,-134.265427 56.253052,-134.259323 56.263050,-134.220276 56.276939,-134.204712 56.298050,-134.227203 56.307495,-134.251953 56.314995,-134.282303 56.348461,-134.231659 56.419159,-134.174728 56.435959,-134.084991 56.397217,-134.064590 56.384296,-134.056122 56.373047,-134.049866 56.362144,-134.034592 56.377354,-134.032639 56.417492,-134.052795 56.503883,-134.064590 56.548046,-134.071243 56.555962,-134.089432 56.538189,-134.174164 56.535828,-134.304031 56.558186,-134.390015 56.711105,-134.393341 56.721375,-134.408905 56.829437,-134.404724 56.847771,-134.396545 56.854580,-134.318054 56.895550,-134.297791 56.900543,-134.276123 56.899994,-134.263916 56.898331,-134.244141 56.893608,-134.221100 56.884163,-134.178345 56.858887,-134.155579 56.849434,-134.120132 56.842072,-134.106934 56.845825,-134.136139 56.884163,-134.146820 56.889160,-134.172791 56.894714,-134.195282 56.896385,-134.213623 56.901382,-134.261551 56.938740,-134.248047 56.939713,-134.191681 56.930275,-134.126923 56.913322,-134.036133 56.888603,-134.008911 56.880547,-133.990540 56.872631,-133.925842 56.801933,-133.903625 56.749996,-133.922516 56.714996,-133.965134 56.657490,-133.979309 56.651657,-134.014191 56.650826,-134.024170 56.648468,-134.006683 56.641937,-133.975006 56.635551,-133.958893 56.639717,-133.945831 56.646385,-133.917236 56.667213,-133.872345 56.709576,-133.862213 56.723602,-133.856110 56.736938,-133.853058 56.749161,-133.853058 56.760551,-133.855545 56.773743,-133.865265 56.790276,-133.830566 56.796104,-133.732910 56.775826,-133.719299 56.769020,-133.725952 56.653046,-133.692627 56.597076,-133.738586 56.560547,-133.749039 56.555962,-133.763062 56.554710,-133.773621 56.556656,-133.782776 56.564995,-133.787231 56.580551,-133.794312 56.593533,-133.817352 56.607079,-133.833893 56.609993,-133.890839 56.614998,-133.912231 56.615829,-133.921249 56.611103,-133.914459 56.602077,-133.876648 56.523605,-133.882477 56.437210,-133.850281 56.352493,-133.841812 56.344711,-133.846100 56.290833,-133.851517 56.281662,-133.862213 56.277489)),((-132.801941 56.786385,-132.732483 56.724709,-132.667236 56.678604,-132.613892 56.645271,-132.549744 56.605270,-132.536255 56.601242,-132.528198 56.592628,-132.529327 56.581104,-132.538757 56.570827,-132.561951 56.559158,-132.577209 56.554161,-132.683624 56.520271,-132.773071 56.494713,-132.792511 56.493881,-132.894745 56.497490,-132.905853 56.498329,-132.930420 56.504440,-132.942993 56.515759,-132.956390 56.594154,-132.923035 56.618881,-132.896744 56.621887,-132.883224 56.634659,-132.898239 56.656448,-132.923035 56.702278,-132.918335 56.748878,-132.873596 56.796104,-132.801941 56.786385)),((-169.580017 56.535828,-169.611664 56.539986,-169.644745 56.547077,-169.744141 56.588875,-169.769196 56.602486,-169.782867 56.614296,-169.760284 56.618050,-169.726105 56.613319,-169.673370 56.608597,-169.594452 56.603043,-169.584198 56.603882,-169.557526 56.607216,-169.521393 56.613602,-169.488068 56.603600,-169.472763 56.594711,-169.501953 56.574715,-169.565308 56.541100,-169.580017 56.535828)),((-154.083313 56.603882,-154.075287 56.588326,-154.077484 56.573883,-154.106934 56.536659,-154.176941 56.507500,-154.207077 56.499714,-154.236664 56.498047,-154.246643 56.498878,-154.296967 56.504715,-154.328888 56.510414,-154.339996 56.521660,-154.352478 56.541664,-154.315277 56.575272,-154.304993 56.583054,-154.287781 56.594154,-154.272247 56.599434,-154.234436 56.606941,-154.214722 56.608887,-154.087219 56.610271,-154.083313 56.603882)),((-154.421387 56.587769,-154.412094 56.582771,-154.403473 56.573467,-154.399582 56.561241,-154.405014 56.544579,-154.416534 56.537357,-154.428619 56.533607,-154.455826 56.533188,-154.429169 56.539577,-154.418060 56.549992,-154.446243 56.586937,-154.455566 56.592216,-154.481110 56.598045,-154.496674 56.597076,-154.515015 56.589989,-154.524872 56.578606,-154.526688 56.551273,-154.503830 56.535908,-154.490433 56.508331,-154.525101 56.501633,-154.569626 56.490604,-154.608627 56.477211,-154.637375 56.463814,-154.675598 56.438210,-154.704361 56.408268,-154.719711 56.399994,-154.736267 56.396057,-154.763245 56.398220,-154.787476 56.414967,-154.792206 56.429935,-154.778809 56.451996,-154.759903 56.474846,-154.740601 56.495331,-154.714996 56.517788,-154.648407 56.547333,-154.605865 56.566635,-154.563324 56.587120,-154.531418 56.599335,-154.505417 56.602879,-154.481384 56.601696,-154.452621 56.595787,-154.421387 56.587769)),((-157.240265 56.581665,-157.159454 56.583054,-157.072784 56.580826,-157.055847 56.576942,-157.000137 56.557076,-156.975677 56.537216,-157.002228 56.529438,-157.024033 56.545414,-157.036407 56.548607,-157.069153 56.549164,-157.111664 56.549438,-157.122772 56.549438,-157.140839 56.544998,-157.195282 56.530823,-157.327209 56.522217,-157.329712 56.535828,-157.298340 56.558884,-157.287231 56.566666,-157.269470 56.577217,-157.251678 56.581665,-157.240265 56.581665)),((-153.876099 56.551102,-153.879578 56.538052,-153.888626 56.529575,-153.942230 56.507217,-153.958893 56.502777,-154.063049 56.499161,-154.106659 56.501106,-154.129776 56.508469,-154.107758 56.523605,-154.071106 56.538048,-154.039169 56.547497,-154.012787 56.550827,-153.965820 56.553879,-153.899170 56.558044,-153.875961 56.555683,-153.876099 56.551102)),((-132.056122 56.111382,-132.099014 56.160686,-132.109436 56.165825,-132.171112 56.185265,-132.191681 56.189713,-132.203613 56.191658,-132.214722 56.192490,-132.225006 56.194710,-132.251404 56.203049,-132.273071 56.213608,-132.302216 56.232208,-132.312500 56.239990,-132.331116 56.256386,-132.346237 56.270966,-132.348053 56.281525,-132.332504 56.305408,-132.327789 56.315269,-132.327209 56.326660,-132.326660 56.401798,-132.348602 56.436653,-132.368240 56.454159,-132.375687 56.475407,-132.371796 56.487213,-132.354996 56.488602,-132.256256 56.453602,-132.231232 56.439156,-132.222702 56.421036,-132.217911 56.398884,-132.212357 56.389580,-132.160828 56.353050,-132.127762 56.344437,-132.108597 56.344299,-132.091675 56.352493,-132.074173 56.359581,-132.043060 56.354996,-132.006546 56.338600,-131.994995 56.328331,-131.989441 56.318886,-131.947235 56.232208,-132.010284 56.134159,-132.056122 56.111382)),((-132.834167 56.230820,-132.845001 56.231659,-132.861389 56.237495,-132.910278 56.261108,-133.044739 56.332077,-133.055481 56.349087,-132.989304 56.421242,-132.940277 56.447769,-132.920837 56.453327,-132.887787 56.455551,-132.732758 56.458328,-132.722504 56.458328,-132.703064 56.456100,-132.683075 56.452492,-132.656403 56.444153,-132.638474 56.435963,-132.629700 56.424713,-132.614304 56.393608,-132.634735 56.298332,-132.640289 56.283192,-132.648071 56.276100,-132.677216 56.265549,-132.700836 56.259163,-132.759460 56.245827,-132.817230 56.233879,-132.834167 56.230820)),((-132.318878 55.912209,-132.425568 55.956100,-132.421936 55.968323,-132.411270 55.995827,-132.419739 56.028328,-132.447784 56.053604,-132.598465 56.080551,-132.607483 56.074997,-132.610809 56.062767,-132.621796 56.049023,-132.635010 56.049164,-132.687225 56.099434,-132.695831 56.107773,-132.712769 56.135826,-132.716949 56.151382,-132.696396 56.219299,-132.683609 56.226242,-132.573334 56.277771,-132.565277 56.289436,-132.529175 56.331940,-132.515839 56.338600,-132.495544 56.343323,-132.437225 56.350273,-132.417786 56.350830,-132.402100 56.347351,-132.384644 56.332008,-132.378601 56.313049,-132.370544 56.268326,-132.395020 56.221931,-132.211670 56.178047,-132.179306 56.168743,-132.107208 56.115829,-132.093750 56.101032,-132.137787 56.067497,-132.114304 55.947491,-132.119843 55.935127,-132.131531 55.927078,-132.143616 55.924438,-132.273895 55.916664,-132.318878 55.912209)),((-132.159180 55.444435,-132.217773 55.475548,-132.377777 55.530273,-132.408356 55.536942,-132.434448 55.545273,-132.452652 55.559299,-132.475830 55.590965,-132.512848 55.615063,-132.542923 55.620964,-132.562500 55.567772,-132.500137 55.511105,-132.282440 55.457424,-132.088287 55.267597,-132.135010 55.239159,-132.170563 55.242493,-132.201385 55.248047,-132.233322 55.249302,-132.250000 55.211662,-132.235336 55.193115,-132.100479 55.198044,-132.070419 55.213326,-132.057709 55.235752,-132.014786 55.269711,-131.985825 55.259579,-131.968048 55.220963,-131.969986 55.178608,-131.995590 55.105480,-132.043488 55.079021,-132.083893 55.067772,-132.074722 55.040966,-132.143066 55.013885,-132.172791 55.004719,-132.213531 54.993744,-132.137360 54.965134,-132.085693 54.976376,-132.057770 54.998329,-132.027924 55.021938,-131.972565 55.029713,-131.949432 54.788330,-132.007233 54.689987,-132.126389 54.688183,-132.286545 54.713326,-132.297150 54.744019,-132.289444 54.768051,-132.257355 54.784298,-132.219147 54.784721,-132.214172 54.791245,-132.222076 54.810966,-132.284180 54.854713,-132.326660 54.881935,-132.489700 54.977489,-132.502365 54.953323,-132.517105 54.938877,-132.544174 54.934364,-132.573334 54.948601,-132.596024 54.969086,-132.574448 55.034992,-132.547562 55.044926,-132.515381 55.051437,-132.511963 55.106384,-132.650726 55.243813,-132.647232 55.205826,-132.632492 55.188324,-132.609848 55.170689,-132.622910 55.147911,-132.655136 55.138741,-132.694031 55.142910,-132.777161 55.181522,-132.802216 55.209644,-132.807495 55.248047,-132.944733 55.207771,-133.002808 55.203049,-133.027603 55.215576,-132.987762 55.228737,-132.910812 55.275723,-132.970276 55.271103,-133.025421 55.267212,-133.212845 55.277840,-133.261398 55.335690,-133.209778 55.381104,-133.116379 55.377491,-133.041534 55.361870,-132.968597 55.349998,-132.900421 55.345684,-132.867493 55.353882,-132.888336 55.359993,-132.944458 55.370270,-132.965820 55.372215,-132.986664 55.373047,-133.001816 55.379295,-133.031128 55.398048,-133.114563 55.465546,-133.126984 55.491032,-133.117905 55.515553,-133.051941 55.577217,-133.006134 55.609436,-132.981934 55.619576,-132.961243 55.623600,-132.921143 55.624641,-132.966797 55.638607,-133.059448 55.623600,-133.120117 55.603951,-133.198608 55.577911,-133.259460 55.574440,-133.365967 55.615616,-133.382980 55.640755,-133.371307 55.721584,-133.264038 55.741383,-133.243195 55.744438,-133.141876 55.816380,-133.143860 55.879784,-133.177643 55.860966,-133.226654 55.886940,-133.239838 55.902077,-133.256958 55.946934,-133.265076 56.154850,-133.321655 56.169441,-133.364716 56.171936,-133.417511 56.164711,-133.564301 56.179024,-133.611649 56.205200,-133.632751 56.273880,-133.610535 56.348328,-133.585541 56.349716,-133.488586 56.336937,-133.346375 56.330276,-133.249023 56.331108,-133.180206 56.327286,-133.056808 56.237492,-133.023544 56.172489,-133.062775 56.118050,-133.088120 56.105621,-133.125412 56.118671,-133.072906 56.051311,-133.043060 56.047638,-132.947784 56.058044,-132.902222 56.049164,-132.822769 56.028744,-132.621796 55.919575,-132.512512 55.835548,-132.498337 55.820686,-132.464020 55.775406,-132.442505 55.688042,-132.404175 55.658325,-132.246948 55.541939,-132.226654 55.537216,-132.206665 55.526939,-132.182220 55.512497,-132.165283 55.501389,-132.141800 55.475685,-132.143066 55.452423,-132.159180 55.444435)),((-133.285553 56.128876,-133.313904 56.081383,-133.363037 56.010277,-133.458344 56.003326,-133.608337 55.958885,-133.637238 55.933327,-133.699860 55.895966,-133.787781 55.919022,-133.793060 55.931381,-133.793060 55.948326,-133.785843 55.963051,-133.774445 55.975822,-133.682632 56.064297,-133.611389 56.106102,-133.571381 56.127213,-133.400574 56.154434,-133.390564 56.154434,-133.314453 56.149162,-133.303345 56.148331,-133.279663 56.137840,-133.285553 56.128876)),((-131.388916 55.254997,-131.398071 55.256386,-131.418060 55.261108,-131.454926 55.278603,-131.458054 55.299782,-131.428070 55.313324,-131.368317 55.337769,-131.290833 55.411102,-131.273544 55.433117,-131.281403 55.489159,-131.347702 55.643120,-131.367554 55.624989,-131.360809 55.574997,-131.353333 55.555267,-131.326935 55.508049,-131.316589 55.457558,-131.328598 55.425827,-131.400085 55.348465,-131.458755 55.326801,-131.421524 55.365112,-131.422806 55.385433,-131.445663 55.407028,-131.470276 55.448326,-131.465820 55.471657,-131.429230 55.520443,-131.493881 55.505550,-131.516327 55.481030,-131.495392 55.421795,-131.471909 55.393074,-131.465729 55.368782,-131.518616 55.294579,-131.545013 55.291801,-131.665833 55.344711,-131.687225 55.354713,-131.711243 55.367771,-131.819168 55.453632,-131.700836 55.526100,-131.690842 55.609997,-131.704300 55.625198,-131.696121 55.670963,-131.629425 55.730820,-131.622772 55.781380,-131.684021 55.793606,-131.684860 55.830273,-131.539185 55.851936,-131.530304 55.901657,-131.478333 55.919159,-131.439728 55.929993,-131.291809 55.957909,-131.259598 55.960270,-131.231659 55.953880,-131.209167 55.938042,-131.142517 55.887077,-131.069458 55.821381,-131.055984 55.806244,-130.934998 55.636799,-130.938049 55.562210,-130.968063 55.388187,-131.056396 55.258049,-131.073883 55.246101,-131.100266 55.233463,-131.135010 55.229156,-131.142090 55.198879,-131.205276 55.186794,-131.247787 55.200966,-131.281128 55.226379,-131.284729 55.246384,-131.254166 55.264854,-131.232483 55.282494,-131.219574 55.299301,-131.192017 55.361588,-131.196106 55.393326,-131.218048 55.403046,-131.268753 55.383045,-131.273056 55.351658,-131.256195 55.318535,-131.290558 55.276451,-131.344147 55.256943,-131.388916 55.254997)),((-134.114716 55.899719,-134.121643 55.898605,-134.136414 55.893608,-134.176941 55.874992,-134.209167 55.858330,-134.221100 55.850830,-134.235260 55.835823,-134.252502 55.817356,-134.293884 55.830551,-134.315826 55.852493,-134.340836 55.913742,-134.321671 55.923603,-134.116394 55.921661,-134.101166 55.915062,-134.114716 55.899719)),((-155.556671 55.911377,-155.554169 55.812767,-155.557495 55.801659,-155.563477 55.788609,-155.576813 55.775963,-155.603058 55.772766,-155.715973 55.784439,-155.739990 55.828606,-155.620270 55.914154,-155.605820 55.919994,-155.580566 55.922493,-155.563904 55.918602,-155.556671 55.911377)),((-133.215546 55.861938,-133.212082 55.854717,-133.211395 55.840828,-133.212357 55.826382,-133.230545 55.789577,-133.245407 55.775131,-133.260986 55.778046,-133.309723 55.821106,-133.331528 55.873600,-133.286942 55.901100,-133.268204 55.899437,-133.215546 55.861938)),((-158.808899 55.892220,-158.783630 55.888603,-158.768890 55.883606,-158.717361 55.845547,-158.710556 55.834713,-158.719162 55.826797,-158.853333 55.805267,-158.864166 55.803879,-158.890579 55.804298,-158.906052 55.814854,-158.911957 55.834717,-158.894730 55.869991,-158.832764 55.893883,-158.813049 55.893883,-158.808899 55.892220)),((-133.303345 55.796944,-133.300980 55.790970,-133.318604 55.765831,-133.482483 55.699997,-133.505585 55.693321,-133.523071 55.690826,-133.533905 55.691658,-133.569153 55.702492,-133.591095 55.711937,-133.604431 55.718597,-133.617493 55.725548,-133.635284 55.736382,-133.645569 55.744156,-133.677780 55.775684,-133.676117 55.786385,-133.634186 55.820274,-133.616928 55.827637,-133.553345 55.829163,-133.542511 55.828331,-133.325836 55.802216,-133.303345 55.796944)),((-133.269745 55.527214,-133.267792 55.496941,-133.272522 55.488045,-133.289459 55.475822,-133.348877 55.447350,-133.434097 55.524086,-133.419586 55.544304,-133.393890 55.553047,-133.377472 55.556381,-133.338318 55.556938,-133.305420 55.552906,-133.279175 55.536385,-133.269745 55.527214)),((-133.645569 55.441101,-133.667511 55.450546,-133.714157 55.465546,-133.729431 55.467766,-133.746643 55.465271,-133.758057 55.487213,-133.726791 55.541386,-133.718872 55.548050,-133.702484 55.551384,-133.691681 55.550545,-133.583603 55.537079,-133.577911 55.527634,-133.576172 55.502079,-133.634720 55.444851,-133.645569 55.441101)),((-133.478333 55.514999,-133.423615 55.485687,-133.417923 55.476376,-133.417236 55.462494,-133.421677 55.446938,-133.428894 55.439430,-133.443329 55.434715,-133.459717 55.431381,-133.505005 55.427216,-133.515015 55.427216,-133.537506 55.429718,-133.578339 55.438599,-133.599014 55.448669,-133.512512 55.519436,-133.499420 55.520828,-133.478333 55.514999)),((-160.154999 55.437492,-160.178894 55.396103,-160.317917 55.392078,-160.328613 55.395828,-160.340897 55.412350,-160.339996 55.428047,-160.329575 55.438740,-160.290283 55.457771,-160.264450 55.463188,-160.245834 55.462078,-160.154999 55.437492)),((-133.447784 55.399994,-133.445419 55.371937,-133.503082 55.348602,-133.559860 55.314159,-133.595139 55.235546,-133.606384 55.232208,-133.644165 55.258888,-133.653076 55.267212,-133.684311 55.308327,-133.651260 55.371937,-133.637787 55.382767,-133.586670 55.417213,-133.572510 55.420830,-133.561951 55.419991,-133.446960 55.410271,-133.447784 55.399994)),((-131.819458 55.412766,-131.747498 55.369438,-131.678070 55.330551,-131.648346 55.312210,-131.631653 55.300827,-131.621918 55.292770,-131.616577 55.276592,-131.722229 55.136662,-131.737625 55.135548,-131.808350 55.182770,-131.815002 55.191933,-131.818878 55.201660,-131.822784 55.211662,-131.840271 55.266937,-131.848602 55.295830,-131.858337 55.359436,-131.851807 55.410824,-131.841934 55.420685,-131.827789 55.419159,-131.819458 55.412766)),((-160.695557 55.399994,-160.661407 55.387215,-160.553619 55.390133,-160.543884 55.385551,-160.536133 55.375267,-160.532227 55.361664,-160.533905 55.350273,-160.541107 55.341377,-160.567642 55.331387,-160.581665 55.319439,-160.584717 55.305550,-160.573761 55.230686,-160.560287 55.225685,-160.522507 55.222630,-160.511688 55.218597,-160.464294 55.186794,-160.506409 55.165268,-160.547516 55.152489,-160.628601 55.149853,-160.679169 55.163879,-160.801392 55.125267,-160.813904 55.117908,-160.824158 55.136940,-160.850830 55.203880,-160.857620 55.265686,-160.846527 55.332497,-160.800842 55.376381,-160.790833 55.384163,-160.775574 55.389992,-160.726654 55.406796,-160.695557 55.399994)),((-160.328339 55.350273,-160.317780 55.289436,-160.320831 55.278877,-160.328613 55.258049,-160.335556 55.246101,-160.483063 55.289993,-160.508636 55.302773,-160.525360 55.316380,-160.498474 55.349438,-160.346954 55.368599,-160.327927 55.356659,-160.328339 55.350273)),((-133.296661 55.330551,-133.230835 55.264999,-133.223602 55.250549,-133.241379 55.215408,-133.249725 55.209160,-133.323059 55.194710,-133.416946 55.198742,-133.427795 55.203606,-133.436401 55.211937,-133.442230 55.221100,-133.447083 55.233604,-133.450562 55.252220,-133.437500 55.304852,-133.429169 55.311104,-133.327225 55.335407,-133.311951 55.334991,-133.296661 55.330551)),((-159.871643 55.278046,-159.862213 55.260826,-159.856659 55.248878,-159.826935 55.176659,-159.840820 55.135963,-159.880417 55.098743,-159.890839 55.097771,-160.008057 55.042770,-160.122498 54.971100,-160.173340 54.931107,-160.180573 54.922218,-160.198059 54.893608,-160.202637 54.874577,-160.216385 54.870132,-160.225555 54.875267,-160.244720 54.901382,-160.246033 54.920200,-160.234711 54.931938,-160.171387 54.968880,-160.123596 55.015274,-160.138336 55.047775,-160.161682 55.067215,-160.193405 55.113255,-160.117493 55.154991,-160.101807 55.154987,-160.074295 55.142910,-160.066803 55.132492,-160.060272 55.117767,-160.009598 55.105827,-159.949432 55.168884,-159.936951 55.208046,-159.936401 55.234436,-159.920013 55.258606,-159.882202 55.290833,-159.871643 55.278046)),((-131.467224 55.235825,-131.465271 55.231934,-131.452087 55.222210,-131.421539 55.209717,-131.408356 55.208885,-131.387360 55.211243,-131.373322 55.196938,-131.348328 55.119022,-131.344025 55.059780,-131.354980 55.035553,-131.375137 55.011524,-131.386139 55.008049,-131.578888 54.991379,-131.593887 54.993881,-131.619568 55.013329,-131.622269 55.026588,-131.577789 55.083603,-131.566803 55.170963,-131.583740 55.215683,-131.584991 55.229431,-131.581665 55.254719,-131.546112 55.267212,-131.520569 55.263611,-131.469788 55.248466,-131.467224 55.235825)),((-133.102203 55.245544,-133.070831 55.199715,-132.992493 55.123047,-132.991364 55.095268,-133.003632 55.087769,-132.998047 55.059433,-132.898621 54.910545,-132.871368 54.897217,-132.852783 54.892494,-132.839020 54.890270,-132.755005 54.822220,-132.723053 54.784721,-132.686127 54.718880,-132.667786 54.679161,-132.679993 54.666100,-132.840561 54.690685,-132.863892 54.726097,-132.935547 54.804993,-132.972916 54.825554,-132.984711 54.828880,-133.004730 54.844711,-133.122498 54.939430,-133.197235 55.046661,-133.213623 55.092213,-133.196396 55.227215,-133.188049 55.233330,-133.113602 55.251804,-133.102203 55.245544)),((-159.516113 55.238045,-159.504868 55.172215,-159.506821 55.148880,-159.519470 55.064156,-159.648758 55.039997,-159.655289 55.056313,-159.653061 55.125546,-159.537918 55.245548,-159.522095 55.245548,-159.516113 55.238045)),((-132.813904 55.185822,-132.732208 55.140274,-132.691681 55.092216,-132.671936 55.037075,-132.731934 55.002777,-132.801666 55.006386,-132.866791 55.032078,-132.864166 55.141106,-132.853333 55.159431,-132.824722 55.191795,-132.813904 55.185822)),((-161.732208 55.148605,-161.659592 55.127769,-161.643341 55.115963,-161.642929 55.105270,-161.744293 55.054852,-161.763214 55.055130,-161.778198 55.060406,-161.903351 55.132492,-161.903549 55.151657,-161.858032 55.166382,-161.847778 55.168053,-161.827789 55.170830,-161.817230 55.171104,-161.727768 55.155685,-161.732208 55.148605)),((-159.382202 55.056099,-159.358322 55.054298,-159.347488 55.046524,-159.338593 54.971931,-159.379700 54.953323,-159.423889 54.941933,-159.434174 54.940544,-159.449448 54.940964,-159.458344 54.946098,-159.479156 55.014160,-159.460541 55.036659,-159.446655 55.048607,-159.438599 55.054993,-159.382202 55.056099)),((-164.176117 54.604164,-164.193329 54.599159,-164.216644 54.590546,-164.255554 54.573326,-164.279999 54.559433,-164.297516 54.548882,-164.326309 54.529297,-164.324432 54.503605,-164.343063 54.469715,-164.379730 54.446098,-164.437225 54.421379,-164.468048 54.412907,-164.663910 54.391937,-164.776672 54.396381,-164.827789 54.412491,-164.857071 54.428600,-164.933472 54.530132,-164.952347 54.580200,-164.928345 54.601387,-164.859985 54.621101,-164.805695 54.633324,-164.771118 54.635551,-164.746674 54.643604,-164.704163 54.668327,-164.681946 54.689430,-164.631378 54.746384,-164.554031 54.841381,-164.547989 54.870686,-164.491089 54.914574,-164.425003 54.929440,-164.373734 54.918053,-164.347626 54.901100,-164.304443 54.890690,-164.235260 54.891106,-164.023071 54.976936,-163.986099 54.991940,-163.954712 55.009163,-163.926178 55.031727,-163.777512 55.055405,-163.536392 55.047287,-163.438324 54.943321,-163.422073 54.920200,-163.414047 54.885410,-163.399445 54.836655,-163.374985 54.791798,-163.337341 54.770744,-163.311325 54.761826,-163.264191 54.754997,-163.222000 54.761871,-163.197433 54.777561,-163.140640 54.763187,-163.054886 54.668118,-163.154861 54.658741,-163.295563 54.699432,-163.335968 54.708015,-163.432434 54.668465,-163.520020 54.632210,-163.594986 54.611797,-163.629730 54.610970,-163.682495 54.617214,-163.714447 54.624161,-163.756805 54.630962,-163.814453 54.633606,-164.008362 54.629990,-164.051666 54.626656,-164.084991 54.621933,-164.116638 54.616386,-164.167236 54.606659,-164.176117 54.604164)),((-131.238312 54.986382,-131.242630 54.976658,-131.241364 54.931381,-131.225830 54.924995,-131.201950 54.918884,-131.192429 54.908115,-131.233887 54.877213,-131.329865 54.856247,-131.344452 54.856659,-131.378052 54.863609,-131.473877 54.911377,-131.483459 54.922352,-131.480820 54.933601,-131.470963 54.943459,-131.451385 54.953049,-131.253357 54.998878,-131.237549 54.993462,-131.238312 54.986382)),((-162.232758 54.965271,-162.229355 54.951931,-162.234146 54.930134,-162.227905 54.911240,-162.228882 54.896942,-162.235535 54.887772,-162.256271 54.875546,-162.264313 54.866940,-162.277924 54.848743,-162.293060 54.834160,-162.309448 54.828880,-162.328888 54.829720,-162.355270 54.845963,-162.367355 54.853050,-162.386246 54.862770,-162.395569 54.867767,-162.405853 54.876381,-162.419861 54.885967,-162.423889 54.905823,-162.430420 54.921661,-162.431396 54.932770,-162.421387 54.935265,-162.385834 54.944710,-162.363739 54.956520,-162.340546 54.970821,-162.319992 54.980408,-162.303894 54.982765,-162.279877 54.981655,-162.248199 54.973877,-162.232758 54.965271)),((-132.616394 54.890831,-132.611389 54.878044,-132.609207 54.769993,-132.619446 54.754440,-132.633057 54.748878,-132.647919 54.751106,-132.662231 54.757633,-132.774445 54.856941,-132.783630 54.867908,-132.789871 54.904987,-132.777512 54.926521,-132.708893 54.940544,-132.628601 54.901932,-132.618866 54.896103,-132.616394 54.890831)),((-162.753632 54.484718,-162.595551 54.453465,-162.560547 54.429161,-162.544586 54.412769,-162.542923 54.384018,-162.621368 54.367210,-162.639740 54.368599,-162.736389 54.397491,-162.765839 54.406654,-162.786407 54.414711,-162.799164 54.421104,-162.810272 54.428879,-162.836105 54.454159,-162.828751 54.496243,-162.816101 54.500000,-162.783081 54.494156,-162.759460 54.488327,-162.753632 54.484718)),((-165.569153 54.108887,-165.605408 54.114429,-165.621277 54.125542,-165.680862 54.235542,-165.667526 54.261799,-165.625275 54.291100,-165.520844 54.292496,-165.486603 54.286518,-165.478088 54.201935,-165.485840 54.173325,-165.550995 54.114849,-165.560577 54.110268,-165.569153 54.108887)),((-165.897522 54.028870,-165.911896 54.054153,-165.935028 54.060822,-165.967529 54.062202,-165.989456 54.049576,-166.042679 54.037495,-166.067230 54.053879,-166.121689 54.114433,-166.090973 54.168186,-166.070587 54.178879,-165.977921 54.215405,-165.943054 54.220264,-165.658981 54.122345,-165.672241 54.097771,-165.683624 54.090546,-165.696960 54.084717,-165.767654 54.063881,-165.782501 54.063599,-165.848907 54.070267,-165.897522 54.028870)),((-164.976410 54.126442,-164.952805 54.129013,-164.937119 54.125961,-164.929199 54.118595,-164.929184 54.107906,-164.949890 54.083179,-164.961823 54.076382,-165.018890 54.070824,-165.076416 54.066666,-165.086945 54.067215,-165.213486 54.084709,-165.221649 54.093044,-165.204712 54.113884,-165.133209 54.127487,-165.088348 54.124985,-165.073334 54.119431,-165.051147 54.110825,-165.038940 54.104156,-164.978394 54.121792,-164.976410 54.126442)),((-166.284760 53.676384,-166.305573 53.676941,-166.410858 53.669991,-166.542847 53.625126,-166.632202 53.531097,-166.650177 53.492073,-166.756561 53.445267,-166.825317 53.437759,-166.959442 53.431664,-166.979431 53.440819,-167.137512 53.417355,-167.383331 53.339706,-167.495300 53.279160,-167.552246 53.271103,-167.663330 53.255547,-167.764771 53.270821,-167.842560 53.306374,-167.718079 53.373604,-167.691406 53.384720,-167.587250 53.388039,-167.555298 53.386932,-167.504181 53.399712,-167.492493 53.416100,-167.478897 53.433327,-167.372223 53.428040,-167.301941 53.437759,-167.164062 53.464577,-167.083755 53.528595,-167.142792 53.551102,-167.161667 53.600197,-167.145859 53.620548,-167.121811 53.629704,-167.093765 53.630260,-167.066971 53.618038,-167.046417 53.593880,-167.063507 53.678181,-167.025726 53.702625,-166.905640 53.708736,-166.803894 53.648872,-166.766449 53.685822,-166.768890 53.729706,-166.958771 53.771240,-166.981277 53.769573,-167.004059 53.759434,-167.034485 53.752766,-167.152374 53.823879,-167.160309 53.850819,-167.091385 53.917557,-167.020432 53.956654,-166.754913 54.008465,-166.668472 54.009430,-166.631546 53.999710,-166.610413 53.987762,-166.592575 53.964504,-166.616943 53.948875,-166.637665 53.915684,-166.636414 53.874985,-166.603607 53.829025,-166.468872 53.890549,-166.437500 53.923325,-166.413498 53.969151,-166.375153 54.001030,-166.261429 53.972485,-166.215149 53.920959,-166.247940 53.876377,-166.273376 53.863319,-166.438080 53.796654,-166.469193 53.789440,-166.533081 53.780540,-166.570831 53.710274,-166.550018 53.685547,-166.531570 53.693527,-166.499176 53.722755,-166.439301 53.751240,-166.337173 53.778042,-166.270996 53.710957,-166.275421 53.681232,-166.284760 53.676384)),((-166.219452 53.704712,-166.226959 53.707497,-166.245544 53.717484,-166.287247 53.744152,-166.294449 53.753330,-166.297241 53.766930,-166.296661 53.779427,-166.291809 53.794296,-166.195145 53.834988,-166.171417 53.841103,-166.110016 53.848877,-166.090027 53.839432,-166.117493 53.774982,-166.209991 53.705269,-166.219452 53.704712)),((-167.795319 53.495537,-167.847809 53.403313,-167.848907 53.380814,-167.868042 53.371651,-168.117798 53.272484,-168.165833 53.261932,-168.193604 53.259995,-168.218628 53.255547,-168.243591 53.251099,-168.272827 53.241936,-168.285553 53.236107,-168.326828 53.208874,-168.342529 53.183868,-168.373871 53.126656,-168.467514 53.048882,-168.488892 53.038048,-168.633087 52.991936,-168.870544 52.903313,-169.041962 52.832764,-169.057220 52.828873,-169.086700 52.828049,-169.053894 52.860550,-168.969452 52.909714,-168.897934 52.932354,-168.880310 52.938324,-168.871948 52.947487,-168.775024 53.057213,-168.767227 53.070824,-168.765015 53.083881,-168.773239 53.092354,-168.793900 53.100964,-168.798920 53.114159,-168.791809 53.150127,-168.756989 53.181664,-168.735840 53.196938,-168.621399 53.272217,-168.607529 53.272629,-168.589172 53.266663,-168.557800 53.250542,-168.541382 53.246094,-168.530029 53.245270,-168.421967 53.248322,-168.367371 53.254578,-168.357239 53.262356,-168.345306 53.294716,-168.404480 53.345818,-168.409729 53.407974,-168.354050 53.473324,-168.239990 53.528603,-168.085297 53.556931,-168.005585 53.563599,-167.854980 53.519440,-167.795319 53.495537)),((172.928589 52.743881,172.900116 52.787216,172.796082 52.868050,172.774414 52.879715,172.707184 52.874161,172.638306 52.863327,172.494110 52.914436,172.478714 52.922215,172.529144 52.953049,172.544693 52.959854,172.586365 52.977211,172.647064 53.001663,172.786652 53.011940,172.889984 52.999718,173.026367 52.995544,173.123566 52.992767,173.140259 52.990273,173.311646 52.919575,173.321411 52.906586,173.297623 52.880268,173.346619 52.856941,173.436920 52.851936,173.434280 52.832077,173.425262 52.826942,173.321899 52.821106,173.194427 52.819443,173.098022 52.808327,173.010803 52.797493,172.942047 52.746937,172.928589 52.743881)),((-170.000000 52.838673,-169.989990 52.845261,-169.975586 52.849991,-169.864746 52.872208,-169.781158 52.885262,-169.760834 52.884163,-169.726105 52.881371,-169.714325 52.877907,-169.681671 52.862206,-169.677521 52.852486,-169.675049 52.817772,-169.708649 52.776932,-169.721924 52.771378,-169.734879 52.771793,-169.747238 52.778038,-169.879974 52.808884,-169.920151 52.789719,-169.960434 52.785690,-169.991516 52.800827,-170.013062 52.818329,-170.006439 52.834435,-170.000000 52.838673)),((-170.795013 52.532494,-170.840302 52.551659,-170.842224 52.566376,-170.838089 52.586655,-170.820160 52.621513,-170.745407 52.674156,-170.671707 52.694710,-170.631409 52.691933,-170.605286 52.686646,-170.592224 52.682487,-170.564590 52.669777,-170.563766 52.646938,-170.603485 52.593044,-170.615128 52.586376,-170.634766 52.581940,-170.655029 52.581383,-170.665039 52.582764,-170.688904 52.589432,-170.703476 52.590126,-170.736115 52.579987,-170.748077 52.573601,-170.770294 52.559433,-170.795013 52.532494)),((173.660248 52.348877,173.664001 52.365273,173.628845 52.391663,173.591919 52.394997,173.577057 52.393883,173.560242 52.386383,173.524414 52.380821,173.496918 52.378876,173.375107 52.401936,173.394852 52.421383,173.454407 52.450546,173.630798 52.503883,173.698578 52.508331,173.766663 52.508049,173.785400 52.503330,173.739120 52.354713,173.724670 52.352219,173.660248 52.348877)),((-174.397278 52.054993,-174.444153 52.041939,-174.609467 52.024994,-174.719757 52.002213,-174.729736 52.003052,-174.760178 52.014442,-174.787537 52.023041,-174.840271 52.031937,-174.890457 52.038185,-174.969757 52.029709,-175.001282 52.014019,-175.013351 52.002628,-175.079712 51.998322,-175.128357 52.001656,-175.183350 52.007500,-175.259766 52.008606,-175.295029 52.008190,-175.312805 51.998737,-175.334030 52.016518,-175.188324 52.043877,-175.011719 52.072762,-174.999054 52.072350,-174.979187 52.054703,-174.918060 52.106377,-174.908356 52.110687,-174.799316 52.094990,-174.666412 52.109711,-174.600830 52.119156,-174.504486 52.134575,-174.496414 52.143604,-174.506149 52.149155,-174.526978 52.145546,-174.540573 52.147488,-174.550842 52.154293,-174.554749 52.173607,-174.441696 52.212215,-174.398926 52.213326,-174.379974 52.210815,-174.364746 52.206650,-174.355576 52.202072,-174.344177 52.191933,-174.328613 52.194427,-174.279175 52.209984,-174.229309 52.246449,-174.227097 52.261517,-174.236679 52.269287,-174.345306 52.278603,-174.368637 52.277489,-174.418915 52.288319,-174.435822 52.294991,-174.446213 52.306728,-174.433929 52.319153,-174.337250 52.364998,-174.180038 52.417629,-174.158936 52.418602,-174.080292 52.390129,-174.029175 52.355820,-173.990753 52.322140,-173.993622 52.293465,-174.141998 52.123871,-174.209442 52.098877,-174.282257 52.109711,-174.374695 52.098038,-174.397278 52.054993)),((-172.521393 52.243050,-172.603760 52.248875,-172.628052 52.258324,-172.620270 52.284161,-172.611664 52.296387,-172.567230 52.334717,-172.473907 52.382767,-172.458893 52.387215,-172.438324 52.391930,-172.414185 52.389709,-172.319153 52.353600,-172.303787 52.345680,-172.296555 52.324852,-172.313904 52.311928,-172.349457 52.299988,-172.388367 52.289719,-172.437927 52.282497,-172.500336 52.257500,-172.511963 52.251099,-172.521393 52.243050)),((-173.495026 52.014992,-173.504486 52.021378,-173.561401 52.048878,-173.673920 52.057487,-173.706131 52.052071,-173.733063 52.044991,-173.827484 52.035271,-173.837494 52.036110,-173.923096 52.051659,-174.028900 52.104706,-174.056824 52.123047,-174.050720 52.132492,-173.792816 52.106102,-173.781830 52.116657,-173.772278 52.120827,-173.756439 52.124702,-173.636414 52.147484,-173.626373 52.148041,-173.591980 52.149437,-173.548920 52.146378,-173.542389 52.119568,-173.512115 52.105820,-173.440857 52.102486,-173.363312 52.101379,-173.300568 52.104153,-173.258911 52.106934,-173.183350 52.107773,-173.172546 52.107491,-173.138367 52.104439,-173.022827 52.093597,-172.959045 52.083878,-173.026672 52.070267,-173.157257 52.055260,-173.181534 52.055267,-173.213928 52.066376,-173.233627 52.071106,-173.474197 52.036106,-173.495026 52.014992)),((177.318573 51.821106,177.289429 51.852493,177.244537 51.875824,177.248016 51.902214,177.366638 51.969986,177.388885 51.977768,177.464691 51.987770,177.523315 52.046104,177.553589 52.100548,177.569427 52.113052,177.599136 52.126240,177.613434 52.127213,177.677475 52.105827,177.684906 52.084297,177.608078 51.923466,177.565247 51.911659,177.494690 51.923882,177.466354 51.936100,177.453033 51.936653,177.404709 51.926800,177.394135 51.922768,177.376892 51.912491,177.351074 51.894440,177.341217 51.883606,177.318573 51.821106)),((-176.054749 51.961655,-176.070282 51.965828,-176.167526 51.994572,-176.189743 52.039433,-176.191986 52.051102,-176.189178 52.062351,-176.165588 52.091103,-176.152222 52.103325,-176.133606 52.108330,-176.050552 52.102909,-176.041718 52.098038,-175.995300 52.029160,-176.018356 51.971645,-176.037231 51.964432,-176.054749 51.961655)),((179.649719 51.867210,179.639709 51.867493,179.560791 51.883606,179.531097 51.891937,179.500000 51.914154,179.489548 51.930271,179.486908 51.974297,179.628708 52.028049,179.642761 52.028328,179.658600 52.024712,179.768997 51.966103,179.775940 51.952976,179.753326 51.920273,179.737457 51.903046,179.649719 51.867210)),((178.528046 51.893326,178.519135 51.894157,178.500259 51.899017,178.466919 51.920547,178.453171 51.941795,178.476410 51.986244,178.518860 51.987495,178.576630 51.971100,178.587463 51.963882,178.606628 51.946102,178.603577 51.932213,178.567062 51.900131,178.536926 51.893608,178.528046 51.893326)),((-176.938629 51.584435,-176.961945 51.590271,-176.976685 51.598183,-176.980988 51.616379,-176.972260 51.657761,-176.893341 51.765831,-176.781403 51.830269,-176.783356 51.925262,-176.775162 51.942276,-176.758362 51.950829,-176.743042 51.954987,-176.605560 51.985550,-176.584747 51.986382,-176.559769 51.984711,-176.548080 51.978325,-176.540283 51.923599,-176.548355 51.907902,-176.558044 51.903870,-176.587799 51.905823,-176.605698 51.901375,-176.642242 51.857216,-176.594040 51.830406,-176.582520 51.829987,-176.554993 51.839149,-176.465027 51.843597,-176.430283 51.837349,-176.423630 51.827770,-176.416687 51.749718,-176.427521 51.732346,-176.466980 51.719147,-176.530609 51.726929,-176.707672 51.677624,-176.723602 51.659157,-176.913086 51.603882,-176.938629 51.584435)),((-177.642242 51.649437,-177.651978 51.649994,-177.669327 51.656376,-177.702789 51.698460,-177.639465 51.732487,-177.626923 51.732491,-177.610565 51.726791,-177.565857 51.717484,-177.536133 51.715828,-177.525330 51.716103,-177.294769 51.776932,-177.243347 51.793320,-177.213043 51.808884,-177.200638 51.824024,-177.199768 51.844704,-177.197784 51.882767,-177.195587 51.920540,-177.178238 51.933876,-177.157257 51.938324,-177.141953 51.937763,-177.105286 51.929710,-177.093079 51.926659,-177.079712 51.921097,-177.047791 51.903183,-177.044876 51.891930,-177.122223 51.784431,-177.129333 51.721657,-177.153900 51.699425,-177.260590 51.671928,-177.270599 51.672493,-177.285858 51.676384,-177.333893 51.702766,-177.374176 51.726372,-177.384216 51.726929,-177.425842 51.724991,-177.623611 51.694290,-177.640015 51.680550,-177.642242 51.649437)),((-177.907806 51.591927,-177.949982 51.606377,-178.087494 51.659424,-178.100830 51.664711,-178.092102 51.696369,-178.081116 51.698738,-178.066147 51.694427,-178.036545 51.695683,-177.971680 51.714149,-177.954880 51.720951,-177.948761 51.730820,-177.949982 51.746941,-177.954041 51.761936,-177.962784 51.770550,-178.069733 51.810822,-178.171661 51.846657,-178.216522 51.863602,-178.216553 51.874294,-178.186966 51.896931,-178.171417 51.904427,-178.151840 51.909706,-178.109161 51.914711,-177.941696 51.918606,-177.930573 51.915268,-177.886169 51.884438,-177.825317 51.831100,-177.797241 51.788879,-177.813904 51.719704,-177.879150 51.684708,-177.911133 51.659424,-177.913208 51.637356,-177.907806 51.591927)),((-176.139191 51.774437,-176.143341 51.774437,-176.155609 51.780540,-176.216125 51.817768,-176.219040 51.834438,-176.207672 51.876789,-176.179199 51.881653,-176.169189 51.881104,-176.023926 51.848038,-176.013916 51.833042,-176.006134 51.809708,-176.021698 51.816666,-176.032501 51.823318,-176.140320 51.819920,-176.150330 51.800545,-176.149200 51.788879,-176.139191 51.774437)),((-176.336426 51.721657,-176.345001 51.721657,-176.381943 51.728039,-176.392548 51.738602,-176.396973 51.749718,-176.404343 51.776100,-176.416153 51.852493,-176.392548 51.860550,-176.318909 51.866936,-176.308929 51.867760,-176.278091 51.859158,-176.264496 51.811371,-176.261169 51.780266,-176.327072 51.726101,-176.336426 51.721657)),((179.252197 51.347488,179.030823 51.487213,179.022217 51.495544,178.970795 51.532494,178.959961 51.539719,178.892487 51.563324,178.843170 51.571941,178.827057 51.569164,178.774414 51.569160,178.716202 51.584023,178.660797 51.618050,178.649994 51.625267,178.638321 51.635410,178.669693 51.656242,178.682190 51.656654,178.694122 51.648880,178.730103 51.634018,178.883026 51.618462,178.900543 51.613609,178.914429 51.608604,178.981354 51.581383,178.994965 51.572773,179.007355 51.551941,179.033600 51.529991,179.075256 51.500832,179.250519 51.407074,179.293304 51.409988,179.384705 51.402489,179.457886 51.380684,179.468018 51.367634,179.405869 51.364182,179.398590 51.374714,179.385529 51.374710,179.291351 51.358330,179.274414 51.354713,179.252197 51.347488)),((-76.028992 36.549995,-76.038887 36.518188,-76.034729 36.496658,-75.986938 36.411659,-75.946655 36.371933,-75.916397 36.351387,-75.883331 36.295547,-75.796387 36.118050,-75.793152 36.073849,-75.852707 36.110687,-75.938950 36.283813,-75.976036 36.311378,-75.997353 36.310825,-75.952873 36.192406,-75.926537 36.170891,-75.949432 36.168602,-76.004654 36.181103,-76.032417 36.202213,-76.042747 36.219738,-76.139862 36.288052,-76.199654 36.317390,-76.222641 36.292496,-76.183609 36.269157,-76.150772 36.258675,-76.092163 36.197601,-76.075912 36.179100,-76.070969 36.149296,-76.214172 36.094711,-76.235825 36.094994,-76.334167 36.134720,-76.370834 36.149994,-76.367767 36.118324,-76.371384 36.076942,-76.495270 36.009579,-76.518616 36.006939,-76.659790 36.033119,-76.691170 36.071644,-76.710213 36.117519,-76.727638 36.167355,-76.718887 36.209435,-76.704582 36.246727,-76.746101 36.228184,-76.757507 36.204159,-76.760284 36.145130,-76.753838 36.094772,-76.733917 36.047600,-76.729515 35.939850,-76.662216 35.933048,-76.553749 35.939713,-76.529724 35.946102,-76.470276 35.964993,-76.420135 35.978737,-76.392776 35.975269,-76.379852 35.957630,-76.279175 35.919159,-76.267502 35.918884,-76.301735 35.954052,-76.174721 35.995964,-76.077507 35.993187,-76.051109 35.982212,-76.026527 35.962215,-76.021812 35.922771,-76.053047 35.873741,-76.060272 35.846939,-76.053055 35.793610,-76.041672 35.749161,-76.044754 35.684364,-76.109581 35.691307,-76.135628 35.692387,-76.103195 35.660408,-76.028748 35.654091,-75.993881 35.710274,-75.988541 35.791103,-75.995544 35.813324,-75.989441 35.880547,-75.970695 35.897770,-75.943329 35.917770,-75.850830 35.975269,-75.824730 35.964993,-75.783325 35.919716,-75.749168 35.877907,-75.720833 35.814507,-75.720833 35.692631,-75.740761 35.618465,-75.789444 35.571384,-75.816956 35.566101,-75.838333 35.566940,-75.860001 35.584717,-75.893616 35.575554,-75.979584 35.516663,-76.002228 35.466103,-76.041107 35.424164,-76.133194 35.359856,-76.149170 35.336937,-76.461945 35.372211,-76.496109 35.384720,-76.522507 35.404160,-76.567108 35.484936,-76.563751 35.508812,-76.515564 35.531937,-76.588196 35.551033,-76.614861 35.535828,-76.631943 35.522491,-76.616104 35.458885,-76.601395 35.431381,-76.652496 35.414993,-76.912918 35.461662,-76.942635 35.477283,-77.049583 35.526939,-77.023056 35.486935,-76.832504 35.392220,-76.502983 35.307907,-76.468887 35.271660,-76.487495 35.225822,-76.563614 35.233604,-76.664894 35.166935,-76.573051 35.160130,-76.552917 35.137909,-76.565552 35.114853,-76.604019 35.074162,-76.654175 35.043327,-76.727081 35.001522,-76.761398 34.987770,-76.805305 34.985588,-76.836060 34.992550,-76.867218 35.000000,-76.976395 35.068054,-77.068161 35.149780,-76.965012 34.997772,-76.931801 34.969574,-76.889999 34.953880,-76.840691 34.943516,-76.816353 34.939434,-76.778885 34.926659,-76.753067 34.905266,-76.738747 34.918606,-76.697220 34.948875,-76.633820 34.982422,-76.529175 35.004440,-76.489441 35.009163,-76.453568 35.066761,-76.432365 35.042774,-76.433952 34.987816,-76.462296 34.962978,-76.453194 34.935234,-76.415329 34.941154,-76.323547 34.974293,-76.333755 34.996246,-76.351250 35.022213,-76.312637 35.012634,-76.271812 34.962631,-76.292496 34.936935,-76.343262 34.881939,-76.383049 34.864227,-76.411392 34.847771,-76.481384 34.776382,-76.500626 34.736172,-76.626106 34.710133,-76.653610 34.717281,-76.660973 34.757809,-76.683258 34.797493,-76.759933 34.766590,-77.094238 34.677422,-77.123322 34.693321,-77.175552 34.654709,-77.273056 34.584435,-77.309578 34.559715,-77.333900 34.575993,-77.350235 34.600990,-77.330971 34.639923,-77.388474 34.733047,-77.428879 34.741936,-77.424438 34.713051,-77.409439 34.689156,-77.385719 34.612602,-77.379044 34.562935,-77.381729 34.516453,-77.421249 34.514442,-77.455276 34.504025,-77.573624 34.436935,-77.614578 34.412216,-77.636673 34.398048,-77.664444 34.379433,-77.682220 34.365547,-77.705276 34.341934,-77.757233 34.285271,-77.835007 34.191933,-77.862221 34.150826,-77.869720 34.130821,-77.882149 34.061661,-77.884171 34.032768,-77.922638 33.937145,-77.934433 33.926941,-77.922501 33.991936,-77.920692 34.019299,-77.927284 34.117561,-77.955627 34.149017,-77.950836 34.119438,-77.947769 34.091377,-77.944992 34.064995,-77.946243 34.028744,-77.952988 33.992424,-77.976112 33.942768,-78.025970 33.889366,-78.069733 33.894997,-78.101395 33.904709,-78.153893 33.914711,-78.237358 33.919853,-78.437210 33.898048,-78.518066 33.879990,-78.572220 33.881668,-78.582092 33.879295,-78.600555 33.870827,-78.827499 33.730270,-78.861252 33.707214,-78.881378 33.691933,-78.917770 33.657494,-78.937500 33.638046,-78.980835 33.591660,-79.137642 33.415684,-79.148621 33.389439,-79.164169 33.314438,-79.196442 33.278938,-79.269104 33.314159,-79.263481 33.336937,-79.237289 33.377213,-79.199684 33.430271,-79.226105 33.413322,-79.271393 33.373322,-79.289581 33.329441,-79.295692 33.305134,-79.294579 33.284161,-79.282501 33.266388,-79.255608 33.244049,-79.224777 33.232552,-79.204727 33.185547,-79.205841 33.165543,-79.233063 33.141106,-79.297073 33.099209,-79.344353 33.079758,-79.371719 33.058945,-79.388336 33.008190,-79.445267 33.004715,-79.494438 33.009163,-79.523193 33.033398,-79.571388 33.015549,-79.602501 32.986519,-79.627907 32.939297,-79.612221 32.917496,-79.732635 32.804157,-79.794724 32.775269,-79.815826 32.767212,-79.857338 32.770718,-79.883972 32.790882,-79.893677 32.818188,-79.878395 32.838810,-79.895416 32.852009,-79.942635 32.853466,-79.969170 32.787910,-79.950134 32.763329,-79.910194 32.745148,-79.882393 32.727730,-79.877983 32.694851,-79.900284 32.673882,-79.917221 32.662491,-79.987778 32.618324,-80.046951 32.606102,-80.222778 32.540833,-80.327721 32.480408,-80.409164 32.471657,-80.431900 32.498363,-80.536942 32.514999,-80.611389 32.520271,-80.669304 32.522911,-80.680008 32.500168,-80.555000 32.485756,-80.530556 32.491173,-80.482086 32.475128,-80.429512 32.398048,-80.442490 32.351936,-80.465004 32.317493,-80.533325 32.286110,-80.574448 32.268051,-80.631378 32.256386,-80.643074 32.293785,-80.641663 32.342991,-80.653610 32.422768,-80.674438 32.450272,-80.674713 32.397217,-80.682610 32.328159,-80.711121 32.319717,-80.764519 32.372700,-80.798050 32.461380,-80.806946 32.500275,-80.832367 32.519993,-80.827499 32.462494,-80.816254 32.419163,-80.783325 32.310547,-80.766403 32.284721,-80.740341 32.260063,-80.710350 32.258884,-80.672287 32.217075,-80.720695 32.156658,-80.819725 32.109577,-80.801102 32.152489,-80.825562 32.156654,-80.879166 32.079437,-80.896187 32.041798,-80.892960 32.027855,-80.835419 32.006279,-80.854721 31.971939,-80.934578 31.894579,-80.977707 31.861940,-81.055557 31.792221,-81.121933 31.728607,-81.126938 31.692633,-81.136948 31.613331,-81.165901 31.564857,-81.241753 31.560108,-81.279030 31.565275,-81.302498 31.567776,-81.329025 31.554789,-81.284096 31.491106,-81.252060 31.501802,-81.204727 31.474716,-81.277496 31.357220,-81.293884 31.323051,-81.268959 31.267185,-81.284233 31.221245,-81.386040 31.162432,-81.404083 31.177626,-81.408539 31.205063,-81.444099 31.207216,-81.488434 31.113468,-81.435638 31.084692,-81.409882 31.089731,-81.419441 31.029026,-81.459595 30.942219,-81.473610 30.927217,-81.501389 30.900692,-81.533752 30.849442,-81.510147 30.800276,-81.492912 30.777916,-81.487289 30.752010,-81.495270 30.732216,-81.507339 30.713463,-81.472778 30.691940,-81.435272 30.639439,-81.444153 30.573051,-81.453064 30.508331,-81.412506 30.467079,-81.390701 30.384996,-81.392776 30.358051,-81.390839 30.283192,-81.386124 30.261108,-81.361115 30.190273,-81.329727 30.074440,-81.304169 29.973885,-81.287216 29.903885,-81.255280 29.796665,-81.248047 29.776665,-81.185272 29.619717,-81.159164 29.558331,-81.013901 29.243050,-80.966110 29.153049,-80.829727 28.939716,-80.702499 28.747215,-80.681175 28.715965,-80.638474 28.669161,-80.587219 28.590553,-80.565979 28.554581,-80.552490 28.524998,-80.535172 28.449335,-80.559860 28.432495,-80.596954 28.402218,-80.597778 28.339165,-80.597778 28.274166,-80.597778 28.246662,-80.595551 28.226105,-80.590836 28.194717,-80.586945 28.173607,-80.580841 28.142220,-80.573059 28.111107,-80.561386 28.079441,-80.536942 28.033747,-80.496658 27.968884,-80.475006 27.935829,-80.464172 27.918327,-80.446136 27.874475,-80.446655 27.864441,-80.507782 27.954716,-80.561386 28.044580,-80.593056 28.114859,-80.600830 28.137497,-80.607224 28.161106,-80.620277 28.217911,-80.621658 28.328053,-80.616943 28.402775,-80.605278 28.424856,-80.591675 28.468884,-80.584305 28.501663,-80.584656 28.548885,-80.603195 28.608608,-80.659302 28.608330,-80.674576 28.588955,-80.755348 28.604370,-80.782494 28.635689,-80.770348 28.687181,-80.745056 28.708118,-80.751457 28.731731,-80.813049 28.771664,-80.843613 28.780970,-80.823059 28.651661,-80.757233 28.420691,-80.718887 28.337498,-80.576675 28.034443,-80.486938 27.854164,-80.460899 27.812565,-80.441940 27.787220,-80.432495 27.769165,-80.397232 27.695549,-80.385559 27.668606,-80.371933 27.632217,-80.356033 27.583330,-80.349518 27.538191,-80.312073 27.429995,-80.215012 27.193607,-80.150970 27.138189,-80.105270 27.051662,-80.082512 26.985687,-80.051666 26.864441,-80.035339 26.795691,-80.028748 26.632357,-80.035210 26.552984,-80.046387 26.514999,-80.050827 26.492493,-80.067505 26.383606,-80.094727 26.200550,-80.136124 25.905552,-80.191238 25.743189,-80.255844 25.684162,-80.312912 25.599371,-80.313324 25.542496,-80.311935 25.538052,-80.339447 25.502426,-80.376099 25.319717,-80.421112 25.249857,-80.419441 25.207911,-80.397507 25.186655,-80.415306 25.191210,-80.453545 25.241938,-80.488869 25.216330,-80.503151 25.198746,-80.510910 25.233984,-80.539993 25.245548,-80.573967 25.240549,-80.652222 25.186939,-80.682220 25.163609,-80.827789 25.162216,-81.046661 25.127773,-81.088058 25.115551,-81.103333 25.126385,-81.146675 25.160412,-81.177498 25.240480,-81.135612 25.320538,-81.108673 25.298719,-81.091667 25.280275,-81.003342 25.211105,-80.977211 25.200897,-80.928886 25.219854,-80.917847 25.246872,-80.954453 25.299164,-80.990837 25.322426,-81.042503 25.329580,-81.107719 25.365398,-81.126389 25.379524,-81.144867 25.408329,-81.172226 25.471107,-81.327652 25.788054,-81.340904 25.809719,-81.376801 25.835691,-81.402222 25.848885,-81.558609 25.919716,-81.618332 25.930550,-81.674713 25.914440,-81.736588 25.959442,-81.780563 26.086941,-81.800415 26.099997,-81.811111 26.138885,-81.816956 26.165550,-81.841110 26.349998,-81.881622 26.445688,-81.969307 26.481829,-81.955246 26.501204,-81.918724 26.512329,-81.922775 26.533607,-81.785934 26.706903,-81.891121 26.660275,-81.915619 26.628052,-81.920067 26.599300,-81.948746 26.540831,-82.023376 26.529219,-82.066948 26.554373,-82.080002 26.683884,-82.079727 26.707771,-82.049438 26.847775,-82.017227 26.964718,-82.100281 26.952496,-82.191940 26.938049,-82.164169 26.874165,-82.150833 26.818886,-82.158890 26.782879,-82.291107 26.829580,-82.309441 26.844440,-82.378883 26.935411,-82.396393 26.962357,-82.424438 27.021942,-82.456116 27.090832,-82.538399 27.288538,-82.544998 27.319717,-82.571533 27.391247,-82.587219 27.409718,-82.655273 27.461662,-82.646118 27.465271,-82.590836 27.496939,-82.583755 27.550276,-82.616104 27.553608,-82.547501 27.640553,-82.534729 27.656662,-82.465836 27.732910,-82.442215 27.744995,-82.405006 27.780691,-82.388542 27.821108,-82.407501 27.880550,-82.424164 27.919439,-82.443329 27.930828,-82.691246 28.029858,-82.714928 27.925621,-82.637512 27.883606,-82.603607 27.873051,-82.595070 27.821873,-82.622772 27.722496,-82.636528 27.696106,-82.724724 27.658051,-82.744446 27.679440,-82.835007 27.814442,-82.843887 27.832775,-82.854164 27.858608,-82.852295 27.894857,-82.827782 27.941730,-82.835732 27.897182,-82.809433 27.936661,-82.797501 27.969715,-82.773895 28.070274,-82.749725 28.230549,-82.716110 28.305553,-82.664032 28.436939,-82.641678 28.539440,-82.628601 28.696384,-82.636810 28.752359,-82.654175 28.767776,-82.675621 28.804058,-82.641113 28.825829,-82.628883 28.849581,-82.629715 28.880135,-82.644585 28.894995,-82.750839 29.007500,-82.769455 29.070553,-82.802780 29.154995,-82.831955 29.163883,-82.933060 29.182774,-82.962639 29.186245,-82.983749 29.179718,-83.071671 29.224438,-83.100281 29.274441,-83.222504 29.422771,-83.352219 29.505276,-83.374435 29.514164,-83.398064 29.525414,-83.407501 29.575829,-83.428055 29.668327,-83.466949 29.680550,-83.536667 29.722633,-83.578270 29.766525,-83.583267 29.805414,-83.631943 29.875690,-83.669449 29.906105,-83.737778 29.952496,-83.788193 29.974091,-83.824448 29.984440,-83.889305 30.017637,-83.937500 30.050552,-84.010979 30.097637,-84.031677 30.101387,-84.205559 30.105692,-84.264313 30.096386,-84.329178 30.070831,-84.459030 29.997078,-84.437492 29.958050,-84.412361 29.955551,-84.386124 29.958050,-84.336739 29.941452,-84.334999 29.919996,-84.347290 29.894371,-84.376556 29.904804,-84.409729 29.916939,-84.449310 29.920969,-84.515839 29.914719,-84.550827 29.899441,-84.574722 29.886940,-84.651947 29.845829,-84.722778 29.800831,-84.752228 29.781248,-84.830002 29.751110,-84.865555 29.737495,-84.885284 29.747215,-84.864159 29.795588,-84.915009 29.779720,-84.977783 29.733604,-85.059998 29.719994,-85.208893 29.699440,-85.295273 29.688885,-85.341675 29.676384,-85.357086 29.677773,-85.374306 29.691107,-85.386673 29.710966,-85.400558 29.751663,-85.412224 29.793747,-85.413330 29.813885,-85.399200 29.864681,-85.399025 29.821108,-85.396667 29.791664,-85.385704 29.741104,-85.372223 29.713882,-85.347115 29.686974,-85.306595 29.699995,-85.302216 29.744160,-85.307213 29.815969,-85.362907 29.897911,-85.405830 29.933605,-85.546387 30.033886,-85.613602 30.069998,-85.629395 30.104628,-85.598686 30.102356,-85.550316 30.074566,-85.521538 30.060553,-85.476952 30.025829,-85.439438 30.017672,-85.393890 30.041525,-85.413193 30.055412,-85.442490 30.054165,-85.647385 30.145996,-85.688248 30.190666,-85.663620 30.246105,-85.746948 30.297218,-85.838684 30.287428,-85.845551 30.247080,-85.829727 30.227633,-85.803535 30.241451,-85.764030 30.240273,-85.738998 30.198828,-85.722580 30.162161,-85.725555 30.125828,-85.779999 30.162773,-85.830292 30.195549,-85.872223 30.216938,-85.902496 30.232216,-85.929993 30.244717,-86.030838 30.283886,-86.085831 30.303608,-86.164719 30.329441,-86.255554 30.358330,-86.312500 30.372498,-86.337364 30.384439,-86.162506 30.390831,-86.104233 30.379093,-86.122772 30.426105,-86.197495 30.473049,-86.260002 30.495829,-86.438049 30.496105,-86.492912 30.469995,-86.598053 30.414995,-86.618332 30.414997,-86.664444 30.417217,-86.708618 30.419163,-86.780289 30.416664,-86.926666 30.399162,-86.970840 30.393330,-87.072227 30.378609,-87.098343 30.373051,-87.126099 30.363884,-87.175537 30.369823,-87.115829 30.394440,-87.084862 30.400829,-87.009453 30.407495,-86.986252 30.417219,-86.936386 30.449997,-86.953613 30.470829,-87.012512 30.519997,-87.101944 30.526665,-87.160835 30.517775,-87.153198 30.498608,-87.156670 30.472149,-87.179718 30.431664,-87.266113 30.351109,-87.302109 30.345448,-87.306656 30.321384,-87.334167 30.314720,-87.453064 30.290554,-87.522560 30.279293,-87.498543 30.303329,-87.458801 30.306871,-87.418053 30.338329,-87.340836 30.434578,-87.355064 30.456314,-87.420395 30.480946,-87.408890 30.452774,-87.422775 30.420551,-87.463341 30.359720,-87.568619 30.279442,-87.655975 30.251942,-87.733612 30.234993,-87.777222 30.231663,-88.021355 30.225479,-87.952499 30.248329,-87.915283 30.244995,-87.873741 30.237564,-87.778191 30.262915,-87.757713 30.282429,-87.763405 30.303051,-87.831680 30.360828,-87.871796 30.384300,-87.908409 30.409718,-87.934158 30.495274,-87.917778 30.533886,-87.909447 30.569443,-87.913055 30.593887,-87.930550 30.641106,-87.949028 30.670341,-88.020279 30.701107,-88.082504 30.574720,-88.100975 30.512638,-88.102219 30.470272,-88.107224 30.397495,-88.111107 30.367081,-88.131454 30.318954,-88.194023 30.331524,-88.192314 30.359928,-88.353401 30.404232,-88.402191 30.387665,-88.405975 30.356386,-88.457924 30.317495,-88.484444 30.323051,-88.559860 30.348330,-88.614441 30.363609,-88.696106 30.345692,-88.722504 30.346386,-88.744720 30.354164,-88.788193 30.377634,-88.832504 30.413052,-88.980835 30.418327,-88.985001 30.386383,-89.202354 30.327082,-89.264450 30.318262,-89.311798 30.310553,-89.448257 30.184299,-89.498611 30.183884,-89.522064 30.186855,-89.593124 30.153259,-89.695000 30.183773,-89.819733 30.223328,-89.979584 30.266386,-89.987915 30.301107,-90.000832 30.319164,-90.063889 30.358885,-90.089447 30.365551,-90.187630 30.387774,-90.213753 30.386942,-90.236252 30.376524,-90.415001 30.203468,-90.427910 30.178606,-90.430550 30.151800,-90.425140 30.123468,-90.412636 30.097914,-90.349731 30.061665,-90.170135 30.023470,-90.131668 30.022221,-90.034027 30.036665,-89.811935 30.099163,-89.722313 30.142731,-89.673538 30.167149,-89.642647 30.133192,-89.719162 30.058052,-89.769516 30.044302,-89.805695 30.044304,-89.827789 30.032915,-89.843750 30.007082,-89.835556 29.981106,-89.817848 29.945480,-89.683609 29.879025,-89.658051 29.873886,-89.625694 29.873398,-89.589302 29.899578,-89.565826 29.961105,-89.476318 30.074614,-89.399445 30.050831,-89.333755 29.878191,-89.404175 29.762497,-89.412216 29.790276,-89.429718 29.808331,-89.448044 29.821384,-89.476387 29.832287,-89.590561 29.738884,-89.662506 29.666386,-89.752716 29.632980,-89.677780 29.525692,-89.519165 29.462494,-89.464172 29.403049,-89.317505 29.350552,-89.255844 29.334721,-89.187210 29.339718,-89.029175 29.215828,-89.009315 29.196383,-89.008759 29.174162,-89.021667 29.140274,-89.042358 29.110413,-89.153885 29.039997,-89.249435 29.096107,-89.306946 29.042221,-89.325844 29.018330,-89.338333 28.986799,-89.363052 28.953606,-89.390625 28.932077,-89.404999 28.926662,-89.413055 28.931107,-89.397499 28.974579,-89.381248 28.989300,-89.365829 29.003609,-89.301941 29.082497,-89.272018 29.149649,-89.324310 29.178049,-89.329659 29.153120,-89.323753 29.121803,-89.331390 29.101664,-89.355415 29.086664,-89.389580 29.092081,-89.478607 29.233604,-89.608398 29.251108,-89.708344 29.300831,-89.770561 29.339163,-89.750832 29.360552,-89.773338 29.414858,-89.831680 29.443886,-89.985275 29.486382,-90.119156 29.551388,-90.182495 29.569859,-90.203270 29.544720,-90.191101 29.510830,-90.172081 29.488050,-90.124863 29.465828,-90.096664 29.461384,-90.058746 29.459578,-90.026527 29.425135,-90.056946 29.311943,-90.051590 29.221523,-90.065826 29.183331,-90.115967 29.139025,-90.135834 29.126385,-90.209442 29.091108,-90.237503 29.083607,-90.247772 29.082497,-90.235970 29.092220,-90.235695 29.118467,-90.255569 29.197216,-90.272781 29.259720,-90.345001 29.309162,-90.393616 29.317497,-90.444443 29.326107,-90.524445 29.289719,-90.589722 29.233330,-90.647232 29.158051,-90.678604 29.129719,-90.702019 29.115829,-90.765015 29.109440,-90.878326 29.128746,-90.912216 29.150829,-90.930000 29.164301,-90.998894 29.219233,-91.035347 29.213120,-91.048325 29.194162,-91.077644 29.194855,-91.096954 29.202217,-91.194717 29.226940,-91.219452 29.231663,-91.254868 29.244301,-91.277916 29.255833,-91.299438 29.271385,-91.322235 29.295277,-91.339310 29.324718,-91.223328 29.360554,-91.162148 29.329788,-91.163055 29.293192,-91.173470 29.273607,-91.149239 29.249439,-91.117706 29.262497,-91.114441 29.325415,-91.126526 29.347359,-91.267227 29.466938,-91.415009 29.540276,-91.523056 29.532219,-91.543335 29.542774,-91.551102 29.586109,-91.557144 29.630482,-91.631035 29.739023,-91.664169 29.748604,-91.823898 29.795553,-91.838821 29.828260,-91.899170 29.836109,-92.148621 29.768887,-92.175827 29.690273,-92.099731 29.615551,-92.137222 29.589996,-92.273201 29.540970,-92.308334 29.539719,-92.337219 29.542221,-92.570007 29.575829,-92.687775 29.600273,-92.751114 29.620689,-92.813614 29.643887,-92.855270 29.663052,-92.905563 29.693327,-93.037506 29.739162,-93.118332 29.763611,-93.144730 29.769444,-93.240829 29.784996,-93.272232 29.786942,-93.299988 29.786663,-93.667770 29.763885,-93.719307 29.759165,-93.750000 29.749996,-93.794029 29.727356,-93.823471 29.708189,-93.850487 29.708815,-93.885559 29.745274,-93.900978 29.791109,-93.892014 29.817566,-93.862083 29.830692,-93.811867 29.833885,-93.773064 29.900414,-93.768028 29.976278,-93.789726 29.994856,-93.796661 29.994160,-93.852013 29.985132,-93.958473 29.816662,-93.947495 29.786318,-93.914719 29.765553,-93.890701 29.740412,-93.858437 29.681625,-93.890907 29.672148,-93.920273 29.681522,-94.036392 29.679161,-94.068344 29.674164,-94.134300 29.653606,-94.317505 29.584164,-94.458893 29.527496,-94.619995 29.461941,-94.653610 29.447079,-94.683609 29.429161,-94.708061 29.409441,-94.733749 29.380692,-94.754173 29.367912,-94.786942 29.373537,-94.781113 29.397219,-94.692078 29.467495,-94.612213 29.494438,-94.515419 29.516525,-94.476593 29.558886,-94.574028 29.573191,-94.675552 29.552776,-94.765839 29.568054,-94.730423 29.612913,-94.722084 29.633747,-94.717224 29.653328,-94.706665 29.711105,-94.711044 29.756804,-94.757019 29.784998,-94.824310 29.761942,-94.840561 29.749161,-94.955559 29.695829,-95.007088 29.716522,-95.060066 29.715063,-95.015839 29.565552,-94.897987 29.420897,-94.887505 29.385275,-94.893898 29.337776,-94.902786 29.314442,-95.086945 29.181940,-95.148613 29.051249,-95.303192 28.931524,-95.331955 28.912773,-95.359726 28.896107,-95.618332 28.755552,-95.689888 28.738132,-95.745674 28.737301,-95.797226 28.736938,-95.941109 28.686417,-95.941521 28.626316,-95.896118 28.639996,-95.876099 28.650272,-95.847778 28.668190,-95.816978 28.680830,-95.765511 28.692488,-95.827225 28.648331,-95.858047 28.635273,-95.895554 28.621384,-95.929443 28.610275,-95.951675 28.603607,-95.979027 28.598469,-96.000565 28.590275,-96.036118 28.573608,-96.059433 28.560829,-96.064163 28.557499,-96.131104 28.521942,-96.156387 28.510555,-96.212013 28.488119,-96.195618 28.509789,-96.146667 28.538330,-96.072365 28.573885,-96.045837 28.584442,-96.025284 28.591942,-95.996521 28.603886,-95.981667 28.632357,-95.990685 28.651037,-96.029724 28.644997,-96.059158 28.634441,-96.081390 28.622772,-96.106949 28.612217,-96.133614 28.602079,-96.217430 28.581942,-96.207222 28.603260,-96.183189 28.602774,-96.140800 28.627287,-96.192078 28.695480,-96.267365 28.685135,-96.394112 28.736189,-96.442909 28.760277,-96.437653 28.725885,-96.408676 28.635481,-96.375549 28.622009,-96.411530 28.601385,-96.431938 28.599302,-96.495544 28.619442,-96.555199 28.647774,-96.562637 28.674164,-96.562561 28.697563,-96.594719 28.719231,-96.644730 28.711939,-96.651321 28.685551,-96.583893 28.566940,-96.489990 28.509441,-96.399971 28.441730,-96.624710 28.324165,-96.659309 28.315207,-96.697006 28.334093,-96.702225 28.369995,-96.707085 28.397703,-96.746948 28.437775,-96.800339 28.471521,-96.845215 28.409857,-96.831810 28.388050,-96.783821 28.348955,-96.780838 28.241383,-96.882767 28.140274,-96.930969 28.127079,-96.983337 28.121107,-97.016113 28.135830,-97.028061 28.186382,-97.169373 28.161800,-97.213470 28.068537,-97.182915 28.060274,-97.146667 28.039997,-97.144165 28.028053,-97.098061 28.069719,-97.046112 28.091663,-97.025833 28.078609,-97.022499 28.031666,-97.194511 27.821802,-97.226456 27.820900,-97.345276 27.852497,-97.492493 27.878052,-97.517090 27.863815,-97.484718 27.825830,-97.392776 27.783333,-97.315552 27.715549,-97.279724 27.656105,-97.386948 27.395275,-97.412987 27.327288,-97.489998 27.306248,-97.525284 27.377220,-97.624695 27.344803,-97.638275 27.370884,-97.676941 27.385551,-97.723328 27.432217,-97.769341 27.449717,-97.723328 27.395550,-97.676697 27.316982,-97.660828 27.276665,-97.633888 27.252497,-97.533890 27.235271,-97.476944 27.257774,-97.429367 27.262289,-97.444443 27.128052,-97.475006 27.030830,-97.557419 27.005484,-97.565552 26.981800,-97.560410 26.842081,-97.539856 26.816872,-97.504028 26.807011,-97.491943 26.790276,-97.477493 26.739437,-97.423050 26.545551,-97.412781 26.411942,-97.401947 26.369442,-97.369438 26.365137,-97.318619 26.246105,-97.319458 26.213329,-97.317505 26.161385,-97.307220 26.122772,-97.240768 25.981939,-97.209312 25.992495,-97.180656 26.027704,-97.167877 26.070135,-97.150558 26.040276,-97.146118 26.017220,-97.141037 25.979725,-97.140739 25.966429,-97.160843 25.967220,-97.265289 25.941109,-97.315292 25.919998,-97.346680 25.893053,-97.344734 25.859652,-97.364731 25.839859,-97.417229 25.843330,-97.514450 25.898329,-97.559448 25.951111,-97.614456 26.004997,-97.648056 26.029442,-97.678902 26.038054,-97.803345 26.058052,-97.847511 26.063610,-97.979736 26.058609,-98.033340 26.047775,-98.060143 26.038887,-98.200012 26.062496,-98.286118 26.097775,-98.305283 26.109165,-98.361389 26.153610,-98.388062 26.191666,-98.439873 26.223331,-98.578339 26.256107,-98.604736 26.256664,-98.695564 26.289721,-98.730011 26.314442,-98.784180 26.348888,-98.925293 26.391388,-98.975571 26.405830,-99.104736 26.434998,-99.132507 26.526943,-99.200562 26.714443,-99.239731 26.803608,-99.253342 26.830830,-99.271126 26.859928,-99.319244 26.869858,-99.458618 27.046944,-99.443344 27.258053,-99.473198 27.476665,-99.503899 27.568052,-99.530838 27.600067,-99.606186 27.641247,-99.653625 27.641388,-99.696396 27.656944,-99.713898 27.668938,-99.727432 27.689163,-99.741402 27.714720,-99.758896 27.727150,-99.782303 27.737637,-99.798203 27.766665,-99.806702 27.771748,-99.832924 27.774303,-99.860909 27.805136,-99.871948 27.855553,-99.880836 27.903887,-99.935013 27.961666,-99.962234 27.984722,-100.050842 28.116386,-100.078339 28.155622,-100.108475 28.165691,-100.186401 28.197498,-100.240280 28.242775,-100.281464 28.280552,-100.331261 28.400414,-100.329590 28.425415,-100.350845 28.494720,-100.359177 28.518330,-100.399445 28.571110,-100.443893 28.626389,-100.479866 28.675833,-100.492371 28.704165,-100.491821 28.725712,-100.527367 28.822777,-100.564453 28.863609,-100.590561 28.894722,-100.621948 28.933331,-100.634453 28.958609,-100.628204 28.995831,-100.665840 29.109026,-100.795708 29.258749,-100.936951 29.349998,-101.025284 29.437775,-101.042999 29.461496,-101.106674 29.482082,-101.139038 29.490692,-101.218613 29.540276,-101.310837 29.615276,-101.355835 29.660553,-101.369354 29.692471,-101.405014 29.772778,-101.456680 29.772221,-101.539169 29.771111,-101.628761 29.766388,-101.706680 29.778053,-101.745010 29.788887,-101.774734 29.796665,-101.825836 29.804722,-101.892227 29.806110,-101.990845 29.805832,-102.048203 29.798470,-102.072784 29.798193,-102.097504 29.802776,-102.121948 29.810555,-102.227783 29.847221,-102.261253 29.867914,-102.301811 29.887983,-102.355560 29.850555,-102.496254 29.781666,-102.560837 29.767776,-102.670288 29.742775,-102.804764 29.474079,-102.851120 29.352219,-102.895844 29.254166,-102.955002 29.183052,-103.051956 29.094166,-103.163689 28.984026,-103.290871 28.996519,-103.296257 28.997360,-103.375000 29.023609,-103.401123 29.036388,-103.461945 29.073055,-103.485001 29.088886,-103.531403 29.126110,-103.735840 29.199165,-103.889175 29.285831,-103.975006 29.305832,-104.023621 29.321110,-104.045288 29.330830,-104.063614 29.342499,-104.080841 29.355274,-104.169724 29.422775,-104.202438 29.460970,-104.228348 29.494442,-104.252792 29.508331,-104.285141 29.525970,-104.316742 29.530899,-104.338058 29.524998,-104.419174 29.569443,-104.453339 29.595833,-104.541817 29.672915,-104.678062 29.940969,-104.695007 30.004997,-104.701324 30.058886,-104.679306 30.105415,-104.675003 30.167774,-104.682236 30.187496,-104.705566 30.233330,-104.776947 30.318054,-104.822235 30.386108,-104.865005 30.466389,-104.879730 30.524998,-104.896530 30.566248,-104.934731 30.607637,-104.990845 30.632221,-105.061951 30.694164,-105.125000 30.749722,-105.169449 30.778610,-105.222572 30.804720,-105.253059 30.797220,-105.393066 30.865833,-105.490707 30.946386,-105.541397 30.996387,-105.580704 31.057915,-105.600006 31.081526,-105.710007 31.144165,-105.771667 31.178263,-105.786957 31.208193,-105.827515 31.254444,-105.841949 31.269165,-105.858063 31.282497,-105.972778 31.369720,-106.011673 31.395277,-106.062927 31.402498,-106.143616 31.431942,-106.209869 31.472221,-106.272232 31.559303,-106.289169 31.597500,-106.303345 31.637497,-106.334312 31.687359,-106.395844 31.747498,-106.416534 31.754026,-106.439178 31.751663,-106.460007 31.750275,-106.496399 31.757080,-106.522881 31.780754,-106.539566 31.782051,-106.608337 31.783607,-107.075287 31.783333,-107.141678 31.783886,-107.174728 31.783333,-107.241959 31.783886,-107.274727 31.783333,-107.341133 31.783886,-107.375000 31.783333,-107.441391 31.783886,-107.507782 31.783333,-107.575012 31.783886,-107.608063 31.783333,-107.708069 31.783886,-107.908340 31.783054,-108.175003 31.783886,-108.208618 31.783333,-108.207779 31.699444,-108.208618 31.599442,-108.207779 31.532776,-108.208618 31.433331,-108.207779 31.366386,-108.208344 31.333054,-108.778633 31.332775,-108.816650 31.333174,-108.831940 31.332632,-108.832764 31.332603,-109.047363 31.332603,-109.058929 31.332872,-109.512222 31.333332,-109.879181 31.332775,-110.245560 31.332775,-110.311951 31.332775,-111.045837 31.333054,-111.417511 31.454166,-111.946381 31.623608,-112.299438 31.735550,-112.500000 31.798370,-112.867279 31.913410,-113.052887 31.971069,-113.344513 32.061081,-113.692009 32.167576,-113.858284 32.218300,-114.061317 32.279732,-114.343903 32.364948,-114.585533 32.437092,-114.795227 32.500496,-114.809830 32.506989,-114.791672 32.557777,-114.731392 32.685276,-114.721390 32.711105,-114.719093 32.718456,-114.729797 32.717712,-114.871346 32.707851,-115.025894 32.696987,-115.202499 32.684441,-115.404167 32.669716,-115.605560 32.654716,-115.907784 32.631943,-116.242638 32.605770,-116.508148 32.584999,-116.713058 32.568604,-116.914169 32.552216,-117.095291 32.536659,-117.122375 32.535332,-117.133331 32.565826,-117.182709 32.659294,-117.212914 32.683029,-117.212379 32.697056,-117.200508 32.697594,-117.174080 32.674938,-117.147224 32.618603,-117.115623 32.621311,-117.116653 32.642494,-117.141388 32.680614,-117.202156 32.727695,-117.228813 32.715614,-117.240547 32.684643,-117.242043 32.662533,-117.254990 32.657139,-117.268478 32.688423,-117.266113 32.708603,-117.258766 32.770416,-117.280342 32.829216,-117.252922 32.860825,-117.249062 32.871292,-117.250000 32.889717,-117.269859 32.977074,-117.319733 33.105270,-117.329453 33.124435,-117.340286 33.141663,-117.409439 33.244156,-117.480827 33.327492,-117.495003 33.342216,-117.631943 33.442764,-117.672501 33.470543,-117.774437 33.539436,-117.863892 33.595684,-117.884018 33.600552,-117.910828 33.606659,-117.936111 33.620544,-117.955002 33.632767,-117.973618 33.645546,-117.994995 33.662491,-118.027084 33.694019,-118.045273 33.709435,-118.083069 33.739716,-118.108185 33.756939,-118.134743 33.766663,-118.222221 33.784164,-118.267128 33.757774,-118.272087 33.723320,-118.297775 33.716103,-118.318069 33.720825,-118.400017 33.749855,-118.417465 33.781799,-118.398621 33.808044,-118.386185 33.840965,-118.421104 33.921246,-118.432503 33.939156,-118.454453 33.967766,-118.471123 33.987770,-118.508904 34.031105,-118.530006 34.047913,-118.554443 34.055687,-118.654999 34.049438,-118.697769 34.046104,-118.752502 34.039719,-118.781113 34.033188,-118.836403 34.030548,-118.936111 34.055550,-118.961403 34.062210,-118.981110 34.067497,-119.129173 34.113884,-119.174301 34.136108,-119.219650 34.164921,-119.255844 34.223461,-119.312469 34.283516,-119.416107 34.357498,-119.446663 34.373322,-119.541672 34.414154,-119.577217 34.420547,-119.599731 34.423607,-119.624710 34.424713,-119.798607 34.426384,-120.003746 34.467907,-120.130829 34.478737,-120.245003 34.473602,-120.355003 34.465828,-120.424156 34.456100,-120.449028 34.455688,-120.481941 34.509575,-120.495346 34.530476,-120.558327 34.561935,-120.583191 34.562214,-120.605827 34.558601,-120.625961 34.584438,-120.628326 34.623604,-120.623894 34.641106,-120.603325 34.669437,-120.594170 34.690269,-120.591377 34.710823,-120.598061 34.860828,-120.624710 34.894997,-120.613747 35.018604,-120.600067 35.100060,-120.618195 35.139439,-120.680557 35.171104,-120.718681 35.180546,-120.738533 35.164642,-120.831390 35.209991,-120.856796 35.228809,-120.869728 35.257221,-120.868195 35.279995,-120.859161 35.307495,-120.841110 35.355270,-120.919998 35.448875,-120.977081 35.465961,-120.999451 35.479156,-121.047775 35.524990,-121.166656 35.649162,-121.268753 35.700130,-121.296387 35.766106,-121.321541 35.794025,-121.368057 35.829163,-121.434990 35.894299,-121.441803 35.928047,-121.460968 35.979435,-121.472084 35.997772,-121.665421 36.183044,-121.758064 36.229435,-121.796104 36.241104,-121.867630 36.315338,-121.864166 36.342907,-121.873466 36.393887,-121.884743 36.433876,-121.897644 36.467354,-121.921661 36.518051,-121.943253 36.594574,-121.899796 36.641243,-121.865616 36.619854,-121.845001 36.615131,-121.825562 36.627075,-121.809151 36.648464,-121.799309 36.667908,-121.774719 36.759163,-121.763901 36.812492,-121.799164 36.884018,-121.851112 36.950687,-121.879166 36.972488,-121.913597 36.980335,-121.978333 36.969154,-122.020287 36.954853,-122.041519 36.954159,-122.070976 36.962353,-122.147232 36.995827,-122.179581 37.017632,-122.379021 37.199989,-122.388344 37.220268,-122.393684 37.251865,-122.384453 37.289719,-122.373192 37.329159,-122.378044 37.374435,-122.425972 37.484295,-122.443329 37.504368,-122.480614 37.512218,-122.490280 37.529991,-122.495827 37.566101,-122.499443 37.589989,-122.490547 37.752220,-122.484306 37.789925,-122.448120 37.810059,-122.379639 37.813812,-122.359993 37.786938,-122.351387 37.731659,-122.356934 37.687630,-122.367355 37.654434,-122.357773 37.615826,-122.064301 37.459297,-122.023186 37.457909,-122.005836 37.471375,-122.029716 37.479431,-122.080833 37.510273,-122.125969 37.602772,-122.130829 37.632214,-122.138481 37.662216,-122.157227 37.694710,-122.174713 37.714714,-122.242767 37.766663,-122.299988 37.826385,-122.393410 37.959160,-122.352783 37.990829,-122.225273 38.064159,-122.163322 38.047436,-122.127731 38.035263,-122.015839 38.066101,-121.989441 38.065544,-121.915558 38.054161,-121.857224 38.043053,-121.833755 38.036663,-121.684853 38.018116,-121.654198 38.048618,-121.643494 38.078991,-121.591110 38.104649,-121.498047 38.048882,-121.427216 38.012909,-121.470551 38.054993,-121.553192 38.110413,-121.585007 38.115688,-121.662216 38.096588,-121.685219 38.066467,-121.722916 38.047466,-121.818680 38.081154,-121.905273 38.066101,-121.977783 38.097214,-122.018623 38.148113,-122.050003 38.108780,-122.109734 38.061378,-122.264183 38.109993,-122.292084 38.126934,-122.311394 38.136108,-122.365280 38.155548,-122.390839 38.147491,-122.478325 38.119572,-122.479866 37.936657,-122.443329 37.906937,-122.420135 37.883186,-122.456673 37.833466,-122.505486 37.831039,-122.656662 37.910545,-122.782288 38.001316,-122.816963 38.020271,-122.896667 38.054436,-122.928329 38.053604,-122.956390 38.058044,-122.926941 38.162491,-122.839996 38.107773,-122.803047 38.081940,-122.807770 38.094990,-122.830566 38.127487,-122.958618 38.285271,-123.107224 38.462772,-123.129028 38.472908,-123.171661 38.491936,-123.237213 38.522766,-123.266663 38.540833,-123.313065 38.573883,-123.353058 38.624435,-123.447502 38.734020,-123.536118 38.796104,-123.620003 38.860825,-123.701523 38.930412,-123.707260 38.971100,-123.674583 39.004581,-123.666939 39.025547,-123.686104 39.121937,-123.712646 39.178047,-123.754181 39.259438,-123.795700 39.353325,-123.795692 39.385826,-123.774170 39.496521,-123.763062 39.519157,-123.736870 39.554993,-123.772362 39.709713,-123.820282 39.791664,-123.867493 39.869156,-123.931107 39.949715,-124.062355 40.091660,-124.092773 40.116310,-124.152573 40.147907,-124.202217 40.174164,-124.297234 40.238045,-124.331184 40.272457,-124.324036 40.311935,-124.323341 40.336243,-124.354309 40.415268,-124.375824 40.447697,-124.352356 40.532215,-124.331947 40.581665,-124.275009 40.694714,-124.252914 40.724365,-124.229446 40.746384,-124.199432 40.745544,-124.143066 40.811935,-124.098892 40.991936,-124.099304 41.038536,-124.112503 41.057495,-124.122223 41.157494,-124.090973 41.249855,-124.061394 41.344154,-124.045837 41.394440,-124.039993 41.427773,-124.046799 41.463184,-124.063606 41.515274,-124.118607 41.683052,-124.181381 41.754166,-124.215561 41.819992,-124.197357 41.848049,-124.190277 41.869438,-124.175278 41.949715,-124.184158 41.994156,-124.185852 41.999466,-124.203613 42.018883,-124.252785 42.055824,-124.289719 42.073051,-124.327507 42.105965,-124.339447 42.124992,-124.355560 42.168053,-124.381104 42.243050,-124.396957 42.316101,-124.408623 42.374710,-124.419853 42.483879,-124.401115 42.517006,-124.384720 42.554226,-124.382217 42.628876,-124.392639 42.666103,-124.412216 42.682632,-124.433052 42.694851,-124.481377 42.748047,-124.521942 42.828606,-124.524437 42.866104,-124.514862 42.905685,-124.503891 42.924992,-124.488327 42.941658,-124.473053 42.964714,-124.426659 43.040688,-124.387512 43.188881,-124.370003 43.264442,-124.373322 43.289162,-124.378532 43.319019,-124.334160 43.355103,-124.248062 43.395832,-124.206665 43.392353,-124.188469 43.378185,-124.142784 43.371693,-124.196953 43.456100,-124.238068 43.438488,-124.263725 43.415657,-124.285095 43.403175,-124.302490 43.400543,-124.294724 43.409431,-124.277496 43.439430,-124.222229 43.562767,-124.212219 43.596657,-124.203743 43.636379,-124.187233 43.674431,-124.115829 43.725266,-124.134453 43.754715,-124.153877 43.793884,-124.131378 43.920830,-124.110283 44.151657,-124.068062 44.522633,-124.057907 44.597351,-124.047768 44.625408,-124.040970 44.739159,-124.049988 44.769440,-124.059433 44.789993,-124.054855 44.836933,-124.022507 44.886940,-124.003067 44.949158,-123.995003 44.977768,-123.944786 45.179852,-123.955978 45.215546,-123.944717 45.461105,-123.944099 45.520588,-123.871613 45.528980,-123.892418 45.572601,-123.931107 45.591934,-123.900284 45.674713,-123.904716 45.709160,-123.929718 45.731934,-123.951683 45.765831,-123.949997 45.806099,-123.936943 45.894714,-123.916595 45.997562,-123.909157 46.030411,-123.911530 46.065689,-123.916946 46.095543,-123.927353 46.133324,-123.951950 46.181107,-123.926941 46.214439,-123.828888 46.190269,-123.702209 46.188046,-123.595978 46.202492,-123.554031 46.224854,-123.535561 46.239853,-123.506256 46.250134,-123.474373 46.246452,-123.429787 46.208672,-123.416519 46.186520,-123.398621 46.174995,-123.367355 46.162907,-123.263474 46.144855,-123.241806 46.145824,-123.203888 46.160820,-123.163574 46.195190,-123.258331 46.171520,-123.295273 46.177353,-123.371376 46.222767,-123.393066 46.241661,-123.409233 46.272701,-123.430412 46.286938,-123.461395 46.289440,-123.487503 46.287216,-123.518341 46.281380,-123.548195 46.274853,-123.589592 46.272629,-123.620132 46.276382,-123.655701 46.292217,-123.693604 46.300545,-123.737213 46.293884,-123.822243 46.272766,-123.857979 46.260548,-123.892494 46.265690,-124.000000 46.323608,-124.038330 46.409714,-124.049988 46.625130,-124.038750 46.656654,-124.018341 46.656239,-124.005211 46.574368,-124.013634 46.542221,-124.013550 46.498810,-123.983467 46.393814,-123.941246 46.392979,-123.899437 46.443047,-123.879173 46.532494,-123.882004 46.564159,-123.906525 46.605831,-123.921799 46.619301,-123.940826 46.636658,-123.895233 46.687363,-123.830833 46.714230,-123.810280 46.697491,-123.789719 46.677773,-123.759460 46.685623,-123.846664 46.746658,-123.876526 46.754856,-123.902924 46.740200,-123.959312 46.723042,-124.053604 46.735546,-124.078117 46.749229,-124.097504 46.861382,-124.082230 46.886108,-123.971939 46.932770,-123.938889 46.937492,-123.871933 46.953323,-123.801247 46.976791,-123.909157 46.990829,-123.961945 46.988602,-123.989235 47.000896,-124.000420 47.023880,-124.021950 47.047215,-124.050819 47.062073,-124.074997 47.066246,-124.111595 47.059505,-124.133888 47.042076,-124.122498 47.001389,-124.110619 46.975613,-124.152565 46.941658,-124.164169 46.946381,-124.157501 46.976654,-124.152222 47.007774,-124.148903 47.033051,-124.148621 47.060822,-124.153061 47.091103,-124.183319 47.221375,-124.208893 47.279434,-124.227905 47.313950,-124.267227 47.341934,-124.300690 47.373116,-124.307220 47.433052,-124.327217 47.535828,-124.359291 47.667217,-124.394997 47.729431,-124.463196 47.824303,-124.498894 47.852219,-124.525566 47.871243,-124.548744 47.883049,-124.579025 47.885132,-124.618187 47.924995,-124.644730 47.973320,-124.655685 47.996937,-124.668190 48.039856,-124.672501 48.064156,-124.681381 48.126381,-124.687210 48.184433,-124.681953 48.252220,-124.705696 48.371239,-124.714310 48.397076,-124.637222 48.399994,-124.566101 48.379715,-124.546661 48.372215,-124.478882 48.342216,-124.415833 48.316383,-124.309433 48.283882,-124.232224 48.275826,-124.144997 48.251389,-124.099297 48.232071,-124.085213 48.211727,-124.040283 48.193047,-124.016953 48.188881,-123.934723 48.175827,-123.897232 48.171936,-123.806953 48.165825,-123.786667 48.165543,-123.758347 48.166664,-123.673889 48.170830,-123.508904 48.148331,-123.401390 48.131939,-123.354172 48.128601,-123.242706 48.129433,-123.209175 48.142353,-123.187767 48.159157,-123.146667 48.179436,-123.113266 48.190960,-122.970001 48.113327,-122.868042 48.112286,-122.846527 48.135963,-122.825279 48.145969,-122.781677 48.158043,-122.749435 48.153950,-122.747002 48.127838,-122.777496 48.110481,-122.778061 48.090271,-122.713898 48.010277,-122.678680 47.987286,-122.630280 47.915825,-122.671661 47.856941,-122.747772 47.763054,-122.788063 47.765549,-122.779869 47.812214,-122.784729 47.832497,-122.794998 47.860275,-122.849297 47.831379,-122.849442 47.806099,-122.841949 47.783051,-122.851097 47.751389,-122.875412 47.703743,-122.893890 47.677490,-122.914719 47.658600,-122.966400 47.618599,-122.983887 47.603050,-123.017227 47.569717,-123.104446 47.469437,-123.147926 47.371655,-123.129723 47.359440,-123.103882 47.356384,-123.006668 47.368465,-122.904716 47.403877,-122.876106 47.414993,-122.840630 47.447315,-122.866096 47.445267,-122.918060 47.426102,-122.954727 47.409988,-122.995979 47.390270,-123.024994 47.379990,-123.097496 47.400826,-123.084167 47.443047,-122.999733 47.545273,-122.942490 47.607910,-122.903336 47.634300,-122.836121 47.656654,-122.736099 47.721661,-122.728752 47.747772,-122.565552 47.938042,-122.514099 47.922073,-122.460037 47.763741,-122.541672 47.742218,-122.598465 47.706657,-122.593391 47.640385,-122.598091 47.608437,-122.638474 47.619576,-122.655418 47.638466,-122.671104 47.658600,-122.680832 47.639229,-122.663330 47.545689,-122.602783 47.561661,-122.575096 47.578629,-122.536522 47.593182,-122.508621 47.500549,-122.547768 47.288048,-122.571114 47.278740,-122.672905 47.321762,-122.644852 47.348881,-122.613678 47.394436,-122.619164 47.420547,-122.709579 47.355549,-122.743050 47.290760,-122.714134 47.252632,-122.728607 47.211937,-122.748962 47.189297,-122.771118 47.201660,-122.790421 47.222626,-122.811241 47.270546,-122.795441 47.292240,-122.767570 47.320480,-122.770210 47.372074,-122.797501 47.395271,-122.812500 47.367767,-122.846497 47.313160,-122.902916 47.299999,-122.917007 47.284496,-122.926872 47.250668,-122.939575 47.205688,-122.980064 47.180477,-123.025284 47.169716,-123.062569 47.155960,-123.064857 47.113884,-123.025558 47.124161,-122.951401 47.134995,-122.900978 47.066383,-122.878601 47.064156,-122.885414 47.156448,-122.845139 47.174992,-122.792778 47.182491,-122.716949 47.120270,-122.639717 47.151932,-122.610001 47.172768,-122.591377 47.193878,-122.565277 47.224434,-122.527092 47.275826,-122.459167 47.297775,-122.416397 47.314713,-122.313538 47.371796,-122.309578 47.404572,-122.351387 47.485268,-122.385147 47.546661,-122.398621 47.586380,-122.418327 47.672218,-122.373604 47.832355,-122.291100 47.958187,-122.320557 48.074165,-122.374405 48.213428,-122.442627 48.225540,-122.470001 48.169922,-122.446800 48.133602,-122.429993 48.119713,-122.451401 48.114998,-122.500420 48.129086,-122.528465 48.182907,-122.531113 48.205132,-122.520691 48.236031,-122.498337 48.250416,-122.455696 48.254997,-122.434021 48.255135,-122.415703 48.247078,-122.397499 48.238186,-122.378189 48.284718,-122.392845 48.309437,-122.590950 48.425793,-122.607079 48.411240,-122.625832 48.403183,-122.658333 48.404713,-122.679581 48.418324,-122.698738 48.494785,-122.619720 48.511246,-122.550415 48.484852,-122.536110 48.467354,-122.517090 48.453049,-122.486244 48.452702,-122.436661 48.590408,-122.500000 48.744854,-122.521950 48.761524,-122.565834 48.775131,-122.587639 48.772076,-122.609032 48.752773,-122.649437 48.764442,-122.681107 48.795547,-122.809715 48.942905,-122.770348 48.964024,-122.734123 48.962353,-122.753616 48.993881,-122.760300 48.999435,-122.699997 49.000000,-122.566673 49.000000,-122.433609 49.000000,-122.333893 49.000000,-122.100563 49.000000,-121.084976 48.999718,-120.534729 48.999435,-120.034157 48.999435,-119.934158 48.999435,-119.867493 48.999435,-119.467773 48.999435,-119.267227 48.999435,-119.134171 48.999435,-118.967499 48.999435,-118.767776 48.999435,-118.368057 48.999435,-118.134171 48.999435,-118.000839 48.999435,-117.867493 48.999435,-117.834442 49.000000,-117.567497 49.000000,-117.300552 49.000000,-117.234734 49.000000,-117.200844 48.999435,-117.067230 48.999718,-117.036621 49.003128,-117.001404 48.999718,-116.048340 48.999718,-115.734444 48.999435,-115.601387 48.999435,-115.567230 49.000000,-115.468063 49.000000,-115.368057 49.000000,-115.167503 48.999435,-115.034157 48.999435,-114.901108 48.999435,-114.633904 49.000000,-114.534729 49.000000,-114.467499 48.999435,-114.335007 48.999435,-114.059860 49.000603,-114.034439 48.999435,-113.567497 48.999435,-113.368332 48.999435,-113.234161 48.999435,-113.034439 49.000000,-112.934723 49.000000,-112.601669 49.000000,-112.535004 49.000000,-112.434998 49.000000,-112.335007 49.000000,-112.234734 49.000000,-112.168327 48.999435,-112.034729 48.999435,-111.801102 48.999435,-111.368332 48.999435,-110.768623 48.999435,-110.667770 49.000000,-110.501106 49.000000,-110.367767 49.000000,-110.301666 49.000000,-110.201111 48.999435,-110.101387 48.999435,-109.999657 49.000603,-109.967773 48.999718,-109.801941 48.999435,-109.634743 48.999435,-109.334732 48.999435,-108.834732 48.999435,-108.667770 48.999435,-108.534729 48.999435,-108.335007 48.999435,-108.168877 48.999435,-107.801102 48.999435,-107.735550 48.999435,-107.634743 48.999435,-107.434998 49.000000,-107.335281 49.000000,-106.735550 48.999435,-106.468063 48.999435,-106.268623 48.999435,-106.135277 48.999435,-106.034729 48.999435,-105.935547 48.999435,-105.702217 48.999435,-105.268341 49.000000,-105.001404 48.999435,-104.835007 48.999435,-104.335007 48.999435,-104.135277 48.999718,-104.033096 49.000252,-103.735283 48.999435,-103.535278 48.999435,-103.435547 49.000275,-103.268890 49.000000,-103.168327 48.999435,-103.035278 48.999435,-102.768341 48.999435,-102.535553 49.000275,-102.335564 48.999435,-102.168877 49.000000,-101.468887 48.999435,-101.367233 48.998787,-101.302223 49.000275,-101.069168 49.000000,-100.501953 48.999718,-100.002228 49.000000,-99.835556 49.000000,-99.335556 48.999435,-98.868607 49.000000,-98.502228 48.999435,-98.269165 49.000275,-97.969162 49.000275,-97.801941 49.000000,-97.635834 48.999435,-97.502792 48.999435,-97.219940 48.999718,-95.266556 48.999977,-95.154175 48.999435,-95.153961 49.173332,-95.154449 49.333328,-95.154175 49.366386,-95.152786 49.376656,-95.142502 49.371658,-95.120834 49.364998,-95.081863 49.359592,-95.025833 49.357498,-94.998611 49.357498,-94.962090 49.360970,-94.931961 49.358540,-94.817780 49.305546,-94.805687 49.186661,-94.798332 49.157490,-94.766953 49.075554,-94.745270 49.028603,-94.729996 48.996941,-94.718605 48.974709,-94.705841 48.933186,-94.700981 48.902493,-94.707039 48.857998,-94.708054 48.796799,-94.694992 48.778740,-94.640419 48.741104,-94.605835 48.724434,-94.523895 48.701935,-94.500839 48.696938,-94.461044 48.694988,-94.433319 48.701935,-94.400352 48.710827,-94.298470 48.707214,-94.267365 48.695892,-94.247887 48.660995,-94.134171 48.642769,-94.111938 48.641106,-94.063889 48.638046,-93.882919 48.630272,-93.858749 48.628605,-93.833954 48.616383,-93.818893 48.586243,-93.804787 48.531864,-93.785835 48.517078,-93.724167 48.513885,-93.660698 48.515137,-93.496254 48.538609,-93.464241 48.551727,-93.454063 48.584332,-93.408340 48.608604,-93.315697 48.629158,-93.244995 48.640549,-92.951317 48.622627,-92.715286 48.541382,-92.697769 48.485268,-92.582230 48.441376,-92.455276 48.394157,-92.426392 48.311661,-92.359856 48.231728,-92.331680 48.234161,-92.291405 48.248863,-92.286110 48.269993,-92.299789 48.299366,-92.276810 48.334991,-92.257233 48.346939,-92.162216 48.356659,-92.141678 48.357216,-92.039375 48.345341,-92.014168 48.304436,-92.008064 48.280964,-91.991798 48.261246,-91.963715 48.240536,-91.940277 48.230545,-91.850555 48.203880,-91.783890 48.194710,-91.740135 48.191376,-91.687500 48.144714,-91.645142 48.098343,-91.573624 48.093048,-91.462784 48.057770,-91.418335 48.041107,-91.386803 48.058880,-91.347229 48.068054,-91.318611 48.069439,-91.276390 48.072632,-91.240555 48.083603,-91.192490 48.114998,-91.149170 48.144157,-91.126099 48.154991,-90.969162 48.214714,-90.928329 48.228600,-90.898056 48.236656,-90.868607 48.237495,-90.835213 48.227074,-90.835800 48.204460,-90.773895 48.103748,-90.749863 48.092770,-90.279999 48.113052,-90.146523 48.121449,-90.065552 48.106453,-90.032776 48.069717,-89.994240 48.025269,-89.899788 47.990616,-89.862503 48.000832,-89.838898 48.011665,-89.755562 48.029575,-89.606384 48.011868,-89.572914 48.002251,-89.493126 48.003166,-89.447769 48.003326,-89.356659 47.979713,-89.323334 47.993050,-88.974167 48.139160,-88.691666 48.255554,-88.645554 48.264160,-88.368057 48.312210,-88.188324 48.244156,-87.444717 47.955826,-87.341675 47.915543,-87.201401 47.860275,-86.884445 47.734718,-86.568893 47.608330,-86.466660 47.567215,-86.051392 47.398880,-86.014725 47.383881,-85.839722 47.312210,-85.738892 47.270828,-85.464172 47.157211,-85.354446 47.111664,-84.917496 46.928604,-84.864586 46.905823,-84.832779 46.829163,-84.825562 46.806938,-84.806946 46.748329,-84.787781 46.689713,-84.775009 46.653046,-84.565002 46.466385,-84.521255 46.460270,-84.483955 46.460201,-84.458061 46.483742,-84.431381 46.501663,-84.408615 46.508606,-84.192764 46.546661,-84.125343 46.529438,-84.120064 46.507076,-84.144585 46.465687,-84.154449 46.445267,-84.160278 46.424995,-84.157646 46.394161,-84.102501 46.240269,-84.089722 46.220268,-84.076675 46.203049,-83.954323 46.070480,-83.923752 46.070560,-83.890549 46.094616,-83.838341 46.125546,-83.663055 46.126099,-83.619164 46.121101,-83.596115 46.114159,-83.572083 46.101936,-83.479019 46.040134,-83.447769 46.011940,-83.487778 45.961662,-83.523895 45.918053,-83.597778 45.827217,-83.500290 45.784996,-83.270844 45.683327,-83.112213 45.612770,-83.050827 45.585266,-82.954178 45.541939,-82.665009 45.411934,-82.629990 45.396103,-82.543060 45.355827,-82.430557 44.882767,-82.331680 44.460823,-82.214447 43.952217,-82.130280 43.585266,-82.146118 43.553047,-82.228882 43.391380,-82.252792 43.346382,-82.322235 43.210548,-82.404175 43.049164,-82.418777 43.018639,-82.463478 42.901379,-82.481529 42.826382,-82.474091 42.796383,-82.472916 42.760826,-82.484726 42.719154,-82.517365 42.627632,-82.535828 42.599434,-82.579033 42.563744,-82.618195 42.555756,-82.662651 42.545296,-82.704453 42.508331,-82.729996 42.483330,-82.769173 42.442905,-82.801247 42.418045,-82.841385 42.396942,-82.940552 42.357498,-82.975830 42.344711,-83.002228 42.339157,-83.027222 42.331940,-83.055664 42.319576,-83.084541 42.299358,-83.112915 42.265270,-83.123322 42.245827,-83.132492 42.220825,-83.137222 42.201385,-83.168610 42.046104,-83.150284 42.008331,-83.130829 41.970543,-83.117416 41.946194,-83.076393 41.867355,-82.696655 41.683876,-82.649994 41.681938,-82.462784 41.676102,-82.425278 41.675552,-82.238892 41.763885,-82.218063 41.774437,-81.822235 41.960274,-81.623611 42.052773,-81.424438 42.144997,-81.249161 42.224991,-80.869156 42.279160,-80.528549 42.326618,-80.510284 42.329163,-80.091537 42.398190,-79.776672 42.520271,-79.763428 42.524704,-79.566452 42.600708,-79.299438 42.702492,-79.154449 42.757217,-79.121109 42.769157,-78.986938 42.819992,-78.965836 42.833603,-78.934158 42.865963,-78.917778 42.901936,-78.920341 42.936241,-78.945198 42.954021,-78.975273 42.959713,-79.013756 42.982212,-79.042084 43.009720,-79.081116 43.085548,-79.054649 43.140545,-79.044861 43.163044,-79.053749 43.259579,-79.066788 43.279400,-79.132217 43.382492,-79.184723 43.465546,-79.095276 43.497772,-79.028061 43.521935,-78.938324 43.553879,-78.724716 43.629433,-78.663055 43.637497,-78.388062 43.638329,-77.887222 43.639435,-77.857773 43.639435,-77.729996 43.639160,-77.582779 43.638603,-77.288330 43.636658,-76.974167 43.634438,-76.809448 43.633327,-76.697495 43.768600,-76.583618 43.915825,-76.569458 43.934158,-76.531387 43.983047,-76.437355 44.102074,-76.410278 44.121101,-76.363373 44.150993,-76.061104 44.343185,-76.040840 44.351383,-76.019455 44.353325,-75.989975 44.357067,-75.966110 44.364159,-75.904449 44.384995,-75.872078 44.398048,-75.845276 44.418880,-75.831253 44.440544,-75.822639 44.472488,-75.806664 44.487076,-75.736115 44.546387,-75.682495 44.588043,-75.623055 44.631382,-75.562500 44.673882,-75.537216 44.691376,-75.395844 44.785828,-75.309723 44.841934,-75.278061 44.857216,-75.170547 44.898605,-74.996117 44.983601,-74.850281 45.016663,-74.820549 45.018463,-74.777779 45.008884,-74.751114 45.002220,-74.682022 45.006714,-74.249161 44.992218,-73.911644 45.000000,-73.622772 45.006660,-73.367966 45.010586,-73.352997 45.009422,-73.341644 45.011623,-72.956390 45.018326,-72.778885 45.020828,-72.510284 45.017212,-72.459167 45.017494,-72.271652 45.018776,-72.049988 45.019440,-71.892776 45.019157,-71.554718 45.019989,-71.494156 45.020546,-71.498055 45.049438,-71.488747 45.077976,-71.459167 45.102776,-71.434303 45.127769,-71.401390 45.214397,-71.424438 45.250000,-71.321106 45.296940,-71.295692 45.303741,-71.272507 45.296383,-71.236389 45.276520,-71.211670 45.266106,-71.179718 45.255829,-71.143196 45.252773,-71.085129 45.307709,-71.021118 45.326660,-70.876595 45.241032,-70.697083 45.463600,-70.712784 45.477768,-70.724998 45.497215,-70.720276 45.528328,-70.693054 45.571938,-70.631943 45.627769,-70.576950 45.660820,-70.555267 45.672768,-70.466660 45.711937,-70.393890 45.778046,-70.258057 45.909088,-70.244926 45.960407,-70.269447 45.973320,-70.304855 45.979988,-70.305557 46.078880,-70.287781 46.203049,-70.242493 46.279160,-70.200287 46.336380,-70.119156 46.393608,-70.078407 46.417561,-70.057083 46.431381,-70.047775 46.453880,-70.044159 46.474991,-70.038605 46.509995,-70.026947 46.587494,-70.009171 46.698044,-69.992767 46.715828,-69.847229 46.862213,-69.712509 46.996941,-69.653885 47.055267,-69.423615 47.283333,-69.305267 47.400269,-69.236061 47.467892,-69.128326 47.459160,-69.045624 47.431030,-69.044579 47.403118,-69.052490 47.380547,-69.055832 47.342072,-69.055130 47.302074,-69.053589 47.293777,-69.051109 47.281937,-69.032227 47.255550,-68.961952 47.218876,-68.891533 47.189014,-68.831680 47.208885,-68.787506 47.224709,-68.761948 47.232765,-68.564713 47.289719,-68.370407 47.349159,-68.343056 47.361801,-68.314857 47.365135,-68.244995 47.351936,-68.208618 47.341660,-68.185822 47.332771,-67.960976 47.190475,-67.950005 47.168606,-67.892227 47.114441,-67.866943 47.100548,-67.794998 47.069992,-67.791672 46.921379,-67.788895 46.787773,-67.779175 46.283333,-67.772507 45.957497,-67.786667 45.888329,-67.806381 45.784721,-67.804443 45.731377,-67.794510 45.695824,-67.660553 45.632076,-67.573898 45.611664,-67.507507 45.601383,-67.477783 45.608330,-67.458054 45.613605,-67.413124 45.585476,-67.421242 45.524990,-67.481834 45.495827,-67.450562 45.333054,-67.464310 45.283882,-67.455276 45.263054,-67.422501 45.214996,-67.405968 45.196381,-67.338684 45.150269,-67.305832 45.154919,-67.290070 45.180126,-67.264244 45.199989,-67.236115 45.193878,-67.206543 45.183037,-67.162773 45.168327,-67.104996 45.098328,-67.034439 44.984993,-67.075050 44.952133,-67.126755 44.931419,-67.192047 44.925720,-67.178612 44.899158,-67.121887 44.878433,-67.091591 44.869308,-67.074890 44.886940,-67.057884 44.900932,-66.983055 44.866379,-66.970833 44.827911,-66.996948 44.803604,-67.189995 44.660267,-67.263756 44.643051,-67.415833 44.628326,-67.503479 44.649837,-67.546036 44.666866,-67.564995 44.634300,-67.561386 44.596939,-67.562912 44.552490,-67.711113 44.512497,-67.735832 44.520130,-67.775284 44.546944,-67.865005 44.493881,-67.936386 44.426941,-67.973618 44.405823,-68.009171 44.393326,-68.059471 44.351799,-68.094788 44.404713,-68.107918 44.454994,-68.270004 44.466385,-68.321152 44.465881,-68.364250 44.447121,-68.378876 44.422218,-68.463196 44.399368,-68.504181 44.422493,-68.559158 44.418884,-68.549164 44.321175,-68.615829 44.306381,-68.813194 44.330273,-68.793884 44.458046,-68.751114 44.517494,-68.731590 44.555893,-68.796867 44.574612,-68.810944 44.522266,-68.849731 44.473045,-68.902222 44.462212,-68.980835 44.441723,-69.022507 44.256943,-69.083611 44.128880,-69.081673 44.099506,-69.050201 44.100964,-69.065559 44.066105,-69.199158 43.980270,-69.248337 43.938042,-69.298050 43.997215,-69.369995 44.046944,-69.458893 43.925270,-69.486938 43.869438,-69.500420 43.850407,-69.540718 43.874577,-69.553558 43.897827,-69.551048 43.937325,-69.556450 43.975613,-69.528610 44.024261,-69.588913 43.958267,-69.591415 43.919643,-69.587021 43.884476,-69.651199 43.900833,-69.642365 44.003468,-69.626663 44.019436,-69.617325 44.038849,-69.643059 44.028881,-69.664444 44.008606,-69.679054 43.967102,-69.717262 43.905518,-69.692719 43.882439,-69.699997 43.841103,-69.719299 43.792080,-69.752014 43.830162,-69.781921 43.963017,-69.779381 44.047562,-69.771599 44.074299,-69.873466 43.992355,-69.868042 43.968739,-69.830406 43.927685,-69.818550 43.902771,-69.812721 43.866268,-69.800644 43.788769,-69.831390 43.716171,-69.851669 43.759438,-69.856949 43.800827,-69.922226 43.864716,-69.991600 43.875340,-70.091949 43.827774,-70.129990 43.806381,-70.172501 43.780548,-70.208344 43.724991,-70.231110 43.674023,-70.252792 43.652214,-70.216248 43.658043,-70.196594 43.642906,-70.191872 43.575546,-70.290703 43.556660,-70.345840 43.461105,-70.353882 43.442764,-70.393616 43.403046,-70.451523 43.357773,-70.482079 43.356659,-70.514030 43.354229,-70.549164 43.323608,-70.569588 43.297630,-70.583748 43.257076,-70.571671 43.226517,-70.601669 43.177773,-70.671181 43.084503,-70.693954 43.100132,-70.723404 43.119919,-70.737595 43.078026,-70.704514 43.057701,-70.719444 43.023048,-70.759171 42.975822,-70.790276 42.938877,-70.810822 42.893608,-70.812912 42.877579,-70.807632 42.743328,-70.805969 42.715897,-70.746735 42.654572,-70.662422 42.641689,-70.664589 42.663879,-70.643066 42.680550,-70.617775 42.690823,-70.581810 42.652836,-70.628883 42.595409,-70.779175 42.560822,-70.868256 42.540760,-70.888062 42.507774,-71.044861 42.367214,-71.039513 42.304852,-70.957367 42.240685,-70.867844 42.257217,-70.848892 42.274437,-70.757095 42.245411,-70.717644 42.213879,-70.651733 42.057281,-70.682220 41.997215,-70.645073 41.963882,-70.594650 41.948044,-70.573616 41.951660,-70.534027 41.934437,-70.521393 41.865410,-70.527367 41.839714,-70.526840 41.805965,-70.451942 41.755478,-70.332916 41.713882,-70.293610 41.708885,-70.204727 41.743603,-70.172226 41.753326,-70.146393 41.759579,-70.111938 41.761940,-70.085281 41.768600,-70.019310 41.792564,-69.990974 41.830410,-69.988609 41.912628,-70.106949 42.039436,-70.134438 42.058949,-70.172630 42.055824,-70.187233 42.029034,-70.244019 42.073948,-70.226112 42.090546,-70.144165 42.087494,-70.112213 42.077637,-70.074173 42.058880,-70.033333 42.022633,-70.007507 41.996941,-69.993057 41.980820,-69.977219 41.954163,-69.959587 41.920410,-69.934723 41.856659,-69.927216 41.832214,-69.928329 41.719986,-69.935410 41.672497,-69.987831 41.668438,-70.017776 41.669441,-70.047226 41.669991,-70.089172 41.668327,-70.185410 41.655544,-70.232224 41.644157,-70.358047 41.634720,-70.418465 41.633533,-70.439438 41.604164,-70.485619 41.560059,-70.648613 41.539440,-70.658890 41.602493,-70.651108 41.641663,-70.634171 41.701385,-70.726105 41.727768,-70.813889 41.629990,-70.926392 41.553879,-71.065552 41.510551,-71.128052 41.510826,-71.142372 41.494301,-71.188324 41.468323,-71.202225 41.498329,-71.207779 41.549023,-71.206253 41.640545,-71.198608 41.667496,-71.195984 41.671257,-71.156532 41.719711,-71.135559 41.748886,-71.114853 41.789509,-71.216110 41.725266,-71.236542 41.709236,-71.234718 41.677494,-71.271393 41.653046,-71.307838 41.664642,-71.389442 41.806694,-71.413895 41.604996,-71.421806 41.483879,-71.428047 41.461105,-71.474716 41.393051,-71.511673 41.369991,-71.535278 41.376797,-71.563614 41.376938,-71.589722 41.373322,-71.671661 41.353882,-71.733063 41.337769,-71.782227 41.325829,-71.808334 41.321663,-71.845795 41.318825,-71.878609 41.341030,-71.959442 41.347488,-72.183319 41.326103,-72.235420 41.305965,-72.254868 41.287079,-72.388344 41.271103,-72.531387 41.263611,-72.568069 41.274162,-72.606949 41.279160,-72.636124 41.277489,-72.818344 41.258331,-72.890350 41.254368,-72.906387 41.286110,-72.936386 41.273323,-73.041382 41.214157,-73.103607 41.177773,-73.150558 41.157768,-73.177780 41.170830,-73.276672 41.135826,-73.322784 41.118324,-73.379166 41.094711,-73.433609 41.068329,-73.471939 41.051102,-73.559433 41.015827,-73.645508 41.007523,-73.646042 40.983879,-73.677216 40.953949,-73.708481 40.954296,-73.748611 40.925274,-73.781677 40.879990,-73.822784 40.826103,-73.934158 40.798050,-73.923325 40.870544,-73.903061 40.916523,-73.891678 40.943604,-73.883621 40.973877,-73.872910 41.026661,-73.866669 41.064438,-73.866104 41.089157,-73.873329 41.158882,-73.877907 41.178745,-73.951279 41.304436,-73.986107 41.268394,-73.960075 41.204227,-73.936104 41.187630,-73.918060 41.170128,-73.913055 41.145828,-73.904343 40.989563,-73.903610 40.980820,-73.904175 40.959435,-73.928329 40.904434,-74.020981 40.717350,-74.086395 40.669159,-74.119781 40.663391,-74.107285 40.692978,-74.108604 40.713394,-74.133896 40.700825,-74.199303 40.641033,-74.252502 40.552216,-74.259171 40.522217,-74.262985 40.466377,-74.244156 40.452492,-74.199997 40.437626,-74.083893 40.438042,-73.995659 40.458847,-73.956390 40.398186,-73.952225 40.299995,-74.021118 40.029434,-74.088264 39.774853,-74.082924 39.877075,-74.066666 39.939987,-74.051949 39.965824,-74.044449 39.999718,-74.045547 40.052979,-74.071602 40.047844,-74.100830 39.950829,-74.171112 39.780548,-74.178467 39.746525,-74.156319 39.724987,-74.151321 39.703743,-74.181671 39.670547,-74.211121 39.643608,-74.319458 39.561378,-74.405563 39.516106,-74.376572 39.474663,-74.393265 39.441284,-74.422470 39.458939,-74.441086 39.443531,-74.462593 39.421066,-74.447319 39.400021,-74.428749 39.391106,-74.420410 39.353989,-74.522430 39.315964,-74.515564 39.336655,-74.554169 39.334991,-74.650108 39.290203,-74.611526 39.279575,-74.599976 39.257549,-74.651398 39.193047,-74.711121 39.089989,-74.759171 39.038048,-74.820831 38.971935,-74.846802 38.950825,-74.876389 38.938324,-74.908340 38.927357,-74.945274 38.922981,-74.964447 38.933323,-74.957367 38.985405,-74.948471 39.009300,-74.931107 39.036385,-74.907776 39.071663,-74.892365 39.104023,-74.882637 39.140896,-74.894936 39.169022,-74.923889 39.189713,-75.040833 39.213882,-75.086395 39.207497,-75.164444 39.232765,-75.311111 39.313881,-75.378326 39.353607,-75.415695 39.378044,-75.526947 39.465340,-75.542770 39.500549,-75.557220 39.620407,-75.452782 39.756802,-75.424309 39.782772,-75.400558 39.799721,-75.368332 39.818054,-75.344727 39.829437,-75.289169 39.842766,-75.196106 39.863327,-75.137566 39.873947,-75.101105 39.900543,-75.065552 39.964439,-75.028519 40.012306,-75.038887 40.010273,-75.059998 40.000549,-75.111664 39.973320,-75.126381 39.956661,-75.138481 39.935410,-75.177216 39.895546,-75.221664 39.872765,-75.309441 39.863884,-75.361107 39.849506,-75.409721 39.821941,-75.421448 39.811951,-75.459442 39.788330,-75.588608 39.648880,-75.604439 39.614021,-75.572159 39.452908,-75.527222 39.416664,-75.432632 39.310688,-75.395416 39.246243,-75.392433 39.200756,-75.405479 39.157494,-75.389030 39.077774,-75.302216 38.918884,-75.188324 38.816666,-75.139999 38.694992,-75.200836 38.597771,-75.170273 38.578606,-75.140419 38.589436,-75.063889 38.586937,-75.038467 38.479713,-75.039719 38.457497,-75.043686 38.450859,-75.040779 38.449722,-75.044579 38.417213,-75.056664 38.362770,-75.073303 38.340961,-75.061241 38.408051,-75.060478 38.446659,-75.065308 38.453415,-75.079414 38.457596,-75.082855 38.453163,-75.079453 38.445824,-75.095001 38.328812,-75.154442 38.241520,-75.183533 38.224365,-75.329453 38.109161,-75.355827 38.082634,-75.368607 38.034164,-75.370041 38.024384,-75.399734 37.988602,-75.412216 37.919441,-75.490967 37.814716,-75.503342 37.798332,-75.570007 37.681107,-75.608955 37.577354,-75.596527 37.559021,-75.660141 37.497318,-75.687637 37.523884,-75.701103 37.552422,-75.720558 37.547771,-75.803879 37.452774,-75.841675 37.372490,-75.842499 37.347488,-75.851105 37.276100,-75.868057 37.216934,-75.960831 37.152214,-76.002792 37.223877,-76.016464 37.270893,-76.008202 37.314716,-75.956390 37.497772,-75.930557 37.576103,-75.916946 37.608330,-75.874718 37.656654,-75.781387 37.724991,-75.697220 37.799164,-75.662506 37.840546,-75.646118 37.944710,-75.644043 37.961174,-75.670273 37.973602,-75.693184 37.979153,-75.754997 37.979435,-75.774445 37.974712,-75.800278 37.963326,-75.820702 37.948185,-75.851807 37.928951,-75.878532 37.947559,-75.882217 37.985966,-75.853058 38.089157,-75.912216 38.145271,-75.896118 38.250275,-75.846352 38.398777,-76.021942 38.243881,-76.037506 38.226654,-76.087784 38.286385,-76.161118 38.349434,-76.220795 38.384644,-76.222229 38.343323,-76.242493 38.366936,-76.321945 38.488602,-76.297501 38.500549,-76.246948 38.510277,-76.208344 38.523048,-76.184998 38.534439,-76.166458 38.568188,-76.187218 38.579441,-76.214172 38.573608,-76.224655 38.556309,-76.264938 38.551586,-76.284996 38.570271,-76.265289 38.619713,-76.177780 38.611664,-76.131630 38.599934,-76.103745 38.586239,-76.051941 38.574856,-76.028473 38.573746,-76.002640 38.580135,-75.975487 38.593670,-75.962784 38.613327,-75.960976 38.651588,-75.979301 38.634155,-76.002159 38.607006,-76.032776 38.603325,-76.067917 38.613674,-76.191101 38.683876,-76.204727 38.739716,-76.320900 38.682007,-76.342155 38.688255,-76.331955 38.760551,-76.300072 38.818745,-76.255173 38.841034,-76.215141 38.813187,-76.207504 38.793610,-76.186104 38.776100,-76.155968 38.763187,-76.132217 38.772491,-76.104439 38.799091,-76.141953 38.886108,-76.224655 38.964088,-76.296387 38.922493,-76.316956 38.888046,-76.356384 38.851662,-76.359863 38.855412,-76.357773 38.895271,-76.347504 38.940689,-76.338890 38.967075,-76.296837 39.025753,-76.266258 38.996662,-76.242081 38.983879,-76.220001 38.981377,-76.191940 38.984573,-76.156113 39.002632,-76.072464 39.141659,-76.141388 39.112495,-76.220840 39.060822,-76.260147 39.153671,-76.168335 39.316521,-76.095833 39.359936,-75.977783 39.389992,-75.851387 39.535828,-75.835350 39.571938,-75.940826 39.604160,-76.084793 39.548950,-76.112007 39.483463,-76.063332 39.458012,-76.090286 39.431103,-76.187912 39.371937,-76.212776 39.365551,-76.229027 39.387005,-76.225281 39.418884,-76.256958 39.444710,-76.359726 39.399994,-76.351944 39.375267,-76.427780 39.316940,-76.480003 39.302074,-76.451675 39.258606,-76.427361 39.239159,-76.407646 39.231098,-76.395004 39.229988,-76.386948 39.226379,-76.388611 39.224709,-76.416397 39.209717,-76.438560 39.212212,-76.473305 39.223083,-76.489441 39.236523,-76.511398 39.247772,-76.549438 39.261108,-76.576675 39.267212,-76.610519 39.250374,-76.582779 39.242077,-76.519447 39.204826,-76.478279 39.177155,-76.440971 39.145409,-76.421524 39.108330,-76.393890 39.011036,-76.453957 38.913254,-76.523621 38.854713,-76.537506 38.731659,-76.511391 38.557629,-76.505005 38.531105,-76.491943 38.505554,-76.478333 38.490273,-76.441940 38.457214,-76.401390 38.419853,-76.378571 38.365204,-76.406250 38.337212,-76.445763 38.339539,-76.579178 38.431938,-76.636948 38.490967,-76.665703 38.585133,-76.667358 38.608189,-76.666115 38.636799,-76.679161 38.662525,-76.663467 38.474712,-76.649445 38.453323,-76.594452 38.404991,-76.481949 38.315544,-76.448753 38.299995,-76.371109 38.288330,-76.391113 38.248116,-76.380409 38.219849,-76.347778 38.193878,-76.333618 38.178047,-76.317497 38.148323,-76.312347 38.047302,-76.338608 38.058884,-76.548615 38.186378,-76.560272 38.203323,-76.581955 38.221237,-76.606247 38.233047,-76.629990 38.239433,-76.653885 38.241936,-76.674438 38.242493,-76.702080 38.240826,-76.739304 38.233604,-76.870689 38.274574,-76.915833 38.309158,-76.970139 38.358467,-77.044449 38.438320,-77.075287 38.416519,-77.196770 38.367943,-77.243744 38.398258,-77.263199 38.487770,-77.248047 38.524162,-77.234581 38.550690,-77.180557 38.605827,-77.087502 38.685547,-77.064445 38.694992,-77.029373 38.698948,-77.006119 38.754997,-77.019455 38.796104,-77.022781 38.803093,-77.021667 38.808884,-77.016808 38.864300,-77.053398 38.901100,-77.061691 38.904572,-77.050278 38.878876,-77.037216 38.843323,-77.042221 38.726620,-77.095840 38.704712,-77.134445 38.698601,-77.248886 38.598602,-77.304443 38.495544,-77.326401 38.402489,-77.320007 38.345268,-77.246338 38.332832,-77.224167 38.333603,-77.166321 38.343185,-77.068748 38.379017,-77.023331 38.309433,-76.932495 38.203049,-76.876938 38.178329,-76.845558 38.168884,-76.689438 38.151382,-76.590973 38.122772,-76.501114 38.023605,-76.405006 37.974575,-76.349442 37.956657,-76.281532 37.930824,-76.243614 37.906101,-76.228195 37.881660,-76.285553 37.696938,-76.337509 37.626656,-76.353607 37.618599,-76.369713 37.633606,-76.478882 37.678329,-76.702499 37.833054,-76.834442 37.953049,-76.885994 38.025192,-76.910973 38.067635,-76.931946 38.089714,-77.054512 38.160683,-77.129890 38.169121,-77.110695 38.141937,-77.020836 38.096378,-76.985970 38.093327,-76.947914 38.076942,-76.923332 38.053604,-76.902916 38.006161,-76.848473 37.927769,-76.720276 37.794994,-76.663750 37.763607,-76.636108 37.761108,-76.615005 37.752777,-76.589722 37.727486,-76.576675 37.692764,-76.564163 37.660408,-76.538887 37.630272,-76.518616 37.620266,-76.421387 37.603325,-76.290695 37.568607,-76.245270 37.495270,-76.236664 37.428673,-76.239441 37.373463,-76.261124 37.334160,-76.289444 37.335548,-76.365280 37.383881,-76.403473 37.345821,-76.376488 37.280514,-76.448334 37.262772,-76.454727 37.261940,-76.479515 37.268810,-76.578888 37.323608,-76.682770 37.429718,-76.670547 37.386658,-76.606110 37.305824,-76.585556 37.291939,-76.543060 37.268883,-76.465561 37.229713,-76.442635 37.223045,-76.377213 37.214157,-76.290001 37.135548,-76.267715 37.086311,-76.291458 37.005344,-76.389725 36.973320,-76.436386 36.997215,-76.557495 37.084435,-76.613121 37.133949,-76.613884 37.156101,-76.613609 37.183601,-76.631393 37.216240,-76.653885 37.226936,-76.678329 37.226097,-76.785225 37.235046,-76.887466 37.247879,-76.903679 37.266087,-76.974167 37.298882,-76.990273 37.312908,-77.238602 37.336105,-77.232224 37.296387,-77.146118 37.291939,-77.027222 37.283607,-76.864944 37.213383,-76.716660 37.147491,-76.644867 37.046803,-76.575562 37.015831,-76.479652 36.957771,-76.477493 36.905266,-76.331680 36.863609,-76.293610 36.843323,-76.318062 36.881104,-76.314369 36.944920,-76.255142 36.957912,-76.235550 36.950829,-76.195267 36.929436,-76.160835 36.918880,-76.057220 36.906586,-76.013893 36.920059,-75.987289 36.909229,-75.962921 36.854298,-75.886398 36.640549,-75.851685 36.549072,-75.849442 36.531662,-75.844162 36.506660,-75.827789 36.440826,-75.809158 36.370827,-75.785278 36.283607,-75.712082 36.116520,-75.699997 36.096657,-75.659164 36.043610,-75.635834 36.007774,-75.575562 35.908882,-75.553329 35.858887,-75.532646 35.801521,-75.556946 35.808044,-75.589027 35.856453,-75.589790 35.897491,-75.636948 35.952908,-75.660828 35.974434,-75.683319 35.991661,-75.700836 36.008049,-75.728607 36.061104,-75.738609 36.123634,-75.751251 36.182770,-75.758202 36.202213,-75.768341 36.222488,-75.811661 36.319443,-75.863892 36.476379,-75.869995 36.498604,-75.879166 36.532768,-75.882706 36.549942,-75.881943 36.581940,-75.911392 36.665268,-75.945305 36.712421,-75.966660 36.680824,-75.975555 36.620827,-75.975830 36.565823,-75.968842 36.549721,-75.949028 36.542530,-75.943298 36.549721,-75.938255 36.563671,-75.912643 36.573189,-75.909241 36.549995,-75.899582 36.492771,-75.926941 36.484993,-75.969933 36.491936,-76.012802 36.549843,-76.019585 36.566727,-76.042358 36.574642,-76.028992 36.549995)),((-123.093750 48.999435,-123.034317 48.999435,-123.045868 48.977486,-123.086533 48.972073,-123.093750 48.999435)),((-122.895554 48.711105,-122.883057 48.711105,-122.858612 48.706100,-122.844727 48.701103,-122.780838 48.676941,-122.748329 48.659992,-122.751114 48.649021,-122.807632 48.605412,-122.878326 48.587906,-122.899437 48.586105,-122.919998 48.587494,-123.000420 48.599575,-123.012497 48.605827,-123.023338 48.624298,-123.020279 48.635551,-122.940277 48.704437,-122.926247 48.710827,-122.895554 48.711105)),((-123.099731 48.603882,-123.038330 48.561378,-122.995003 48.529716,-122.962639 48.452633,-123.004173 48.445683,-123.095284 48.474991,-123.121933 48.484718,-123.139450 48.494156,-123.148621 48.501663,-123.155563 48.511108,-123.176796 48.551659,-123.177284 48.591724,-123.152496 48.616524,-123.141388 48.618881,-123.105904 48.611454,-123.099731 48.603882)),((-122.868057 48.552490,-122.855560 48.524162,-122.814728 48.467216,-122.808884 48.454437,-122.807503 48.442490,-122.807770 48.427494,-122.814438 48.417912,-122.827087 48.416382,-122.839172 48.417770,-122.860550 48.421379,-122.934860 48.455273,-122.936661 48.474991,-122.936111 48.491661,-122.916107 48.536663,-122.870476 48.560612,-122.868057 48.552490)),((-122.588333 48.392220,-122.520279 48.327217,-122.505836 48.307491,-122.514450 48.296104,-122.526947 48.290833,-122.551109 48.283329,-122.562767 48.285271,-122.572502 48.296108,-122.584999 48.301521,-122.614716 48.300755,-122.663887 48.244713,-122.649307 48.227211,-122.624161 48.219711,-122.607224 48.211105,-122.592216 48.200546,-122.583328 48.192764,-122.486389 48.101105,-122.365280 48.037498,-122.338058 47.981659,-122.335136 47.967491,-122.342216 47.954712,-122.369995 47.921383,-122.423317 47.925827,-122.531677 47.981102,-122.561394 48.022217,-122.606659 48.087494,-122.741379 48.210548,-122.750290 48.219154,-122.756805 48.231102,-122.753754 48.248604,-122.661118 48.377487,-122.596390 48.406242,-122.588333 48.392220)),((-122.381104 47.394714,-122.410553 47.387215,-122.483887 47.347355,-122.494453 47.345825,-122.504181 47.353050,-122.518547 47.371517,-122.511124 47.408882,-122.496109 47.461105,-122.449440 47.516315,-122.442490 47.491104,-122.421944 47.432213,-122.415283 47.423050,-122.381104 47.394714)),((-68.241379 44.438881,-68.192490 44.391106,-68.185547 44.382492,-68.174438 44.364716,-68.168884 44.349365,-68.182495 44.332771,-68.192764 44.325272,-68.323761 44.236519,-68.335556 44.238327,-68.406258 44.271381,-68.414719 44.281937,-68.427498 44.321659,-68.406113 44.369438,-68.365273 44.428604,-68.350281 44.440266,-68.298615 44.449158,-68.259171 44.452080,-68.245552 44.446518,-68.241379 44.438881)),((-68.632767 44.276657,-68.626099 44.273323,-68.615829 44.266106,-68.604301 44.251244,-68.604721 44.224991,-68.615135 44.188187,-68.647781 44.169857,-68.664719 44.167496,-68.710564 44.177769,-68.720970 44.231655,-68.671112 44.284302,-68.659729 44.283882,-68.632767 44.276657)),((-71.220551 41.633331,-71.227493 41.539436,-71.232773 41.494713,-71.297501 41.458603,-71.355621 41.457630,-71.309723 41.561104,-71.263191 41.630482,-71.220978 41.651939,-71.220551 41.633331)),((-70.556946 41.465271,-70.549164 41.457497,-70.542221 41.449158,-70.510284 41.408043,-70.509171 41.355412,-70.519165 41.352776,-70.548050 41.353882,-70.579727 41.356384,-70.601105 41.356941,-70.629990 41.355827,-70.676392 41.351662,-70.696655 41.348877,-70.728058 41.341934,-70.742493 41.335686,-70.753067 41.325554,-70.754311 41.313049,-70.765427 41.308739,-70.781113 41.316101,-70.802490 41.330276,-70.811935 41.337212,-70.834999 41.361176,-70.656387 41.458885,-70.617218 41.473877,-70.563049 41.468880,-70.556946 41.465271)),((-70.019455 41.383881,-69.994995 41.328049,-69.959862 41.282215,-69.962570 41.265965,-69.979446 41.255272,-69.993881 41.250275,-70.013626 41.247772,-70.034729 41.246941,-70.093613 41.248047,-70.107773 41.248329,-70.140839 41.256660,-70.232224 41.281662,-70.197769 41.294159,-70.177490 41.295830,-70.109589 41.296246,-70.035278 41.359161,-70.019455 41.383881)),((-72.867767 40.756104,-72.890556 40.773743,-73.010910 40.752911,-73.095276 40.730545,-73.140289 40.718880,-73.438599 40.665825,-73.561111 40.645271,-73.652786 40.619987,-73.587296 40.603603,-73.618057 40.594437,-73.653610 40.593880,-73.797226 40.592216,-73.777283 40.614895,-73.771111 40.635437,-73.812775 40.656654,-73.836388 40.659435,-73.859718 40.656796,-73.899734 40.635826,-73.881248 40.609436,-73.943321 40.585270,-74.004448 40.580414,-74.032501 40.625824,-74.031044 40.648949,-74.005005 40.679993,-74.002502 40.694435,-73.939987 40.773048,-73.916946 40.792358,-73.835556 40.804993,-73.731674 40.851662,-73.617630 40.909019,-73.589447 40.920547,-73.490555 40.934158,-73.354172 40.925827,-73.226669 40.910545,-73.198883 40.917492,-73.150421 40.943043,-73.037216 40.968597,-72.893616 40.969986,-72.781387 40.965546,-72.758339 40.963745,-72.637642 40.981659,-72.613609 40.990131,-72.577499 41.015549,-72.527946 41.045216,-72.453064 41.088882,-72.350830 41.140831,-72.285278 41.161934,-72.241661 41.157074,-72.257645 41.129158,-72.285484 41.119434,-72.388336 41.084991,-72.617111 40.917595,-72.584732 40.906097,-72.491241 40.904575,-72.436241 40.922356,-72.401947 40.964714,-72.345840 40.999718,-72.263626 41.019440,-72.135010 41.035271,-72.109932 41.005482,-72.053329 41.016106,-72.021324 41.033325,-72.000694 41.050964,-71.919998 41.082077,-71.866798 41.074783,-72.084167 40.981659,-72.352783 40.887215,-72.446655 40.855553,-72.542770 40.825554,-72.665833 40.794441,-72.698608 40.789719,-72.819458 40.769989,-72.867767 40.756104)),((-74.062775 40.639435,-74.055412 40.619854,-74.055550 40.602077,-74.108612 40.559715,-74.123322 40.549721,-74.145004 40.538887,-74.220001 40.511665,-74.235207 40.514717,-74.232498 40.538887,-74.183334 40.634579,-74.173889 40.642353,-74.078339 40.650272,-74.068893 40.645828,-74.062775 40.639435)),((-75.527222 35.235550,-75.610001 35.222214,-75.653610 35.225548,-75.534027 35.269577,-75.521942 35.278046,-75.517227 35.289719,-75.512512 35.307770,-75.491943 35.418053,-75.465012 35.579994,-75.464722 35.591103,-75.474167 35.634720,-75.482773 35.669716,-75.504181 35.727486,-75.510834 35.740273,-75.526665 35.768394,-75.514801 35.775963,-75.494995 35.753052,-75.482773 35.730820,-75.476944 35.714714,-75.451675 35.618050,-75.447769 35.603050,-75.447495 35.582497,-75.483063 35.345825,-75.488892 35.325272,-75.515839 35.246384,-75.527222 35.235550)),((-119.868057 34.084160,-119.698334 34.045273,-119.593613 34.053879,-119.563187 34.065830,-119.552780 34.065826,-119.515564 34.044579,-119.532990 34.015133,-119.589996 33.997215,-119.713333 33.970821,-119.772781 33.967209,-119.788330 33.967209,-119.836937 33.974159,-119.870972 33.991520,-119.917770 34.065269,-119.914230 34.082630,-119.868057 34.084160)),((-120.000000 33.989632,-119.969444 33.992355,-119.966393 33.962490,-120.036530 33.919159,-120.107498 33.905548,-120.121658 33.908043,-120.145279 33.916664,-120.164436 33.927773,-120.172234 33.934715,-120.192207 33.959435,-120.226097 34.006104,-120.184723 34.015831,-120.135010 34.026100,-120.051941 34.036110,-120.035278 34.023880,-120.000000 33.989632)),((-118.516663 33.477768,-118.445267 33.442764,-118.403343 33.428047,-118.349731 33.398331,-118.297234 33.346100,-118.293121 33.328674,-118.303741 33.309853,-118.449646 33.328606,-118.589928 33.483810,-118.581123 33.490829,-118.541801 33.489437,-118.528893 33.486244,-118.516663 33.477768)),((-118.530289 32.993324,-118.526108 32.983604,-118.520279 32.974991,-118.504997 32.959717,-118.482224 32.938042,-118.413330 32.885551,-118.369164 32.854713,-118.369453 32.832771,-118.408607 32.817078,-118.477783 32.852776,-118.486938 32.858887,-118.493881 32.866661,-118.533890 32.927216,-118.570557 32.984161,-118.594864 33.033051,-118.593895 33.044582,-118.554428 33.043053,-118.530289 32.993324)),((-86.558884 30.396664,-86.625404 30.399719,-86.750565 30.398052,-86.910278 30.372219,-86.992493 30.358608,-87.066666 30.345829,-87.089172 30.339996,-87.175278 30.327496,-87.209732 30.322498,-87.251114 30.317427,-87.270004 30.320553,-87.283615 30.326107,-87.290344 30.334579,-87.145004 30.346107,-87.021667 30.370831,-86.890564 30.388607,-86.776947 30.403328,-86.763062 30.404995,-86.734436 30.407219,-86.701401 30.408607,-86.631104 30.411106,-86.585419 30.410412,-86.527641 30.397045,-86.558884 30.396664)),((-91.724167 29.558609,-91.782921 29.487635,-91.842087 29.482494,-91.987778 29.550831,-92.027496 29.571110,-92.036804 29.581387,-92.034439 29.591663,-92.023056 29.603886,-92.005974 29.617981,-91.922920 29.644442,-91.910553 29.645275,-91.868057 29.637775,-91.856384 29.634995,-91.738327 29.576942,-91.724167 29.558609)),((-94.841949 29.269444,-94.841949 29.268055,-94.857224 29.254997,-94.869995 29.246105,-94.879166 29.240273,-95.112320 29.101561,-95.100281 29.120274,-95.091385 29.129440,-94.956116 29.237774,-94.821396 29.338608,-94.781509 29.318365,-94.784729 29.308052,-94.841949 29.269444)),((-80.660553 28.318886,-80.669647 28.280693,-80.665695 28.262499,-80.659721 28.243189,-80.723618 28.379162,-80.740280 28.478329,-80.736664 28.524998,-80.731659 28.539164,-80.695541 28.574997,-80.643059 28.597635,-80.624916 28.589863,-80.613892 28.574997,-80.610275 28.560274,-80.610550 28.548332,-80.615555 28.533886,-80.626938 28.512497,-80.633621 28.500553,-80.639999 28.486938,-80.646118 28.473328,-80.654175 28.447216,-80.669022 28.373608,-80.660553 28.318886)),((-96.776642 28.192055,-96.774170 28.191383,-96.756393 28.194439,-96.710976 28.204439,-96.663612 28.237495,-96.654999 28.247215,-96.644585 28.260693,-96.507233 28.334995,-96.430695 28.376801,-96.425140 28.390135,-96.409927 28.395205,-96.400558 28.367218,-96.399734 28.350552,-96.407089 28.336109,-96.419449 28.324997,-96.449432 28.310829,-96.470001 28.303329,-96.486389 28.297775,-96.528336 28.279720,-96.551941 28.266666,-96.692490 28.182774,-96.706665 28.173607,-96.736938 28.153885,-96.753616 28.141106,-96.805557 28.099998,-96.813614 28.092495,-96.817505 28.109997,-96.810829 28.165272,-96.803879 28.178608,-96.794449 28.189438,-96.782776 28.192493,-96.776642 28.192055)),((-96.839172 28.106384,-96.848618 28.083885,-96.887787 28.030552,-97.025284 27.869442,-97.035828 27.875275,-97.023895 27.911663,-96.921936 28.089718,-96.870407 28.134718,-96.842781 28.118330,-96.836388 28.108887,-96.839172 28.106384)),((-80.432220 27.843330,-80.404999 27.776943,-80.400833 27.767498,-80.391953 27.749718,-80.371658 27.714718,-80.328613 27.593052,-80.292496 27.468884,-80.281387 27.442219,-80.237778 27.363884,-80.167496 27.199440,-80.165146 27.186247,-80.187210 27.207077,-80.206390 27.244160,-80.288895 27.413330,-80.389999 27.699162,-80.444923 27.850412,-80.432220 27.843330)),((-97.246384 27.544441,-97.266953 27.509720,-97.294449 27.457218,-97.308609 27.424438,-97.329453 27.372498,-97.337784 27.350552,-97.344727 27.326385,-97.356110 27.273609,-97.368057 27.239162,-97.374855 27.225550,-97.387985 27.222425,-97.386253 27.277496,-97.374710 27.343052,-97.370270 27.362495,-97.336945 27.450829,-97.332230 27.461636,-97.317230 27.495827,-97.306664 27.512915,-97.281387 27.551109,-97.162781 27.725552,-97.153336 27.737774,-97.073891 27.835415,-97.063057 27.841942,-97.043190 27.839857,-97.043060 27.829163,-97.051102 27.819717,-97.075836 27.792221,-97.102219 27.765274,-97.117493 27.746384,-97.166656 27.680550,-97.174164 27.668327,-97.244995 27.548054,-97.246384 27.544441)),((-97.358246 26.706963,-97.366257 26.801558,-97.385757 26.838224,-97.400558 27.020832,-97.401108 27.052498,-97.399994 27.120274,-97.399445 27.134995,-97.397507 27.149441,-97.383194 27.202530,-97.379715 27.178608,-97.383331 27.135273,-97.386673 27.051388,-97.385834 27.010555,-97.383896 26.996105,-97.358673 26.839275,-97.355751 26.823023,-97.342842 26.774607,-97.325287 26.696106,-97.289444 26.596664,-97.261398 26.522499,-97.248337 26.481384,-97.227783 26.410828,-97.206390 26.328331,-97.199158 26.287777,-97.179718 26.165272,-97.172226 26.117775,-97.171112 26.101940,-97.176598 26.087776,-97.188599 26.096664,-97.195541 26.120552,-97.199432 26.139996,-97.206390 26.231106,-97.224716 26.343330,-97.277786 26.504166,-97.304443 26.576385,-97.346115 26.684162,-97.358246 26.706963)),((-80.600861 24.950809,-80.571671 24.966661,-80.455566 25.091385,-80.410278 25.150829,-80.387550 25.181795,-80.358887 25.218884,-80.341675 25.257500,-80.331390 25.291107,-80.286804 25.341803,-80.273888 25.348747,-80.260979 25.348053,-80.256813 25.335274,-80.267776 25.328331,-80.364166 25.160551,-80.370270 25.146109,-80.575356 24.947216,-80.595146 24.946384,-80.600861 24.950809)),((-159.451416 21.869991,-159.461121 21.883745,-159.505432 21.897078,-159.560272 21.900269,-159.707520 21.958050,-159.754196 21.979160,-159.786682 22.022221,-159.790314 22.035969,-159.789490 22.050831,-159.785309 22.061382,-159.730316 22.137215,-159.714615 22.154163,-159.582642 22.226242,-159.552658 22.236103,-159.401672 22.239159,-159.349579 22.219990,-159.327484 22.201656,-159.317505 22.190269,-159.291824 22.141384,-159.288940 22.126942,-159.333099 21.965546,-159.378601 21.920830,-159.433624 21.881386,-159.451416 21.869991)),((-160.199768 21.783604,-160.204468 21.783604,-160.231689 21.800549,-160.246399 21.811523,-160.247925 21.843330,-160.227203 21.891380,-160.197540 21.919991,-160.182800 21.934158,-160.086243 22.017355,-160.061401 22.013882,-160.046539 21.998051,-160.071136 21.909161,-160.091278 21.896523,-160.114990 21.887497,-160.130417 21.884716,-160.147812 21.885830,-160.182220 21.836941,-160.199768 21.783604)),((-157.813080 21.258884,-157.867798 21.319160,-157.887527 21.332775,-157.902527 21.336941,-157.926132 21.320688,-157.985260 21.302498,-158.100571 21.294443,-158.108200 21.301382,-158.111664 21.315269,-158.113892 21.333607,-158.116394 21.344719,-158.123077 21.359158,-158.130859 21.372768,-158.136414 21.381386,-158.178070 21.426384,-158.203064 21.451939,-158.220001 21.463051,-158.235199 21.478533,-158.273499 21.577772,-158.264771 21.586658,-158.106934 21.609715,-158.047241 21.666103,-158.031708 21.679440,-158.011856 21.692354,-157.971924 21.699436,-157.957764 21.692772,-157.943909 21.684441,-157.928894 21.670547,-157.922546 21.662495,-157.876678 21.576664,-157.855133 21.511387,-157.844177 21.471104,-157.803360 21.434713,-157.780716 21.426937,-157.730316 21.411659,-157.665588 21.324162,-157.708649 21.268604,-157.760590 21.271381,-157.813080 21.258884)),((-156.867493 21.045830,-156.875000 21.046104,-156.888367 21.048054,-156.956390 21.070827,-157.021942 21.095551,-157.037231 21.102493,-157.054443 21.106937,-157.067810 21.108887,-157.082764 21.109440,-157.096130 21.108887,-157.119141 21.102776,-157.157516 21.094440,-157.259460 21.088051,-157.297394 21.090134,-157.304047 21.097773,-157.294174 21.143606,-157.286987 21.154442,-157.244141 21.198605,-157.188629 21.209717,-157.034760 21.194996,-156.974457 21.183048,-156.894470 21.161102,-156.843628 21.160275,-156.829163 21.160275,-156.810654 21.165201,-156.791397 21.176659,-156.750458 21.172773,-156.705154 21.155548,-156.714722 21.139439,-156.750290 21.090826,-156.762131 21.080826,-156.838593 21.052773,-156.849457 21.049164,-156.867493 21.045830)),((-156.374176 20.580830,-156.388367 20.582214,-156.420013 20.588608,-156.444046 20.611940,-156.448090 20.638329,-156.448334 20.658051,-156.446960 20.699162,-156.447540 20.718884,-156.451660 20.735268,-156.471954 20.788330,-156.483124 20.797842,-156.501404 20.799438,-156.517548 20.793884,-156.534317 20.786247,-156.570282 20.798328,-156.586426 20.804714,-156.626923 20.821381,-156.640564 20.829720,-156.688629 20.886105,-156.701599 20.926102,-156.697266 20.947495,-156.692230 20.956940,-156.661438 21.013611,-156.597092 21.051382,-156.526672 20.993881,-156.519470 20.986656,-156.511169 20.973602,-156.503387 20.953606,-156.494720 20.934158,-156.480011 20.902773,-156.470444 20.897356,-156.387390 20.913328,-156.378052 20.918325,-156.363312 20.936108,-156.352509 20.939995,-156.333359 20.946104,-156.288635 20.949856,-156.231384 20.935478,-156.216644 20.916386,-156.206696 20.904713,-156.196136 20.893604,-156.187500 20.887497,-156.113907 20.840830,-156.087769 20.840275,-156.027237 20.811245,-156.002258 20.794994,-155.993347 20.782494,-155.987244 20.764299,-155.988068 20.751108,-155.994720 20.732216,-156.001709 20.717213,-156.008087 20.708881,-156.045319 20.673882,-156.061707 20.661102,-156.139816 20.629574,-156.158630 20.630276,-156.169769 20.634438,-156.182220 20.637215,-156.199432 20.638050,-156.342239 20.595690,-156.374176 20.580830)),((-156.907257 20.737774,-156.966125 20.743465,-157.055969 20.886662,-157.055573 20.910828,-157.046417 20.919022,-157.033081 20.923050,-157.014191 20.925823,-157.000610 20.926659,-156.924194 20.927843,-156.905029 20.920830,-156.890320 20.913052,-156.877228 20.903885,-156.823090 20.854443,-156.812256 20.843609,-156.805008 20.826384,-156.807373 20.815691,-156.817505 20.800274,-156.833099 20.779442,-156.839478 20.771111,-156.847260 20.764439,-156.891998 20.744160,-156.907257 20.737774)),((-155.823334 20.272495,-155.744736 20.242214,-155.727081 20.230268,-155.720551 20.207214,-155.574890 20.128328,-155.514771 20.120831,-155.432358 20.100275,-155.341248 20.062357,-155.210999 20.001663,-155.183350 19.985132,-155.160431 19.964439,-155.139191 19.941105,-155.085159 19.880411,-155.000854 19.746101,-154.966644 19.650269,-154.924194 19.609577,-154.859711 19.575272,-154.797821 19.538086,-154.815170 19.477633,-154.832077 19.455965,-155.005585 19.328880,-155.145294 19.283333,-155.167267 19.276939,-155.188339 19.273190,-155.212387 19.274719,-155.240845 19.284163,-155.287109 19.275690,-155.498322 19.137772,-155.518646 19.124165,-155.539276 19.103466,-155.551132 19.076803,-155.553894 19.042496,-155.589874 18.987770,-155.663147 18.925478,-155.676102 18.955618,-155.703918 18.976936,-155.800430 19.030897,-155.855148 19.031246,-155.900299 19.090340,-155.907867 19.158743,-155.900330 19.213051,-155.890320 19.269444,-155.879089 19.361799,-156.012527 19.666037,-156.037537 19.706383,-156.048981 19.735060,-156.046112 19.768604,-156.035156 19.788675,-155.967636 19.850967,-155.929581 19.860691,-155.813263 20.004025,-155.811127 20.034304,-155.823410 20.051802,-155.853882 20.083328,-155.874039 20.113815,-155.894547 20.173744,-155.887955 20.222216,-155.878601 20.246658,-155.867767 20.265133,-155.846542 20.277634,-155.823334 20.272495)),((-75.139740 19.962872,-75.087234 19.965553,-75.085556 19.917221,-75.085281 19.893040,-75.121399 19.887497,-75.134445 19.886944,-75.159729 19.890484,-75.164459 19.902496,-75.139740 19.962872)),((-75.159180 19.960693,-75.170288 19.931389,-75.223724 19.901554,-75.226959 19.924442,-75.193207 19.960972,-75.159180 19.963055,-75.159180 19.960693))"; + + static private String usaGeometry() { + try { + return FileUtils.readFileToString( + DataUtilities.urlToFile(DataExamples.class.getResource("usa-geometry.wkt")), + "UTF-8"); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + /** + * Show USA geometry can be loaded and used to make a SimpleFeature. + */ + public static void main(String[] args) { + try { + System.out.println(createCountry()); + } catch (Exception e) { + throw new RuntimeException(e); + } } - }
false
false
null
null
diff --git a/java/gadgets/src/test/java/org/apache/shindig/gadgets/servlet/HtmlAccelServletTest.java b/java/gadgets/src/test/java/org/apache/shindig/gadgets/servlet/HtmlAccelServletTest.java index 2cce7e5e5..f75bd1156 100644 --- a/java/gadgets/src/test/java/org/apache/shindig/gadgets/servlet/HtmlAccelServletTest.java +++ b/java/gadgets/src/test/java/org/apache/shindig/gadgets/servlet/HtmlAccelServletTest.java @@ -1,288 +1,289 @@ /* * 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.shindig.gadgets.servlet; import static org.easymock.EasyMock.capture; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.isA; import com.google.common.collect.Maps; import org.apache.shindig.common.uri.Uri; import org.apache.shindig.gadgets.Gadget; import org.apache.shindig.gadgets.GadgetContext; import org.apache.shindig.gadgets.UrlGenerator; import org.apache.shindig.gadgets.UrlValidationStatus; import org.apache.shindig.gadgets.http.HttpRequest; import org.apache.shindig.gadgets.http.HttpResponse; import org.apache.shindig.gadgets.http.HttpResponseBuilder; import org.apache.shindig.gadgets.render.Renderer; import org.apache.shindig.gadgets.render.RenderingResults; import org.easymock.Capture; import org.junit.Before; import org.junit.Test; import java.util.Collection; import java.util.Map; public class HtmlAccelServletTest extends ServletTestFixture { private static final String REWRITE_CONTENT = "working rewrite"; private static final String SERVLET = "/gadgets/accel"; private HtmlAccelServlet servlet; private Renderer renderer; @Before public void setUp() throws Exception { servlet = new HtmlAccelServlet(); servlet.setRequestPipeline(pipeline); servlet.setUrlGenerator(new FakeUrlGenerator()); renderer = mock(Renderer.class); servlet.setRenderer(renderer); } @Test public void testHtmlAccelNoData() throws Exception { String url = "http://example.org/data.html"; HttpRequest req = new HttpRequest(Uri.parse(url)); expect(pipeline.execute(req)).andReturn(null).once(); expectRequest("", url); replay(); servlet.doGet(request, recorder); verify(); assertEquals("Error fetching data", recorder.getResponseAsString()); assertEquals(400, recorder.getHttpStatusCode()); } @Test public void testHtmlAccelNoHtml() throws Exception { String url = "http://example.org/data.xml"; String data = "<html><body>Hello World</body></html>"; HttpRequest req = new HttpRequest(Uri.parse(url)); HttpResponse resp = new HttpResponseBuilder() .setResponse(data.getBytes()) .setHeader("Content-Type", "text/xml") .setHttpStatusCode(200) .create(); expect(pipeline.execute(req)).andReturn(resp).once(); expectRequest("", url); replay(); servlet.doGet(request, recorder); verify(); assertEquals(data, recorder.getResponseAsString()); } @Test public void testHtmlAccelRewriteSimple() throws Exception { String url = "http://example.org/data.html"; String data = "<html><body>Hello World</body></html>"; HttpRequest req = new HttpRequest(Uri.parse(url)); HttpResponse resp = new HttpResponseBuilder() .setResponse(data.getBytes()) .setHeader("Content-Type", "text/html") .setHttpStatusCode(200) .create(); expect(pipeline.execute(req)).andReturn(resp).once(); expectRequest("", url); expect(renderer.render(isA(GadgetContext.class))) .andReturn(RenderingResults.ok(REWRITE_CONTENT)); replay(); servlet.doGet(request, recorder); verify(); assertEquals(REWRITE_CONTENT, recorder.getResponseAsString()); assertEquals(200, recorder.getHttpStatusCode()); } @Test public void testHtmlAccelRewriteChain() throws Exception { String url = "http://example.org/data.html?id=1"; String data = "<html><body>Hello World</body></html>"; Capture<HttpRequest> reqCapture = new Capture<HttpRequest>(); HttpResponse resp = new HttpResponseBuilder() .setResponse(data.getBytes()) .setHeader("Content-Type", "text/html") .setCacheTtl(567) .setHttpStatusCode(200) .create(); expect(pipeline.execute(capture(reqCapture))).andReturn(resp).once(); expectRequest("//" + url, null); expect(renderer.render(isA(GadgetContext.class))) .andReturn(RenderingResults.ok(REWRITE_CONTENT)); replay(); servlet.doGet(request, recorder); verify(); HttpRequest req = reqCapture.getValue(); assertEquals(url, req.getUri().toString()); assertEquals("accel", req.getContainer()); assertEquals(REWRITE_CONTENT, recorder.getResponseAsString()); assertEquals(200, recorder.getHttpStatusCode()); - assertEquals("private,max-age=566", recorder.getHeader("Cache-Control")); + assertTrue(recorder.getHeader("Cache-Control").equals("private,max-age=566") + || recorder.getHeader("Cache-Control").equals("private,max-age=567")); // Note: due to rounding (MS to S conversion), ttl is down by 1 } @Test public void testHtmlAccelRewriteChainParams() throws Exception { String url = "http://example.org/data.html?id=1"; String data = "<html><body>Hello World</body></html>"; HttpResponse resp = new HttpResponseBuilder() .setResponse(data.getBytes()) .setHeader("Content-Type", "text/html") .setHttpStatusCode(200) .create(); Capture<HttpRequest> reqCapture = new Capture<HttpRequest>(); expect(pipeline.execute(capture(reqCapture))).andReturn(resp).once(); expectRequest("/container=open&refresh=3600/" + url, null); expect(renderer.render(isA(GadgetContext.class))) .andReturn(RenderingResults.ok(REWRITE_CONTENT)); replay(); servlet.doGet(request, recorder); verify(); HttpRequest req = reqCapture.getValue(); assertEquals(url, req.getUri().toString()); assertEquals("open", req.getContainer()); assertEquals(REWRITE_CONTENT, recorder.getResponseAsString()); assertEquals(200, recorder.getHttpStatusCode()); assertEquals("private,max-age=3600", recorder.getHeader("Cache-Control")); } @Test public void testHtmlAccelRewriteErrorCode() throws Exception { String url = "http://example.org/data.html"; String data = "<html><body>This is error page</body></html>"; HttpRequest req = new HttpRequest(Uri.parse(url)); HttpResponse resp = new HttpResponseBuilder() .setResponse(data.getBytes()) .setHeader("Content-Type", "text/html") .setHttpStatusCode(404) .create(); expect(pipeline.execute(req)).andReturn(resp).once(); expectRequest("", url); expect(renderer.render(isA(GadgetContext.class))) .andReturn(RenderingResults.ok(REWRITE_CONTENT)); replay(); servlet.doGet(request, recorder); verify(); assertEquals(REWRITE_CONTENT, recorder.getResponseAsString()); assertEquals(404, recorder.getHttpStatusCode()); } @Test public void testHtmlAccelRewriteInternalError() throws Exception { String url = "http://example.org/data.html"; String data = "<html><body>This is error page</body></html>"; HttpRequest req = new HttpRequest(Uri.parse(url)); HttpResponse resp = new HttpResponseBuilder() .setResponse(data.getBytes()) .setHeader("Content-Type", "text/html") .setHttpStatusCode(500) .create(); expect(pipeline.execute(req)).andReturn(resp).once(); expectRequest("", url); expect(renderer.render(isA(GadgetContext.class))) .andReturn(RenderingResults.ok(REWRITE_CONTENT)); replay(); servlet.doGet(request, recorder); verify(); assertEquals(REWRITE_CONTENT, recorder.getResponseAsString()); assertEquals(502, recorder.getHttpStatusCode()); } @Test public void testHtmlAccelParams() throws Exception { Renderer newRenderer = new Renderer(null, null, null, lockedDomainService) { @Override public RenderingResults render(GadgetContext context) { assertTrue(HtmlAccelServlet.isAccel(context)); assertEquals("accel", context.getParameter("container")); return RenderingResults.ok(REWRITE_CONTENT); } }; servlet.setRenderer(newRenderer); Map<String,String> paramMap = Maps.newHashMap(); paramMap.put("container","accel"); servlet.setAddedServletParams(paramMap); String url = "http://example.org/data.html"; HttpRequest req = new HttpRequest(Uri.parse(url)); HttpResponse resp = new HttpResponseBuilder() .setHeader("Content-Type", "text/html") .setHttpStatusCode(200) .create(); expect(pipeline.execute(req)).andReturn(resp).once(); expectRequest("", url); replay(); servlet.doGet(request, recorder); verify(); } private void expectRequest(String extraPath, String url) { expect(request.getServletPath()).andReturn(SERVLET).anyTimes(); expect(request.getScheme()).andReturn("http").once(); expect(request.getServerName()).andReturn("apache.org").once(); expect(request.getServerPort()).andReturn(-1).once(); expect(request.getRequestURI()).andReturn(SERVLET + extraPath).anyTimes(); expect(request.getRequestURL()) .andReturn(new StringBuffer("apache.org" + SERVLET + extraPath)) .anyTimes(); String queryParams = (url == null ? "" : "url=" + url); expect(request.getQueryString()).andReturn(queryParams).anyTimes(); } private static class FakeUrlGenerator implements UrlGenerator { public UrlValidationStatus validateJsUrl(String url) { throw new UnsupportedOperationException(); } public String getIframeUrl(Gadget gadget) { throw new UnsupportedOperationException(); } public UrlValidationStatus validateIframeUrl(String url) { return UrlValidationStatus.VALID_UNVERSIONED; } public String getBundledJsUrl(Collection<String> features, GadgetContext context) { throw new UnsupportedOperationException(); } public String getGadgetDomainOAuthCallback(String container, String gadgetHost) { throw new UnsupportedOperationException(); } } }
true
false
null
null
diff --git a/libraries/OpenCL/Core/src/main/java/com/nativelibs4java/opencl/CLProgram.java b/libraries/OpenCL/Core/src/main/java/com/nativelibs4java/opencl/CLProgram.java index 0fb332ce..fc4b56c6 100644 --- a/libraries/OpenCL/Core/src/main/java/com/nativelibs4java/opencl/CLProgram.java +++ b/libraries/OpenCL/Core/src/main/java/com/nativelibs4java/opencl/CLProgram.java @@ -1,694 +1,696 @@ /* * JavaCL - Java API and utilities for OpenCL * http://javacl.googlecode.com/ * * Copyright (c) 2009-2010, Olivier Chafik (http://ochafik.free.fr/) * 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 Olivier Chafik 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 OLIVIER CHAFIK 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 REGENTS AND 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.nativelibs4java.opencl; import static com.nativelibs4java.opencl.CLException.error; import static com.nativelibs4java.opencl.CLException.errorString; import static com.nativelibs4java.opencl.CLException.failedForLackOfMemory; import static com.nativelibs4java.opencl.JavaCL.CL; import static com.nativelibs4java.opencl.library.OpenCLLibrary.CL_PROGRAM_BINARIES; import static com.nativelibs4java.opencl.library.OpenCLLibrary.CL_PROGRAM_BINARY_SIZES; import static com.nativelibs4java.opencl.library.OpenCLLibrary.CL_PROGRAM_BUILD_LOG; import static com.nativelibs4java.opencl.library.OpenCLLibrary.CL_PROGRAM_SOURCE; import static com.nativelibs4java.opencl.library.OpenCLLibrary.CL_SUCCESS; import static com.nativelibs4java.util.JNAUtils.readNSArray; import static com.nativelibs4java.util.JNAUtils.toNS; import java.io.IOException; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.net.MalformedURLException; import java.net.URLConnection; import java.net.URL; import java.nio.ByteOrder; import java.nio.IntBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Arrays; import java.util.Map; import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_device_id; import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_kernel; import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_program; import com.nativelibs4java.util.NIOUtils; import com.ochafik.io.IOUtils; import com.ochafik.io.ReadText; import com.ochafik.lang.jnaerator.runtime.NativeSize; import com.ochafik.lang.jnaerator.runtime.NativeSizeByReference; import com.ochafik.util.string.RegexUtils; import com.sun.jna.Memory; import com.sun.jna.Native; import com.sun.jna.Pointer; import com.sun.jna.ptr.IntByReference; import com.sun.jna.ptr.PointerByReference; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.lang.Process; import java.net.URL; import java.util.Collection; import java.util.regex.Pattern; import java.util.zip.CRC32; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; +import java.util.zip.GZIPOutputStream; +import java.util.zip.GZIPInputStream; /** * OpenCL program.<br/> * An OpenCL program consists of a set of kernels that are identified as functions declared with the __kernel qualifier in the program source. OpenCL programs may also contain auxiliary functions and constant data that can be used by __kernel functions. The program executable can be generated online or offline by the OpenCL compiler for the appropriate target device(s).<br/> * A program object encapsulates the following information: * <ul> * <li>An associated context.</li> * <li>A program source or binary.</li> * <li>The latest successfully built program executable</li> * <li>The list of devices for which the program executable is built</li> * <li>The build options used and a build log. </li> * <li>The number of kernel objects currently attached.</li> * </ul> * * A program can be compiled on the fly (costly) but its binaries can be stored and * loaded back in subsequent executions to avoid recompilation. * @see CLContext#createProgram(java.lang.String[]) * @author Olivier Chafik */ public class CLProgram extends CLAbstractEntity<cl_program> { protected final CLContext context; private static CLInfoGetter<cl_program> infos = new CLInfoGetter<cl_program>() { @Override protected int getInfo(cl_program entity, int infoTypeEnum, NativeSize size, Pointer out, NativeSizeByReference sizeOut) { return CL.clGetProgramInfo(entity, infoTypeEnum, size, out, sizeOut); } }; CLDevice[] devices; CLProgram(CLContext context, CLDevice... devices) { super(null, true); this.context = context; this.devices = devices == null || devices.length == 0 ? context.getDevices() : devices; } CLProgram(CLContext context, Map<CLDevice, byte[]> binaries) { super(null, true); this.context = context; setBinaries(binaries); } protected void setBinaries(Map<CLDevice, byte[]> binaries) { int nDevices = binaries.size(); this.devices = new CLDevice[nDevices]; NativeSize[] lengths = new NativeSize[nDevices]; cl_device_id[] deviceIds = new cl_device_id[nDevices]; Memory binariesArray = new Memory(Pointer.SIZE * nDevices); Memory[] binariesMems = new Memory[nDevices]; int iDevice = 0; for (Map.Entry<CLDevice, byte[]> e : binaries.entrySet()) { CLDevice device = e.getKey(); byte[] binary = e.getValue(); Memory binaryMem = binariesMems[iDevice] = new Memory(binary.length); binaryMem.write(0, binary, 0, binary.length); binariesArray.setPointer(iDevice * Pointer.SIZE, binaryMem); lengths[iDevice] = toNS(binary.length); deviceIds[iDevice] = (devices[iDevice] = device).getEntity(); iDevice++; } PointerByReference binariesPtr = new PointerByReference(); binariesPtr.setPointer(binariesArray); IntBuffer errBuff = NIOUtils.directInts(1, ByteOrder.nativeOrder()); int previousAttempts = 0; IntBuffer statuses = NIOUtils.directInts(nDevices, ByteOrder.nativeOrder()); do { entity = CL.clCreateProgramWithBinary(context.getEntity(), nDevices, deviceIds, lengths, binariesPtr, statuses, errBuff); } while (failedForLackOfMemory(errBuff.get(0), previousAttempts++)); } /** * Write the compiled binaries of this program (for all devices it was compiled for), so that it can be restored later using {@link CLContext#loadProgram(java.io.InputStream) } * @param out will be closed * @throws CLBuildException * @throws IOException */ public void store(OutputStream out) throws CLBuildException, IOException { writeBinaries(getBinaries(), null, out); } private static final void addStoredEntry(ZipOutputStream zout, String name, byte[] data) throws IOException { ZipEntry ze = new ZipEntry(name); ze.setMethod(ZipEntry.STORED); ze.setSize(data.length); CRC32 crc = new CRC32(); crc.update(data,0,data.length); ze.setCrc(crc.getValue()); zout.putNextEntry(ze); zout.write(data); zout.closeEntry(); } private static final String BinariesSignatureZipEntryName = "SIGNATURE"; public static void writeBinaries(Map<CLDevice, byte[]> binaries, String contentSignatureString, OutputStream out) throws IOException { Map<String, byte[]> binaryBySignature = new HashMap<String, byte[]>(); for (Map.Entry<CLDevice, byte[]> e : binaries.entrySet()) binaryBySignature.put(e.getKey().createSignature(), e.getValue()); // Maybe multiple devices will have the same signature : too bad, we don't care and just write one binary per signature. - ZipOutputStream zout = new ZipOutputStream(new BufferedOutputStream(out)); + ZipOutputStream zout = new ZipOutputStream(new GZIPOutputStream(new BufferedOutputStream(out))); if (contentSignatureString != null) addStoredEntry(zout, BinariesSignatureZipEntryName, contentSignatureString.getBytes("utf-8")); for (Map.Entry<String, byte[]> e : binaryBySignature.entrySet()) addStoredEntry(zout, e.getKey(), e.getValue()); zout.close(); } public static Map<CLDevice, byte[]> readBinaries(List<CLDevice> allowedDevices, String expectedContentSignatureString, InputStream in) throws IOException { Map<CLDevice, byte[]> ret = new HashMap<CLDevice, byte[]>(); Map<String, List<CLDevice>> devicesBySignature = CLDevice.getDevicesBySignature(allowedDevices); - ZipInputStream zin = new ZipInputStream(new BufferedInputStream(in)); + ZipInputStream zin = new ZipInputStream(new GZIPInputStream(new BufferedInputStream(in))); ZipEntry ze; ByteArrayOutputStream bout = new ByteArrayOutputStream(); boolean first = true; byte[] b = new byte[65536]; while ((ze = zin.getNextEntry()) != null) { String signature = ze.getName(); boolean isSignature = signature.equals(BinariesSignatureZipEntryName); if (first && !isSignature && expectedContentSignatureString != null || !first && isSignature) throw new IOException("Expected signature to be the first zip entry, got '" + signature + "' instead !"); first = false; bout.reset(); int len; while ((len = zin.read(b)) > 0) bout.write(b, 0, len); byte[] data = bout.toByteArray(); if (isSignature) { if (expectedContentSignatureString != null) { String contentSignatureString = new String(data, "utf-8"); if (!expectedContentSignatureString.equals(contentSignatureString)) throw new IOException("Content signature does not match expected one :\nExpected '" + expectedContentSignatureString + "',\nGot '" + contentSignatureString + "'"); } } else { List<CLDevice> devices = devicesBySignature.get(signature); for (CLDevice device : devices) ret.put(device, data); } } zin.close(); return ret; } List<String> sources = new ArrayList<String>(); Map<CLDevice, cl_program> programByDevice = new HashMap<CLDevice, cl_program>(); public CLDevice[] getDevices() { return devices.clone(); } /// Workaround to avoid crash of ATI Stream 2.0.0 final (beta 3 & 4 worked fine) public static boolean passMacrosAsSources = true; public synchronized void allocate() { if (entity != null) throw new IllegalThreadStateException("Program was already allocated !"); if (passMacrosAsSources) { if (macros != null && !macros.isEmpty()) { StringBuilder b = new StringBuilder(); for (Map.Entry<String, Object> m : macros.entrySet()) b.append("#define " + m.getKey() + " " + m.getValue() + "\n"); this.sources.add(0, b.toString()); } } String[] sources = this.sources.toArray(new String[this.sources.size()]); NativeSize[] lengths = new NativeSize[sources.length]; for (int i = 0; i < sources.length; i++) { lengths[i] = toNS(sources[i].length()); } IntBuffer errBuff = NIOUtils.directInts(1, ByteOrder.nativeOrder()); cl_program program; int previousAttempts = 0; do { program = CL.clCreateProgramWithSource(context.getEntity(), sources.length, sources, lengths, errBuff); } while (failedForLackOfMemory(errBuff.get(0), previousAttempts++)); entity = program; } @Override protected synchronized cl_program getEntity() { if (entity == null) allocate(); return entity; } List<String> includes; /** * Add a path (file or URL) to the list of paths searched for included files.<br> * OpenCL kernels may contain <code>#include "subpath/file.cl"</code> statements.<br> * This automatically adds a "-Ipath" argument to the compilator's command line options.<br> * Note that it's not necessary to add include paths for files that are in the classpath. * @param path A file or URL that points to the root path from which includes can be resolved. */ public synchronized void addInclude(String path) { if (includes == null) includes = new ArrayList<String>(); includes.add(path); resolvedInclusions = null; } public synchronized void addSource(String src) { if (entity != null) throw new IllegalThreadStateException("Program was already allocated : cannot add sources anymore."); sources.add(src); resolvedInclusions = null; } static File tempIncludes = new File(new File(System.getProperty("java.io.tmpdir")), "JavaCL"); Map<String, URL> resolvedInclusions; protected Runnable copyIncludesToTemporaryDirectory() throws IOException { Map<String, URL> inclusions = resolveInclusions(); tempIncludes.mkdirs(); File includesDir = File.createTempFile("includes", "", tempIncludes); includesDir.delete(); includesDir.mkdirs(); final List<File> filesToDelete = new ArrayList<File>(); for (Map.Entry<String, URL> e : inclusions.entrySet()) { System.out.println("[JavaCL] Copying include '" + e.getKey() + "' from '" + e.getValue() + "' to '" + includesDir + "'"); File f = new File(includesDir, e.getKey().replace('/', File.separatorChar)); File p = f.getParentFile(); filesToDelete.add(f); if (p != null) { p.mkdirs(); filesToDelete.add(p); } InputStream in = e.getValue().openStream(); OutputStream out = new FileOutputStream(f); IOUtils.readWrite(in, out); in.close(); out.close(); f.deleteOnExit(); } filesToDelete.add(includesDir); addInclude(includesDir.toString()); return new Runnable() { public void run() { for (File f : filesToDelete) f.delete(); }}; } public Map<String, URL> resolveInclusions() throws IOException { if (resolvedInclusions == null) { resolvedInclusions = new HashMap<String, URL>(); for (String source : sources) resolveInclusions(source, resolvedInclusions); } return resolvedInclusions; } static Pattern includePattern = Pattern.compile("#\\s*include\\s*\"([^\"]+)\""); private void resolveInclusions(String source, Map<String, URL> ret) throws IOException { Collection<String> includedPaths = RegexUtils.find(source, includePattern, 1); //System.out.println("Included paths = " + includedPaths); for (String includedPath : includedPaths) { if (ret.containsKey(includedPath)) continue; URL url = getIncludedSourceURL(includedPath); if (url == null) { System.err.println("[JavaCL] Failed to resolve include '" + includedPath + "'"); } else { String s = ReadText.readText(url); ret.put(includedPath, url); resolveInclusions(s, ret); } } } public String getIncludedSourceContent(String path) throws IOException { URL url = getIncludedSourceURL(path); if (url == null) return null; String src = ReadText.readText(url); return src; } public URL getIncludedSourceURL(String path) throws MalformedURLException { File f = new File(path); if (f.exists()) return f.toURI().toURL(); URL url = getClass().getClassLoader().getResource(path); if (url != null) return url; if (includes != null) for (String include : includes) { f = new File(new File(include), path); if (f.exists()) return f.toURI().toURL(); url = getClass().getClassLoader().getResource(f.toString()); if (url != null) return url; try { url = new URL(include + (include.endsWith("/") ? "" : "/") + path); url.openStream().close(); return url; } catch (IOException ex) { // Bad URL or impossible to read from the URL } } return null; } /** * Get the source code of this program */ public String getSource() { return infos.getString(getEntity(), CL_PROGRAM_SOURCE); } /** * Get the binaries of the program (one for each device, in order) * @return */ public Map<CLDevice, byte[]> getBinaries() throws CLBuildException { synchronized (this) { if (!built) build(); } Memory s = infos.getMemory(getEntity(), CL_PROGRAM_BINARY_SIZES); int n = (int)s.getSize() / Native.SIZE_T_SIZE; NativeSize[] sizes = readNSArray(s, n); //int[] sizes = new int[n]; //for (int i = 0; i < n; i++) { // sizes[i] = s.getNativeLong(i * Native.LONG_SIZE).intValue(); //} Memory[] binMems = new Memory[n]; Memory ptrs = new Memory(n * Native.POINTER_SIZE); for (int i = 0; i < n; i++) { ptrs.setPointer(i * Native.POINTER_SIZE, binMems[i] = new Memory(sizes[i].intValue())); } error(infos.getInfo(getEntity(), CL_PROGRAM_BINARIES, toNS(ptrs.getSize() * Native.POINTER_SIZE), ptrs, null)); Map<CLDevice, byte[]> ret = new HashMap<CLDevice, byte[]>(devices.length); for (int i = 0; i < n; i++) { CLDevice device = devices[i]; Memory bytes = binMems[i]; ret.put(device, bytes.getByteArray(0, sizes[i].intValue())); } return ret; } /** * Returns the context of this program */ public CLContext getContext() { return context; } Map<String, Object> macros; public CLProgram defineMacro(String name, Object value) { createMacros(); macros.put(name, value); return this; } public CLProgram undefineMacro(String name) { if (macros != null) macros.remove(name); return this; } private void createMacros() { if (macros == null) macros = new LinkedHashMap<String, Object>(); } public void defineMacros(Map<String, Object> macros) { createMacros(); this.macros.putAll(macros); } List<String> extraBuildOptions; /** * Please see <a href="http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/clBuildProgram.html">OpenCL's clBuildProgram documentation</a> for details on supported build options. */ public synchronized void addBuildOption(String option) { if (option.startsWith("-I")) { addInclude(option.substring(2)); return; } if (extraBuildOptions == null) extraBuildOptions = new ArrayList<String>(); extraBuildOptions.add(option); } protected String getOptionsString() { StringBuilder b = new StringBuilder("-DJAVACL=1 "); if (extraBuildOptions != null) for (String option : extraBuildOptions) b.append(option).append(' '); // http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/clBuildProgram.html //b.append("-O2 -cl-no-signed-zeros -cl-unsafe-math-optimizations -cl-finite-math-only -cl-fast-relaxed-math -cl-strict-aliasing "); if (!passMacrosAsSources && macros != null && !macros.isEmpty()) for (Map.Entry<String, Object> m : macros.entrySet()) b.append("-D" + m.getKey() + "=" + m.getValue() + " "); if (includes != null) for (String path : includes) if (new File(path).exists()) // path can be an URL as well, in which case it's copied to a local file copyIncludesToTemporaryDirectory() b.append("-I").append(path).append(' '); return b.toString(); } boolean cached = JavaCL.cacheBinaries; public void setCached(boolean cached) { this.cached = cached; } public boolean isCached() { return cached; } protected String computeCacheSignature() throws IOException { StringBuilder b = new StringBuilder(1024); for (CLDevice device : getDevices()) b.append(device).append("\n"); b.append(getOptionsString()).append('\n'); if (macros != null) for (Map.Entry<String, Object> m : macros.entrySet()) b.append("-D").append(m.getKey()).append("=").append(m.getValue()).append('\n'); if (includes != null) for (String path : includes) b.append("-I").append(path).append('\n'); if (sources != null) for (String source : sources) b.append(source).append("\n"); Map<String, URL> inclusions = resolveInclusions(); for (Map.Entry<String, URL> e : inclusions.entrySet()) { URLConnection con = e.getValue().openConnection(); InputStream in = con.getInputStream(); b.append('#').append(e.getKey()).append(con.getLastModified()).append('\n'); in.close(); } return b.toString(); } //static File cacheDirectory = new File(new File(System.getProperty("user.home"), ".javacl"), "cachedProgramBinaries"); static File cacheDirectory = new File(new File(System.getProperty("java.io.tmpdir"), "JavaCL"), "cachedProgramBinaries"); boolean built; /** * Returns the context of this program */ public synchronized CLProgram build() throws CLBuildException { if (built) throw new IllegalThreadStateException("Program was already built !"); String contentSignature = null; File cacheFile = null; boolean readBinaries = false; if (isCached()) { try { contentSignature = computeCacheSignature(); byte[] sha = java.security.MessageDigest.getInstance("MD5").digest(contentSignature.getBytes("utf-8")); StringBuilder shab = new StringBuilder(); for (byte b : sha) shab.append(Integer.toHexString(b & 0xff)); String hash = shab.toString(); cacheFile = new File(cacheDirectory, hash); if (cacheFile.exists()) { Map<CLDevice, byte[]> bins = readBinaries(Arrays.asList(getDevices()), contentSignature, new FileInputStream(cacheFile)); setBinaries(bins); System.out.println("[JavaCL] Read binaries cache from '" + cacheFile + "'"); readBinaries = true; } } catch (Exception ex) { System.err.println("[JavaCL] Failed to load cached program :"); ex.printStackTrace(); } } if (entity == null) allocate(); Runnable deleteTempFiles = null; if (!readBinaries) try { deleteTempFiles = copyIncludesToTemporaryDirectory(); } catch (IOException ex) { throw new CLBuildException(this, ex.toString(), Collections.EMPTY_LIST); } int nDevices = devices.length; cl_device_id[] deviceIds = null; if (nDevices != 0) { deviceIds = new cl_device_id[nDevices]; for (int i = 0; i < nDevices; i++) deviceIds[i] = devices[i].getEntity(); } int err = CL.clBuildProgram(getEntity(), nDevices, deviceIds, readBinaries ? null : getOptionsString(), null, null); //int err = CL.clBuildProgram(getEntity(), 0, null, getOptionsString(), null, null); if (err != CL_SUCCESS) {//BUILD_PROGRAM_FAILURE) { NativeSizeByReference len = new NativeSizeByReference(); int bufLen = 2048 * 32; //TODO find proper size Memory buffer = new Memory(bufLen); HashSet<String> errs = new HashSet<String>(); if (deviceIds == null) { error(CL.clGetProgramBuildInfo(getEntity(), null, CL_PROGRAM_BUILD_LOG, toNS(bufLen), buffer, len)); String s = buffer.getString(0); errs.add(s); } else for (cl_device_id device : deviceIds) { error(CL.clGetProgramBuildInfo(getEntity(), device, CL_PROGRAM_BUILD_LOG, toNS(bufLen), buffer, len)); String s = buffer.getString(0); errs.add(s); } throw new CLBuildException(this, "Compilation failure : " + errorString(err), errs); } built = true; if (deleteTempFiles != null) deleteTempFiles.run(); if (isCached() && !readBinaries) { cacheDirectory.mkdirs(); try { writeBinaries(getBinaries(), contentSignature, new FileOutputStream(cacheFile)); System.out.println("[JavaCL] Wrote binaries cache to '" + cacheFile + "'"); } catch (Exception ex) { new IOException("[JavaCL] Failed to cache program", ex).printStackTrace(); } } return this; } @Override protected void clear() { error(CL.clReleaseProgram(getEntity())); } /** * Return all the kernels found in the program. */ public CLKernel[] createKernels() throws CLBuildException { synchronized (this) { if (!built) build(); } IntByReference pCount = new IntByReference(); int previousAttempts = 0; while (failedForLackOfMemory(CL.clCreateKernelsInProgram(getEntity(), 0, (cl_kernel[])null, pCount), previousAttempts++)) {} int count = pCount.getValue(); cl_kernel[] kerns = new cl_kernel[count]; previousAttempts = 0; while (failedForLackOfMemory(CL.clCreateKernelsInProgram(getEntity(), count, kerns, pCount), previousAttempts++)) {} CLKernel[] kernels = new CLKernel[count]; for (int i = 0; i < count; i++) kernels[i] = new CLKernel(this, null, kerns[i]); return kernels; } /** * Find a kernel by its functionName, and optionally bind some arguments to it. */ public CLKernel createKernel(String name, Object... args) throws CLBuildException { synchronized (this) { if (!built) build(); } IntBuffer errBuff = NIOUtils.directInts(1, ByteOrder.nativeOrder()); cl_kernel kernel; int previousAttempts = 0; do { kernel = CL.clCreateKernel(getEntity(), name, errBuff); } while (failedForLackOfMemory(errBuff.get(0), previousAttempts++)); CLKernel kn = new CLKernel(this, name, kernel); kn.setArgs(args); return kn; } }
false
false
null
null
diff --git a/src/libbitster/Deputy.java b/src/libbitster/Deputy.java index 04a5dd0..9dae162 100644 --- a/src/libbitster/Deputy.java +++ b/src/libbitster/Deputy.java @@ -1,300 +1,301 @@ package libbitster; import java.io.DataInputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.logging.Logger; /** * Deputy is the {@link Actor} that communicates with the Tracker. * It communicates the list of peers to the Manager upon request. * @author Martin Miralles-Cordal * */ public class Deputy extends Actor { private final static Logger log = Logger.getLogger("Deputy"); private String state; // states: // 'init': just created, waiting to establish a connection // 'error': error occurred, exception property will be populated // 'normal': operating normally (may add more such states later) private String announceURL; private String infoHash; private int listenPort; private int announceInterval = 180; // 3 minutes is a safe enough default private Manager manager; boolean timeoutQueued; public Exception exception; // set to an exception if one occurs /** * Constructs a Deputy object * @param metainfo The data from the metainfo file * @param port The port the manager is listening for incoming connections on */ public Deputy(TorrentInfo metainfo, int port, Manager manager) { this.listenPort = port; this.manager = manager; // assemble our announce URL from metainfo announceURL = metainfo.announce_url.getProtocol() + "://" + metainfo.announce_url.getHost() + ":" + metainfo.announce_url.getPort() + metainfo.announce_url.getPath(); // encode our info hash infoHash = escapeURL(metainfo.info_hash); this.timeoutQueued = false; } /** * Encode all characters in a string using URL escaping * @param s The string to encode * @return The US-ASCII encoded string */ public static String escapeURL(String s) { try { return escapeURL(ByteBuffer.wrap(s.getBytes("UTF-8"))); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Your computer somehow doesn't support UTF-8. Hang your head in shame."); } } /** * Encode all characters in a ByteBuffer using URL escaping * @param b The string ByteBuffer to encode * @return The US-ASCII encoded string */ public static String escapeURL(ByteBuffer bb) { final char[] HEX_CHARS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; StringBuffer sb = new StringBuffer(); while(bb.hasRemaining()) { byte b = bb.get(); sb.append('%'); sb.append(HEX_CHARS[( 0x0F & (b >> 4) )]); sb.append(HEX_CHARS[(0x0F & b)]); } return sb.toString(); } @Override protected void receive (Memo memo) { // special force reannounce request from Manager. // payload = null if (memo.getType().equals("list")) { announce(); } // periodic reannounce request sent from the Timeout from itself // calls announce(payload) else if (memo.getType().equals("announce") && memo.getSender() == this) { timeoutQueued = false; if(memo.getPayload() instanceof ByteBuffer) announce((ByteBuffer) memo.getPayload()); else announce(); } else if (memo.getType().equals("done")) { announce(Util.s("&event=completed")); } else if (memo.getType() == "halt") { announce(Util.s("&event=stopped")); shutdown(); } } /** * Announce at regular intervals */ @Override protected void idle () { // send started event to tracker if we're just starting up if(this.getState().equals("init")) { announce(Util.s("&event=started")); } // queue our next announce if(timeoutQueued == false) { Util.setTimeout(announceInterval * 1000, new Memo("announce", null, this)); timeoutQueued = true; } try { Thread.sleep(1000); } catch (Exception e) {} } /** * Sends an HTTP GET request and gets fresh info from the tracker. */ private void announce() { announce(null); } @SuppressWarnings("unchecked") /** * Sends an HTTP GET request and gets fresh info from the tracker. * @param args extra parameters for the HTTP GET request. Must start with "&". */ private void announce(ByteBuffer args) { if(announceURL == null) return; else { - log.info("Contacting tracker."); + log.info("Contacting tracker..."); + + // no longer in init state, may switch to error later + this.setState("normal"); StringBuffer finalURL = new StringBuffer(); // add announce URL finalURL.append(announceURL); // add info hash finalURL.append("?info_hash="); finalURL.append(infoHash); // add peer ID finalURL.append("&peer_id="); finalURL.append(escapeURL(Util.buff2str(manager.getPeerId()))); // add port finalURL.append("&port="); finalURL.append(this.listenPort); // add uploaded finalURL.append("&uploaded="); finalURL.append(manager.getUploaded()); // add downloaded finalURL.append("&downloaded="); finalURL.append(manager.getDownloaded()); // add amount left finalURL.append("&left="); finalURL.append(manager.getLeft()); if(args != null) { finalURL.append(Util.buff2str(args)); } try { // send request to tracker log.finer("Announce URL = " + finalURL.toString()); URL tracker = new URL(finalURL.toString()); URLConnection trackerConn = tracker.openConnection(); // read response byte[] bytes = new byte[trackerConn.getContentLength()]; DataInputStream dis = new DataInputStream(trackerConn.getInputStream()); dis.readFully(bytes); // bdecode response @SuppressWarnings("rawtypes") Map response = (Map) Bencoder2.decode(bytes); // get our peer list and work it into something nicer @SuppressWarnings("rawtypes") ArrayList<Map> rawPeers = (ArrayList<Map>) response.get(Util.s("peers")); ArrayList<Map<String,Object>> peers = parsePeers(rawPeers); // send updated peer list to manager manager.post(new Memo("peers", peers, this)); // get our announce interval - announceInterval = (Integer) response.get(Util.s("interval")); - - this.setState("normal"); + announceInterval = (Integer) response.get(Util.s("interval")); } catch (MalformedURLException e) { error(e, "Error: malformed announce URL " + finalURL.toString()); } catch (IOException e) { - error(e, "Error: Unable to communicate with tracker."); + log.warning("Warning: Unable to communicate with tracker. Retrying in 60 seconds..."); // Try again in a minute Util.setTimeout(60000, new Memo("announce", args, this)); timeoutQueued = true; } catch (BencodingException e) { error(e, "Error: invalid tracker response."); } } } /** * Takes the raw peer list from the tracker response and processes it into something * that's nicer to work with * @param rawPeerList The {@code ArrayList<Map>} of peers sent from announce() * @return An {@code ArrayList<Map<String, Object>>} of peers and their information */ private ArrayList<Map<String, Object>> parsePeers(@SuppressWarnings("rawtypes") ArrayList<Map> rawPeerList) { ArrayList<Map<String, Object>> processedPeerList = new ArrayList<Map<String, Object>>(); for(int i = 0; i < rawPeerList.size(); ++i) { HashMap<String,Object> peerInfo = new HashMap<String,Object>(); // get this peer's peer ID ByteBuffer peer_id_bytes = (ByteBuffer) rawPeerList.get(i).get(ByteBuffer.wrap(new byte[]{'p','e','e','r',' ','i','d'})); peerInfo.put("peerId", peer_id_bytes); // get this peer's ip ByteBuffer ip_bytes = (ByteBuffer) rawPeerList.get(i).get(ByteBuffer.wrap(new byte[]{'i','p'})); String ip = new String(ip_bytes.array()); peerInfo.put("ip", ip); // get this peer's port Integer port = (Integer) rawPeerList.get(i).get(ByteBuffer.wrap(new byte[]{'p','o','r','t'})); peerInfo.put("port", port); // add it to our peer list processedPeerList.add(peerInfo); } return processedPeerList; } /** * Processes an exception and sets the error state * @param e the exception that was thrown */ private void error(Exception e, String logMessage) { this.exception = e; this.setState("error"); log.severe(logMessage); } /** * Get's the deputy's current state * @return the state */ public String getState() { return state; } /** * Validates the input, and if okay, sets the state to it * @param state the state to set */ public void setState(String state) { if(state.equals("init") || state.equals("error") || state.equals("normal")) { this.state = state; } } }
false
false
null
null
diff --git a/com.palantir.typescript/src/com/palantir/typescript/ResourceDeltaVisitor.java b/com.palantir.typescript/src/com/palantir/typescript/ResourceDeltaVisitor.java index 3fdec23..9b145d3 100644 --- a/com.palantir.typescript/src/com/palantir/typescript/ResourceDeltaVisitor.java +++ b/com.palantir.typescript/src/com/palantir/typescript/ResourceDeltaVisitor.java @@ -1,99 +1,103 @@ /* * Copyright 2013 Palantir Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.palantir.typescript; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceDelta; import org.eclipse.core.resources.IResourceDeltaVisitor; import org.eclipse.core.runtime.CoreException; import com.google.common.collect.ImmutableList; import com.palantir.typescript.services.language.FileDelta; import com.palantir.typescript.services.language.FileDelta.Delta; /** * A resource delta visitor which creates a file delta for each TypeScript file it visits. * * @author dcicerone */ public final class ResourceDeltaVisitor implements IResourceDeltaVisitor { /* * The flags used when the content (or encoding) of a file changes. */ private static final int FLAGS = IResourceDelta.CONTENT | IResourceDelta.ENCODING; private final ImmutableList.Builder<FileDelta> deltas; private final IProject project; private ResourceDeltaVisitor(IProject project) { this.deltas = ImmutableList.builder(); this.project = project; } @Override public boolean visit(IResourceDelta delta) throws CoreException { IResource resource = delta.getResource(); IProject resourceProject = resource.getProject(); // skip other projects if (this.project != null && resourceProject != null && !this.project.equals(resourceProject)) { return false; } - // add the delta if its a TypeScript file and a change to the contents (or encoding) of the file - if (resource.getType() == IResource.FILE && resource.getName().endsWith(".ts") && (delta.getFlags() & FLAGS) != 0) { + // add the delta if its a TypeScript file + if (resource.getType() == IResource.FILE && resource.getName().endsWith(".ts")) { String fileName = resource.getRawLocation().toOSString(); Delta deltaEnum = getDeltaEnum(delta); - FileDelta fileDelta = new FileDelta(deltaEnum, fileName); - this.deltas.add(fileDelta); + // check that the delta is a change that impacts the contents (or encoding) of the file + if (deltaEnum != Delta.CHANGED || (delta.getFlags() & FLAGS) != 0) { + FileDelta fileDelta = new FileDelta(deltaEnum, fileName); + + this.deltas.add(fileDelta); + } } return true; } public ImmutableList<FileDelta> getFileDeltas() { return this.deltas.build(); } public static ImmutableList<FileDelta> getFileDeltas(IResourceDelta delta, IProject project) { ResourceDeltaVisitor visitor = new ResourceDeltaVisitor(project); try { delta.accept(visitor); } catch (CoreException e) { throw new RuntimeException(e); } return visitor.getFileDeltas(); } private Delta getDeltaEnum(IResourceDelta delta) { switch (delta.getKind()) { case IResourceDelta.ADDED: return Delta.ADDED; case IResourceDelta.CHANGED: return Delta.CHANGED; case IResourceDelta.REMOVED: return Delta.REMOVED; default: throw new IllegalStateException(); } } }
false
false
null
null
diff --git a/src/main/java/org/atlasapi/media/entity/Identified.java b/src/main/java/org/atlasapi/media/entity/Identified.java index 358275f9..5e175279 100644 --- a/src/main/java/org/atlasapi/media/entity/Identified.java +++ b/src/main/java/org/atlasapi/media/entity/Identified.java @@ -1,234 +1,235 @@ package org.atlasapi.media.entity; import static com.google.common.base.Preconditions.checkNotNull; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Set; import org.atlasapi.content.rdf.annotations.RdfProperty; import org.atlasapi.media.vocabulary.OWL; import org.atlasapi.media.vocabulary.PLAY_USE_IN_RDF_FOR_BACKWARD_COMPATIBILITY; import org.joda.time.DateTime; import com.google.common.base.Function; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.common.primitives.Ints; /** * Base type for descriptions of resources. * * @author Robert Chatley * @author Lee Denison */ public class Identified { private Long id; private String canonicalUri; private String curie; private Set<String> aliases = Sets.newHashSet(); private Set<LookupRef> equivalentTo = Sets.newHashSet(); /** * Records the time that the 3rd party reported that the * {@link Identified} was last updated */ private DateTime lastUpdated; public Identified(String uri, String curie) { this.canonicalUri = uri; this.curie = curie; } public Identified() { /* allow anonymous entities */ this.canonicalUri = null; this.curie = null; } public Identified(String uri) { this(uri, null); } @RdfProperty(relation = true, namespace=OWL.NS, uri="sameAs") public Set<String> getAliases() { return aliases; } public void setCanonicalUri(String canonicalUri) { this.canonicalUri = canonicalUri; } public void setCurie(String curie) { this.curie = curie; } public void setAliases(Iterable<String> uris) { this.aliases = ImmutableSortedSet.copyOf(uris); } public void addAlias(String uri) { addAliases(ImmutableList.of(uri)); } public void addAliases(Iterable<String> uris) { setAliases(Iterables.concat(this.aliases, ImmutableList.copyOf(uris))); } public String getCanonicalUri() { return canonicalUri; } @RdfProperty(relation = false, namespace=PLAY_USE_IN_RDF_FOR_BACKWARD_COMPATIBILITY.NS, uri="curie") public String getCurie() { return curie; } public Set<String> getAllUris() { Set<String> allUris = Sets.newHashSet(getAliases()); allUris.add(getCanonicalUri()); return Collections.unmodifiableSet(allUris); } @Override public String toString() { return getClass().getSimpleName() + "(uri:" + canonicalUri + ")"; } @Override public int hashCode() { if (canonicalUri == null) { return super.hashCode(); } return canonicalUri.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (canonicalUri != null && obj instanceof Identified) { return canonicalUri.equals(((Identified) obj).canonicalUri); } return false; } public void setLastUpdated(DateTime lastUpdated) { this.lastUpdated = lastUpdated; } public DateTime getLastUpdated() { return lastUpdated; } public void addEquivalentTo(Described content) { checkNotNull(content.getCanonicalUri()); this.equivalentTo.add(LookupRef.from(content)); } public Set<LookupRef> getEquivalentTo() { return equivalentTo; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public static final Function<Identified, String> TO_URI = new Function<Identified, String>() { @Override public String apply(Identified description) { return description.getCanonicalUri(); } }; public static final Function<Identified, Long> TO_ID = new Function<Identified, Long>() { @Override public Long apply(Identified input) { return input.getId(); } }; public void setEquivalentTo(Set<LookupRef> uris) { this.equivalentTo = uris; } public static final Comparator<Identified> DESCENDING_LAST_UPDATED = new Comparator<Identified>() { @Override public int compare(final Identified s1, final Identified s2) { if (s1.getLastUpdated() == null && s2.getLastUpdated() == null) { return 0; } if (s2.getLastUpdated() == null) { return -1; } if (s1.getLastUpdated() == null) { return 1; } return s2.getLastUpdated().compareTo(s1.getLastUpdated()); } }; /** * This method attempts to preserve symmetry of * equivalence (since content is persisted independently * there is often a window of inconsistency) */ - public boolean isEquivalentTo(Identified content) { - return equivalentTo.contains(content.getCanonicalUri()) || content.equivalentTo.contains(canonicalUri); + public boolean isEquivalentTo(Described content) { + return equivalentTo.contains(LookupRef.from(content)) + || Iterables.contains(Iterables.transform(content.getEquivalentTo(), LookupRef.TO_ID), canonicalUri); } public static void copyTo(Identified from, Identified to) { to.aliases = Sets.newHashSet(from.aliases); to.canonicalUri = from.canonicalUri; to.curie = from.curie; to.equivalentTo = Sets.newHashSet(from.equivalentTo); to.lastUpdated = from.lastUpdated; } public static <T extends Identified> List<T> sort(List<T> content, final Iterable<String> orderIterable) { final ImmutableList<String> order = ImmutableList.copyOf(orderIterable); Comparator<Identified> byPositionInList = new Comparator<Identified>() { @Override public int compare(Identified c1, Identified c2) { return Ints.compare(indexOf(c1), indexOf(c2)); } private int indexOf(Identified content) { for (String uri : content.getAllUris()) { int idx = order.indexOf(uri); if (idx != -1) { return idx; } } if (content.getCurie() != null) { return order.indexOf(content.getCurie()); } return -1; } }; List<T> toSort = Lists.newArrayList(content); Collections.sort(toSort, byPositionInList); return toSort; } } \ No newline at end of file
true
false
null
null
diff --git a/backend/grisu-core/src/main/java/org/vpac/grisu/control/serviceInterfaces/DummyServiceInterface.java b/backend/grisu-core/src/main/java/org/vpac/grisu/control/serviceInterfaces/DummyServiceInterface.java index 0a6a348b..daf13ebe 100644 --- a/backend/grisu-core/src/main/java/org/vpac/grisu/control/serviceInterfaces/DummyServiceInterface.java +++ b/backend/grisu-core/src/main/java/org/vpac/grisu/control/serviceInterfaces/DummyServiceInterface.java @@ -1,337 +1,343 @@ package org.vpac.grisu.control.serviceInterfaces; import java.io.BufferedInputStream; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Arrays; import java.util.Date; import java.util.List; import javax.activation.DataHandler; import org.apache.commons.vfs.FileContent; import org.apache.commons.vfs.FileObject; import org.apache.commons.vfs.FileSystemException; import org.globus.myproxy.CredentialInfo; import org.globus.myproxy.MyProxy; import org.globus.myproxy.MyProxyException; import org.ietf.jgss.GSSException; import org.vpac.grisu.backend.model.ProxyCredential; import org.vpac.grisu.backend.model.job.Job; import org.vpac.grisu.backend.utils.CertHelpers; import org.vpac.grisu.backend.utils.LocalTemplatesHelper; import org.vpac.grisu.control.JobConstants; import org.vpac.grisu.control.ServiceInterface; import org.vpac.grisu.control.exceptions.JobSubmissionException; import org.vpac.grisu.control.exceptions.NoSuchJobException; import org.vpac.grisu.control.exceptions.NoSuchTemplateException; import org.vpac.grisu.control.exceptions.NoValidCredentialException; import org.vpac.grisu.control.exceptions.RemoteFileSystemException; import org.vpac.grisu.settings.MyProxyServerParams; import org.vpac.grisu.settings.ServerPropertiesManager; import org.vpac.grisu.settings.ServiceTemplateManagement; import org.vpac.grisu.utils.SeveralXMLHelpers; import org.vpac.security.light.control.CertificateFiles; import org.vpac.security.light.control.VomsesFiles; import org.vpac.security.light.myProxy.MyProxy_light; import org.vpac.security.light.plainProxy.LocalProxy; import org.vpac.security.light.voms.VO; import org.vpac.security.light.voms.VOManagement.VOManagement; import org.w3c.dom.Document; import org.w3c.dom.Element; import au.org.arcs.mds.JsdlHelpers; public class DummyServiceInterface extends AbstractServiceInterface implements ServiceInterface { private ProxyCredential credential = null; private String myproxy_username = null; private char[] passphrase = null; @Override protected final ProxyCredential getCredential() { long oldLifetime = -1; try { if (credential != null) { oldLifetime = credential.getGssCredential() .getRemainingLifetime(); } } catch (GSSException e2) { myLogger .debug("Problem getting lifetime of old certificate: " + e2); credential = null; } if (oldLifetime < ServerPropertiesManager .getMinProxyLifetimeBeforeGettingNewProxy()) { myLogger .debug("Credential reached minimum lifetime. Getting new one from myproxy. Old lifetime: " + oldLifetime); this.credential = null; // user.cleanCache(); } if (credential == null || !credential.isValid()) { if (myproxy_username == null || myproxy_username.length() == 0) { if (passphrase == null || passphrase.length == 0) { // try local proxy try { credential = new ProxyCredential(LocalProxy .loadGSSCredential()); } catch (Exception e) { throw new NoValidCredentialException( "Could not load credential/no valid login data."); } if (!credential.isValid()) { throw new NoValidCredentialException( "Local proxy is not valid anymore."); } } } else { // get credential from myproxy String myProxyServer = MyProxyServerParams.getMyProxyServer(); int myProxyPort = MyProxyServerParams.getMyProxyPort(); try { // this is needed because of a possible round-robin myproxy // server myProxyServer = InetAddress.getByName(myProxyServer) .getHostAddress(); } catch (UnknownHostException e1) { // TODO Auto-generated catch block e1.printStackTrace(); throw new NoValidCredentialException( "Could not download myproxy credential: " + e1.getLocalizedMessage()); } try { credential = new ProxyCredential(MyProxy_light .getDelegation(myProxyServer, myProxyPort, myproxy_username, passphrase, 3600)); if (getUser() != null) { getUser().cleanCache(); } } catch (Throwable e) { // TODO Auto-generated catch block e.printStackTrace(); throw new NoValidCredentialException( "Could not get myproxy credential: " + e.getLocalizedMessage()); } if (!credential.isValid()) { throw new NoValidCredentialException( "MyProxy credential is not valid."); } } } return credential; } public final String getTemplate(final String application) throws NoSuchTemplateException { Document doc = ServiceTemplateManagement .getAvailableTemplate(application); if (doc == null) { throw new NoSuchTemplateException( "Could not find template for application: " + application + "."); } return SeveralXMLHelpers.toString(doc); } public final Document getTemplate(final String application, final String version) throws NoSuchTemplateException { Document doc = ServiceTemplateManagement .getAvailableTemplate(application); if (doc == null) { throw new NoSuchTemplateException( "Could not find template for application: " + application + ", version " + version); } return doc; } public final String[] listHostedApplicationTemplates() { return ServiceTemplateManagement.getAllAvailableApplications(); } public final void login(final String username, final String password) { try { LocalTemplatesHelper.copyTemplatesAndMaybeGlobusFolder(); VomsesFiles.copyVomses(); CertificateFiles.copyCACerts(); } catch (Exception e) { // TODO Auto-generated catch block myLogger.debug(e.getLocalizedMessage()); // throw new // RuntimeException("Could not initiate local backend: "+e.getLocalizedMessage()); } this.myproxy_username = username; this.passphrase = password.toCharArray(); try { getCredential(); } catch (Exception e) { // e.printStackTrace(); throw new NoValidCredentialException("No valid credential: " + e.getLocalizedMessage()); } } public final String logout() { Arrays.fill(passphrase, 'x'); return null; } public final long getCredentialEndTime() { String myProxyServer = MyProxyServerParams.getMyProxyServer(); int myProxyPort = MyProxyServerParams.getMyProxyPort(); try { // this is needed because of a possible round-robin myproxy server myProxyServer = InetAddress.getByName(myProxyServer) .getHostAddress(); } catch (UnknownHostException e1) { // TODO Auto-generated catch block e1.printStackTrace(); throw new NoValidCredentialException( "Could not download myproxy credential: " + e1.getLocalizedMessage()); } MyProxy myproxy = new MyProxy(myProxyServer, myProxyPort); CredentialInfo info = null; try { info = myproxy.info(getCredential().getGssCredential(), myproxy_username, new String(passphrase)); } catch (MyProxyException e) { // TODO Auto-generated catch block e.printStackTrace(); } return info.getEndTime(); } public void submitJob(final String jobname) throws JobSubmissionException { myLogger.info("Submitting job: " + jobname + " for user " + getDN()); Job job; try { job = getJob(jobname); } catch (NoSuchJobException e1) { throw new JobSubmissionException("Job: " + jobname + " could not be found in the grisu job database."); } try { myLogger.debug("Preparing job environment..."); prepareJobEnvironment(job); myLogger.debug("Staging files..."); stageFiles(jobname); } catch (Exception e) { throw new JobSubmissionException( "Could not access remote filesystem: " + e.getLocalizedMessage()); } if (job.getFqan() != null) { VO vo = VOManagement.getVO(getUser().getFqans().get(job.getFqan())); try { job.setCredential(CertHelpers.getVOProxyCredential(vo, job .getFqan(), getCredential())); } catch (Exception e) { throw new JobSubmissionException( "Could not create credential to use to submit the job: " + e.getLocalizedMessage()); } } else { job.setCredential(getCredential()); } String handle = null; myLogger.debug("Submitting job to endpoint..."); try { handle = getSubmissionManager().submit("GT4Dummy", job); } catch (RuntimeException e) { e.printStackTrace(); throw new JobSubmissionException( "Job submission to endpoint failed: " + e.getLocalizedMessage()); } if (handle == null) { throw new JobSubmissionException( "Job apparently submitted but jobhandle is null for job: " + jobname); } job.addJobProperty("submissionTime", Long .toString(new Date().getTime())); // we don't want the credential to be stored with the job in this case // TODO or do we want it to be stored? job.setCredential(null); jobdao.saveOrUpdate(job); myLogger.info("Jobsubmission for job " + jobname + " and user " + getDN() + " successful."); } protected int kill(final String jobname) { Job job; try { job = jobdao.findJobByDN(getUser().getDn(), jobname); } catch (NoSuchJobException e) { return JobConstants.NO_SUCH_JOB; } return JobConstants.KILLED; } public void kill(final String jobname, final boolean clear) throws RemoteFileSystemException, NoSuchJobException { Job job; job = jobdao.findJobByDN(getUser().getDn(), jobname); kill(jobname); if (clear) { jobdao.delete(job); } } public void stageFiles(final String jobname) throws RemoteFileSystemException, NoSuchJobException { myLogger.debug("Dummy staging files..."); } - + public String upload(final DataHandler source, final String filename, final boolean return_absolute_url) throws RemoteFileSystemException { return "DummyHandle"; } +// public boolean mkdir(final String url) throws RemoteFileSystemException { +// +// myLogger.debug("Dummy. Not creating folder: " + url + "..."); +// return true; +// +// } }
false
false
null
null
diff --git a/clc/modules/www/test-gwt/src/com/eucalyptus/webui/server/EucaServiceWrapper.java b/clc/modules/www/test-gwt/src/com/eucalyptus/webui/server/EucaServiceWrapper.java index c94d939..b76f64a 100644 --- a/clc/modules/www/test-gwt/src/com/eucalyptus/webui/server/EucaServiceWrapper.java +++ b/clc/modules/www/test-gwt/src/com/eucalyptus/webui/server/EucaServiceWrapper.java @@ -1,218 +1,219 @@ package com.eucalyptus.webui.server; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import com.amazonaws.services.ec2.model.Address; import com.eucalyptus.webui.client.service.SearchResultRow; import com.eucalyptus.webui.client.session.Session; import com.eucalyptus.webui.client.service.EucalyptusServiceException; import com.eucalyptus.webui.server.db.DBProcWrapper; import com.eucalyptus.webui.server.stat.HistoryDBProcWrapper; import com.eucalyptus.webui.shared.dictionary.DBTableColName; import com.eucalyptus.webui.shared.dictionary.DBTableName; import com.eucalyptus.webui.shared.resource.device.IPServiceInfo; import com.eucalyptus.webui.shared.resource.device.TemplateInfo; import com.eucalyptus.webui.shared.resource.device.status.IPState; import com.eucalyptus.webui.shared.resource.device.status.IPType; public class EucaServiceWrapper { static private EucaServiceWrapper instance = null; private static final Logger LOG = Logger.getLogger(EucaServiceWrapper.class); private AwsServiceImpl aws = null; private HistoryDBProcWrapper history = null; private EucaServiceWrapper() { aws = new AwsServiceImpl(); history = new HistoryDBProcWrapper(); } static public EucaServiceWrapper getInstance() { if (instance == null) instance = new EucaServiceWrapper(); return instance; } /** * run a new virtual machine with eucalyptus * @param session * @param template Template.class * @param image DB vm_image_type euca_vit_id * @param keypair string * @param group string * @return euca id of vm */ public String runVM(Session session, int userID, TemplateInfo template, String keypair, String group, String image) throws EucalyptusServiceException { //real code about template won't be in old repo return aws.runInstance(session, userID, image, keypair, "c1.xlarge", group); } public void terminateVM(Session session, int userID, String instanceID) throws EucalyptusServiceException { List<String> ids = new ArrayList<String>(); ids.add(instanceID); aws.terminateInstances(session, userID, ids); } /** * get all keypairs' name owned by user * @param session * @return */ public List<String> getKeypairs(Session session, int userID) throws EucalyptusServiceException { List<SearchResultRow> data = aws.lookupKeypair(session, userID); List<String> ret = new ArrayList<String>(); for (SearchResultRow d: data) { ret.add(d.getField(0)); } return ret; } /** * get all security groups' name can be used by user * @param session * @return */ public List<String> getSecurityGroups(Session session, int userID) throws EucalyptusServiceException { List<SearchResultRow> data = aws.lookupSecurityGroup(session, userID); List<String> ret = new ArrayList<String>(); for (SearchResultRow d: data) { ret.add(d.getField(0)); } return ret; } public List<String> getAvailabilityZones(Session session) throws EucalyptusServiceException { //TODO: unused filter return aws.lookupAvailablityZones(session); } public void bindServerWithZone(int serverID, String zone) { StringBuilder sb = new StringBuilder(); sb.append("UPDATE ").append(DBTableName.SERVER) .append(" SET ").append(DBTableColName.SERVER.EUCA_ZONE) .append(" = '").append(zone).append("' WHERE ") .append(DBTableColName.SERVER.ID) .append(" = '").append(serverID).append("'"); try { DBProcWrapper.Instance().update(sb.toString()); } catch (SQLException e) { //TODO } } public int getServerID(Session session, int userID, String instanceID) throws EucalyptusServiceException { LOG.error("in getServerID: i-id = " + instanceID); String zone = aws.lookupZoneWithInstanceId(session, userID, instanceID); LOG.error("in getServerID: zone = " + zone); StringBuilder sb = new StringBuilder(); sb.append("SELECT ").append(DBTableColName.SERVER.ID) .append(" FROM ").append(DBTableName.SERVER) .append(" WHERE ").append(DBTableColName.SERVER.EUCA_ZONE) .append(" = '").append(zone).append("'"); try { ResultSet r = DBProcWrapper.Instance().query(sb.toString()).getResultSet(); if (r.first()) { return r.getInt(DBTableColName.SERVER.ID); } } catch (SQLException e) { LOG.error("sql error in getServerID: " + e.toString()); } return -1; } public String getServerIp(int userID, String instanceID) throws EucalyptusServiceException { return aws.lookupInstanceForIp(userID, instanceID); } public List<IPServiceInfo> getIPServices(int accountID, int userID) throws EucalyptusServiceException { List<Integer> ids = new ArrayList<Integer>(); if (userID > 0) { ids.add(userID); } else { StringBuilder sb = new StringBuilder(); sb.append("SELECT ").append(DBTableColName.USER.ID).append(" FROM ") .append(DBTableName.USER); if (accountID > 0) { sb.append(" WHERE ").append(DBTableColName.USER.ACCOUNT_ID).append(" = '") .append(accountID).append("'"); } try { ResultSet r = DBProcWrapper.Instance().query(sb.toString()).getResultSet(); while (r.next()) { ids.add(r.getInt(DBTableColName.USER.ID)); } } catch (Exception e) { throw new EucalyptusServiceException("db error"); } } LOG.debug("ip service: user ids = " + ids.toString()); List<IPServiceInfo> ret = new ArrayList<IPServiceInfo>(); List<Address> addrs = aws.lookupPublicAddress(ids.get(0)); for (Address a : addrs) { String id = a.getInstanceId(); + int _userID = aws.getUserID(id); if (id.startsWith("nobody") || false) { //!ids.contains(aws.getUserID(id))) { continue; } IPServiceInfo e = new IPServiceInfo(); e.ip_addr = a.getPublicIp(); if (id.startsWith("available")) { e.is_state = IPState.RESERVED; } else { e.is_state = IPState.INUSE; IPServiceInfo _e = new IPServiceInfo(); String _id = id.substring(0, id.indexOf(' ')); e.ip_id = getIPID(_id, IPType.PUBLIC); - String _ip = getServerIp(userID, _id); + String _ip = getServerIp(_userID, _id); _e.is_state = IPState.INUSE; _e.ip_type = IPType.PRIVATE; _e.ip_addr = _ip; _e.ip_id = getIPID(_id, IPType.PRIVATE); ret.add(_e); } e.ip_type = IPType.PUBLIC; ret.add(e); } return ret; } public int getIPID(String instanceID, IPType t) throws EucalyptusServiceException{ StringBuilder sb = new StringBuilder(); sb.append("SELECT "); String col = null; if (t == IPType.PRIVATE) col = DBTableColName.USER_APP.PRI_IP_SRV_ID; else col = DBTableColName.USER_APP.PUB_IP_SRV_ID; sb.append(col); sb.append(" FROM ").append(DBTableName.USER_APP) .append(" WHERE ").append(DBTableColName.USER_APP.EUCA_VI_KEY).append(" = '") .append(instanceID).append("'"); try { ResultSet r = DBProcWrapper.Instance().query(sb.toString()).getResultSet(); if (r.first()) return r.getInt(col); } catch (Exception e) { throw new EucalyptusServiceException("db error"); } return 0; } public List<String> allocateAddress(int userID, IPType type, int count) throws EucalyptusServiceException { return aws.allocateAddress(userID, type, count); } public void releaseAddress(int userID, IPType type, String addr) throws EucalyptusServiceException { aws.releaseAddress(userID, type, addr); } }
false
true
public List<IPServiceInfo> getIPServices(int accountID, int userID) throws EucalyptusServiceException { List<Integer> ids = new ArrayList<Integer>(); if (userID > 0) { ids.add(userID); } else { StringBuilder sb = new StringBuilder(); sb.append("SELECT ").append(DBTableColName.USER.ID).append(" FROM ") .append(DBTableName.USER); if (accountID > 0) { sb.append(" WHERE ").append(DBTableColName.USER.ACCOUNT_ID).append(" = '") .append(accountID).append("'"); } try { ResultSet r = DBProcWrapper.Instance().query(sb.toString()).getResultSet(); while (r.next()) { ids.add(r.getInt(DBTableColName.USER.ID)); } } catch (Exception e) { throw new EucalyptusServiceException("db error"); } } LOG.debug("ip service: user ids = " + ids.toString()); List<IPServiceInfo> ret = new ArrayList<IPServiceInfo>(); List<Address> addrs = aws.lookupPublicAddress(ids.get(0)); for (Address a : addrs) { String id = a.getInstanceId(); if (id.startsWith("nobody") || false) { //!ids.contains(aws.getUserID(id))) { continue; } IPServiceInfo e = new IPServiceInfo(); e.ip_addr = a.getPublicIp(); if (id.startsWith("available")) { e.is_state = IPState.RESERVED; } else { e.is_state = IPState.INUSE; IPServiceInfo _e = new IPServiceInfo(); String _id = id.substring(0, id.indexOf(' ')); e.ip_id = getIPID(_id, IPType.PUBLIC); String _ip = getServerIp(userID, _id); _e.is_state = IPState.INUSE; _e.ip_type = IPType.PRIVATE; _e.ip_addr = _ip; _e.ip_id = getIPID(_id, IPType.PRIVATE); ret.add(_e); } e.ip_type = IPType.PUBLIC; ret.add(e); } return ret; }
public List<IPServiceInfo> getIPServices(int accountID, int userID) throws EucalyptusServiceException { List<Integer> ids = new ArrayList<Integer>(); if (userID > 0) { ids.add(userID); } else { StringBuilder sb = new StringBuilder(); sb.append("SELECT ").append(DBTableColName.USER.ID).append(" FROM ") .append(DBTableName.USER); if (accountID > 0) { sb.append(" WHERE ").append(DBTableColName.USER.ACCOUNT_ID).append(" = '") .append(accountID).append("'"); } try { ResultSet r = DBProcWrapper.Instance().query(sb.toString()).getResultSet(); while (r.next()) { ids.add(r.getInt(DBTableColName.USER.ID)); } } catch (Exception e) { throw new EucalyptusServiceException("db error"); } } LOG.debug("ip service: user ids = " + ids.toString()); List<IPServiceInfo> ret = new ArrayList<IPServiceInfo>(); List<Address> addrs = aws.lookupPublicAddress(ids.get(0)); for (Address a : addrs) { String id = a.getInstanceId(); int _userID = aws.getUserID(id); if (id.startsWith("nobody") || false) { //!ids.contains(aws.getUserID(id))) { continue; } IPServiceInfo e = new IPServiceInfo(); e.ip_addr = a.getPublicIp(); if (id.startsWith("available")) { e.is_state = IPState.RESERVED; } else { e.is_state = IPState.INUSE; IPServiceInfo _e = new IPServiceInfo(); String _id = id.substring(0, id.indexOf(' ')); e.ip_id = getIPID(_id, IPType.PUBLIC); String _ip = getServerIp(_userID, _id); _e.is_state = IPState.INUSE; _e.ip_type = IPType.PRIVATE; _e.ip_addr = _ip; _e.ip_id = getIPID(_id, IPType.PRIVATE); ret.add(_e); } e.ip_type = IPType.PUBLIC; ret.add(e); } return ret; }
diff --git a/stepsovc-commcare-api/src/test/java/integration/org/wv/stepsovc/commcare/gateway/CommcareGatewayIT.java b/stepsovc-commcare-api/src/test/java/integration/org/wv/stepsovc/commcare/gateway/CommcareGatewayIT.java index 379203b..b4d9c47 100644 --- a/stepsovc-commcare-api/src/test/java/integration/org/wv/stepsovc/commcare/gateway/CommcareGatewayIT.java +++ b/stepsovc-commcare-api/src/test/java/integration/org/wv/stepsovc/commcare/gateway/CommcareGatewayIT.java @@ -1,224 +1,224 @@ package org.wv.stepsovc.commcare.gateway; import junit.framework.Assert; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.wv.stepsovc.commcare.domain.CaseType; import org.wv.stepsovc.commcare.domain.User; import org.wv.stepsovc.commcare.factories.GroupFactory; import org.wv.stepsovc.commcare.repository.AllGroups; import org.wv.stepsovc.commcare.repository.AllUsers; import org.wv.stepsovc.commcare.vo.BeneficiaryInformation; import org.wv.stepsovc.commcare.vo.CareGiverInformation; import java.util.HashMap; import java.util.UUID; import static junit.framework.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.wv.stepsovc.commcare.gateway.CommcareGateway.*; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath*:applicationContext-stepsovc-commcare-api.xml") public class CommcareGatewayIT { @Autowired CommcareGateway commcareGateway; @Autowired AllGroups allGroups; @Autowired AllUsers allUsers; private User newUser1; private User newUser2; private String userId1; private String userId2; private String groupName = "group1"; @Ignore public void shouldCreateNewBeneficiary() throws Exception { BeneficiaryInformation beneficiaryInformation = getBeneficiaryInformation("7ac0b33f0dac4a81c6d1fbf1bd9dfee0", "ggg2", UUID.randomUUID().toString(), "new-test-case-6", "new-test-case-6", "cg1", null); commcareGateway.createNewBeneficiary(beneficiaryInformation); } - @Ignore + @Test public void shouldRegisterNewCareGiverUser() throws InterruptedException { String testCareGiverName = "testCareGiverName"; CareGiverInformation careGiverInformation = new CareGiverInformation(); careGiverInformation.setId("testCareGiverId"); careGiverInformation.setCode("testCareGiverCode"); careGiverInformation.setName(testCareGiverName); careGiverInformation.setPassword("12345"); careGiverInformation.setPhoneNumber("1234567890"); assertNull(allUsers.getUserByName(testCareGiverName)); commcareGateway.registerUser(careGiverInformation); Thread.sleep(2000); User newCareGiver = allUsers.get("testCareGiverId"); assertNotNull(newCareGiver); allUsers.remove(newCareGiver); } @Test public void shouldConvertObjectToXml() { BeneficiaryInformation beneficiaryInformation = getBeneficiaryInformation("f98589102c60fcc2e0f3c422bb361ebd", "cg1", "c7264b49-4e3d-4659-8df3-7316539829cb", "test-case", "XYZ/123", "cg1", "hw1"); assertConversion(CommcareGateway.BENEFICIARY_FORM_KEY, beneficiaryInformation, BENEFICIARY_CASE_FORM_TEMPLATE_PATH, getExpectedBeneficiaryCaseXml()); assertConversion(CommcareGateway.BENEFICIARY_FORM_KEY, beneficiaryInformation, OWNER_UPDATE_FORM_TEMPLATE_PATH, getExpectedUpdateOwnerXml()); CareGiverInformation careGiverInformation = getCareGiverInformation("7ac0b33f0dac4a81c6d1fbf1bd9dfee0", "EW/123", "cg1", "9089091"); assertConversion(CommcareGateway.CARE_GIVER_FORM_KEY, careGiverInformation, USER_REGISTRATION_FORM_TEMPLATE_PATH, getExpectedUserFormXml()); } @Test public void shouldCreateGroupWithUsers() { newUser1 = createUser("newUser1"); newUser2 = createUser("newUser2"); allUsers.add(newUser1); allUsers.add(newUser2); userId1 = allUsers.getUserByName(newUser1.getUsername()).getId(); userId2 = allUsers.getUserByName(newUser2.getUsername()).getId(); String domainName = "stepsovc"; allGroups.add(GroupFactory.createGroup(groupName, new String[]{userId1, userId2}, domainName)); Assert.assertNotNull(allGroups.getGroupByName(groupName)); allGroups.removeByName(groupName); allUsers.removeByName(newUser1.getUsername()); allUsers.removeByName(newUser2.getUsername()); } private User createUser(String userName) { User newUser = new User(); newUser.setBase_doc("CouchUser"); newUser.setDomain("stepsovc"); newUser.setUsername(userName); return newUser; } private void assertConversion(String key, Object entity, String formPath, String expectedXML) { HashMap<String, Object> model = new HashMap<String, Object>(); model.put(key, entity); String actualXML = commcareGateway.getXmlFromObject(formPath, model); assertEquals(expectedXML, actualXML); } private String getExpectedUserFormXml() { return "<Registration xmlns=\"http://openrosa.org/user/registration\">\n" + "\n" + " <username>EW/123</username>\n" + " <password>sha1$90a7b$47a168cca627c6a34f4e349ea4b1fb3d01702c68</password>\n" + " <uuid>7ac0b33f0dac4a81c6d1fbf1bd9dfee0</uuid>\n" + " <date>01-01-2012</date>\n" + "\n" + " <registering_phone_id>9089091</registering_phone_id>\n" + "\n" + " <user_data type=\"hash\">\n" + " <name>cg1</name>\n" + " </user_data>\n" + "</Registration>"; } private CareGiverInformation getCareGiverInformation(String cgId, String cgCode, String cgName, String phoneNumber) { CareGiverInformation careGiverInformation = new CareGiverInformation(); careGiverInformation.setId(cgId); careGiverInformation.setCode(cgCode); careGiverInformation.setName(cgName); careGiverInformation.setPhoneNumber(phoneNumber); return careGiverInformation; } private BeneficiaryInformation getBeneficiaryInformation(String caregiverId, String caregiverCode, String caseId, String caseName, String beneficiaryCode, String caregiverName, String ownerId) { BeneficiaryInformation beneficiaryInformation = new BeneficiaryInformation(); beneficiaryInformation.setBeneficiaryId(caseId); beneficiaryInformation.setBeneficiaryCode(beneficiaryCode); beneficiaryInformation.setBeneficiaryName(caseName); beneficiaryInformation.setBeneficiaryDob("12-12-1988"); beneficiaryInformation.setBeneficiarySex("male"); beneficiaryInformation.setBeneficiaryTitle("MR"); beneficiaryInformation.setReceivingOrganization("XAQ"); beneficiaryInformation.setCareGiverCode(caregiverCode); beneficiaryInformation.setCareGiverId(caregiverId); beneficiaryInformation.setCareGiverName(caregiverName); beneficiaryInformation.setCaseType(CaseType.BENEFICIARY_CASE.getType()); beneficiaryInformation.setDateModified("2012-05-02T22:18:45.071+05:30"); beneficiaryInformation.setOwnerId(ownerId); return beneficiaryInformation; } private String getExpectedBeneficiaryCaseXml() { return "<?xml version=\"1.0\"?>\n" + "<data xmlns=\"http://openrosa.org/formdesigner/A6E4F029-A971-41F1-80C1-9DDD5CC24571\" uiVersion=\"1\" version=\"12\"\n" + " name=\"Registration\">\n" + " <beneficiary_information>\n" + " <beneficiary_name>test-case</beneficiary_name>\n" + " <beneficiary_code>XYZ/123</beneficiary_code>\n" + " <beneficiary_dob>12-12-1988</beneficiary_dob>\n" + " <receiving_organization>XAQ</receiving_organization>\n" + " <sex>male</sex>\n" + " <title>MR</title>\n" + " </beneficiary_information>\n" + " <caregiver_information>\n" + " <caregiver_code>cg1</caregiver_code>\n" + " <caregiver_name>cg1</caregiver_name>\n" + " </caregiver_information>\n" + " <form_type>beneficiary_registration</form_type>\n" + " <case>\n" + " <case_id>c7264b49-4e3d-4659-8df3-7316539829cb</case_id>\n" + " <date_modified>2012-05-02T22:18:45.071+05:30</date_modified>\n" + " <create>\n" + " <case_type_id>beneficiary</case_type_id>\n" + " <case_name>XYZ/123</case_name>\n" + " <user_id>f98589102c60fcc2e0f3c422bb361ebd</user_id>\n" + " <external_id>XYZ/123</external_id>\n" + " </create>\n" + " <update>\n" + " <beneficiary_dob>12-12-1988</beneficiary_dob>\n" + " <title>MR</title>\n" + " <beneficiary_name>test-case</beneficiary_name>\n" + " <receiving_organization>XAQ</receiving_organization>\n" + " <caregiver_name>cg1</caregiver_name>\n" + " <sex>male</sex>\n" + " <form_type>beneficiary_registration</form_type>\n" + " <beneficiary_code>XYZ/123</beneficiary_code>\n" + " <caregiver_code>cg1</caregiver_code>\n" + " </update>\n" + " </case>\n" + " <meta>\n" + " <username>cg1</username>\n" + " <userID>f98589102c60fcc2e0f3c422bb361ebd</userID>\n" + " </meta>\n" + "</data>"; } private String getExpectedUpdateOwnerXml() { return "<?xml version='1.0' ?>\n" + "<data uiVersion=\"1\" version=\"89\" name=\"update\"\n" + " xmlns=\"http://openrosa.org/formdesigner/E45F3EFD-A7BE-42A6-97C2-5133E766A2AA\">\n" + " <owner_id>hw1</owner_id>\n" + " <form_type>custom_update</form_type>\n" + " <case>\n" + " <case_id>c7264b49-4e3d-4659-8df3-7316539829cb</case_id>\n" + " <date_modified>2012-05-02T22:18:45.071+05:30</date_modified>\n" + " <update>\n" + " <form_type>custom_update</form_type>\n" + " <owner_id>hw1</owner_id>\n" + " </update>\n" + " </case>\n" + " <meta>\n" + " <username>cg1</username>\n" + " <userID>f98589102c60fcc2e0f3c422bb361ebd</userID>\n" + " </meta>\n" + "</data>"; } } \ No newline at end of file
true
false
null
null
diff --git a/engine/src/core/com/jme3/texture/Texture.java b/engine/src/core/com/jme3/texture/Texture.java index 5452262c6..f6bf17a0f 100644 --- a/engine/src/core/com/jme3/texture/Texture.java +++ b/engine/src/core/com/jme3/texture/Texture.java @@ -1,614 +1,614 @@ /* * Copyright (c) 2009-2010 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.jme3.texture; import com.jme3.asset.Asset; import com.jme3.asset.AssetKey; import com.jme3.asset.TextureKey; import com.jme3.export.JmeExporter; import com.jme3.export.JmeImporter; import com.jme3.export.InputCapsule; import com.jme3.export.OutputCapsule; import com.jme3.export.Savable; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; /** * <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. + * Modulate, environment - None. * * @see com.jme3.texture.Image * @author Mark Powell * @author Joshua Slack * @version $Id: Texture.java 4131 2009-03-19 20:15:28Z blaine.dev $ */ public abstract class Texture implements Asset, Savable, Cloneable { public enum Type { /** * Two dimensional texture (default). A rectangle. */ TwoDimensional, /** * An array of two dimensional textures. */ TwoDimensionalArray, /** * Three dimensional texture. (A cube) */ ThreeDimensional, /** * A set of 6 TwoDimensional textures arranged as faces of a cube facing * inwards. */ CubeMap; } public enum MinFilter { /** * 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) */ NearestNoMipMaps(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) */ NearestNearestMipMap(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) */ NearestLinearMipMap(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 MinFilter(boolean usesMipMapLevels) { this.usesMipMapLevels = usesMipMapLevels; } public boolean usesMipMapLevels() { return usesMipMapLevels; } } public enum MagFilter { /** * 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) */ Nearest, /** * 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; } /** * If this texture is a depth texture (the format is Depth*) then * this value may be used to compare the texture depth to the R texture * coordinate. */ public enum ShadowCompareMode { /** * Shadow comparison mode is disabled. * Texturing is done normally. */ Off, /** * Compares the 3rd texture coordinate R to the value * in this depth texture. If R <= texture value then result is 1.0, * otherwise, result is 0.0. If filtering is set to bilinear or trilinear * the implementation may sample the texture multiple times to provide * smoother results in the range [0, 1]. */ LessOrEqual, /** * Compares the 3rd texture coordinate R to the value * in this depth texture. If R >= texture value then result is 1.0, * otherwise, result is 0.0. If filtering is set to bilinear or trilinear * the implementation may sample the texture multiple times to provide * smoother results in the range [0, 1]. */ GreaterOrEqual } /** * The name of the texture (if loaded as a resource). */ private String name = null; /** * The image stored in the texture */ private Image image = null; /** * The texture key allows to reload a texture from a file * if needed. */ private TextureKey key = null; private MinFilter minificationFilter = MinFilter.BilinearNoMipMaps; private MagFilter magnificationFilter = MagFilter.Bilinear; private ShadowCompareMode shadowCompareMode = ShadowCompareMode.Off; private int anisotropicFilter; /** * @return */ @Override public Texture clone(){ try { return (Texture) super.clone(); } catch (CloneNotSupportedException ex) { throw new AssertionError(); } } /** * Constructor instantiates a new <code>Texture</code> object with default * attributes. */ public Texture() { } /** * @return the MinificationFilterMode of this texture. */ public MinFilter getMinFilter() { return minificationFilter; } /** * @param minificationFilter * the new MinificationFilterMode for this texture. * @throws IllegalArgumentException * if minificationFilter is null */ public void setMinFilter(MinFilter minificationFilter) { if (minificationFilter == null) { throw new IllegalArgumentException( "minificationFilter can not be null."); } this.minificationFilter = minificationFilter; } /** * @return the MagnificationFilterMode of this texture. */ public MagFilter getMagFilter() { return magnificationFilter; } /** * @param magnificationFilter * the new MagnificationFilter for this texture. * @throws IllegalArgumentException * if magnificationFilter is null */ public void setMagFilter(MagFilter magnificationFilter) { if (magnificationFilter == null) { throw new IllegalArgumentException( "magnificationFilter can not be null."); } this.magnificationFilter = magnificationFilter; } /** * @return The ShadowCompareMode of this texture. * @see ShadowCompareMode */ public ShadowCompareMode getShadowCompareMode(){ return shadowCompareMode; } /** * @param compareMode * the new ShadowCompareMode for this texture. * @throws IllegalArgumentException * if compareMode is null * @see ShadowCompareMode */ public void setShadowCompareMode(ShadowCompareMode compareMode){ if (compareMode == null){ throw new IllegalArgumentException( "compareMode can not be null."); } this.shadowCompareMode = compareMode; } /** * <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; } /** * @param key The texture key that was used to load this texture */ public void setKey(AssetKey key){ this.key = (TextureKey) key; } public AssetKey getKey(){ return this.key; } /** * <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>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(); public String getName() { return name; } public void setName(String name) { this.name = name; } /** * @return the anisotropic filtering level for this texture. Default value * is 1 (no anisotrophy), 2 means x2, 4 is x4, etc. */ public int getAnisotropicFilter() { return anisotropicFilter; } /** * @param level * the anisotropic filtering level for this texture. */ public void setAnisotropicFilter(int level) { if (level < 1) anisotropicFilter = 1; else anisotropicFilter = level; } @Override public String toString(){ StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append("[name=").append(name); if (image != null) sb.append(", image=").append(image.toString()); sb.append("]"); return sb.toString(); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Texture other = (Texture) obj; if (this.image != other.image && (this.image == null || !this.image.equals(other.image))) { return false; } if (this.minificationFilter != other.minificationFilter) { return false; } if (this.magnificationFilter != other.magnificationFilter) { return false; } if (this.shadowCompareMode != other.shadowCompareMode) { return false; } if (this.anisotropicFilter != other.anisotropicFilter) { return false; } return true; } @Override public int hashCode() { int hash = 5; hash = 67 * hash + (this.image != null ? this.image.hashCode() : 0); hash = 67 * hash + (this.minificationFilter != null ? this.minificationFilter.hashCode() : 0); hash = 67 * hash + (this.magnificationFilter != null ? this.magnificationFilter.hashCode() : 0); hash = 67 * hash + (this.shadowCompareMode != null ? this.shadowCompareMode.hashCode() : 0); hash = 67 * hash + this.anisotropicFilter; return hash; } // public abstract Texture createSimpleClone(); - /** Retreive a basic clone of this Texture (ie, clone everything but the + /** Retrieve a basic clone of this Texture (ie, clone everything but the * image data, which is shared) * * @return Texture */ public Texture createSimpleClone(Texture rVal) { rVal.setMinFilter(minificationFilter); rVal.setMagFilter(magnificationFilter); rVal.setShadowCompareMode(shadowCompareMode); // rVal.setHasBorder(hasBorder); rVal.setAnisotropicFilter(anisotropicFilter); rVal.setImage(image); // NOT CLONED. // rVal.memReq = memReq; rVal.setKey(key); rVal.setName(name); // rVal.setBlendColor(blendColor != null ? blendColor.clone() : null); // if (getTextureKey() != null) { // rVal.setTextureKey(getTextureKey()); // } return rVal; } public abstract Texture createSimpleClone(); public void write(JmeExporter e) throws IOException { OutputCapsule capsule = e.getCapsule(this); capsule.write(name, "name", null); if (key == null){ // no texture key is set, try to save image instead then capsule.write(image, "image", null); }else{ capsule.write(key, "key", null); } capsule.write(anisotropicFilter, "anisotropicFilter", 1); capsule.write(minificationFilter, "minificationFilter", MinFilter.BilinearNoMipMaps); capsule.write(magnificationFilter, "magnificationFilter", MagFilter.Bilinear); } public void read(JmeImporter e) throws IOException { InputCapsule capsule = e.getCapsule(this); name = capsule.readString("name", null); key = (TextureKey) capsule.readSavable("key", null); // load texture from key, if available if (key != null) { // key is available, so try the texture from there. Texture loadedTex = e.getAssetManager().loadTexture(key); if (loadedTex == null) { Logger.getLogger(Texture.class.getName()).log(Level.SEVERE, "Could not load texture: {0}", key.toString()); } else { image = loadedTex.getImage(); } }else{ // no key is set on the texture. Attempt to load an embedded image image = (Image) capsule.readSavable("image", null); if (image == null){ // TODO: what to print out here? the texture has no key or data, there's no useful information .. // assume texture.name is set even though the key is null Logger.getLogger(Texture.class.getName()).log(Level.SEVERE, "Could not load embedded image: {0}", toString() ); } } anisotropicFilter = capsule.readInt("anisotropicFilter", 1); minificationFilter = capsule.readEnum("minificationFilter", MinFilter.class, MinFilter.BilinearNoMipMaps); magnificationFilter = capsule.readEnum("magnificationFilter", MagFilter.class, MagFilter.Bilinear); } } \ No newline at end of file
false
false
null
null
diff --git a/org.eclipse.mylyn.discovery.ui/src/org/eclipse/mylyn/internal/discovery/ui/wizards/InstallConnectorsJob.java b/org.eclipse.mylyn.discovery.ui/src/org/eclipse/mylyn/internal/discovery/ui/wizards/InstallConnectorsJob.java index 84dce915..ba68c264 100644 --- a/org.eclipse.mylyn.discovery.ui/src/org/eclipse/mylyn/internal/discovery/ui/wizards/InstallConnectorsJob.java +++ b/org.eclipse.mylyn.discovery.ui/src/org/eclipse/mylyn/internal/discovery/ui/wizards/InstallConnectorsJob.java @@ -1,290 +1,301 @@ /******************************************************************************* * Copyright (c) 2009 Tasktop Technologies 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: * Tasktop Technologies - initial API and implementation *******************************************************************************/ package org.eclipse.mylyn.internal.discovery.ui.wizards; import java.lang.reflect.InvocationTargetException; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.equinox.internal.provisional.p2.core.Version; import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; import org.eclipse.equinox.internal.provisional.p2.engine.IProfileRegistry; import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; import org.eclipse.equinox.internal.provisional.p2.metadata.IProvidedCapability; import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; import org.eclipse.equinox.internal.provisional.p2.query.Collector; import org.eclipse.equinox.internal.provisional.p2.query.MatchQuery; import org.eclipse.equinox.internal.provisional.p2.query.Query; import org.eclipse.equinox.internal.provisional.p2.ui.actions.InstallAction; import org.eclipse.equinox.internal.provisional.p2.ui.operations.ProvisioningUtil; import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; import org.eclipse.jface.action.IAction; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.mylyn.internal.discovery.core.model.ConnectorDescriptor; import org.eclipse.mylyn.internal.discovery.ui.DiscoveryUi; import org.eclipse.mylyn.internal.discovery.ui.util.SimpleSelectionProvider; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.PlatformUI; import com.ibm.icu.text.MessageFormat; /** * A job that downloads and installs one or more {@link ConnectorDescriptor connectors}. The bulk of the installation * work is done by p2; this class just sets up the p2 repository metadata and selects the appropriate features to * install. * * @author David Green */ @SuppressWarnings("restriction") public class InstallConnectorsJob implements IRunnableWithProgress { private static final String P2_FEATURE_GROUP_SUFFIX = ".feature.group"; //$NON-NLS-1$ private final List<ConnectorDescriptor> installableConnectors; public InstallConnectorsJob(List<ConnectorDescriptor> installableConnectors) { if (installableConnectors == null || installableConnectors.isEmpty()) { throw new IllegalArgumentException(); } this.installableConnectors = new ArrayList<ConnectorDescriptor>(installableConnectors); } public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { doRun(monitor); if (monitor.isCanceled()) { throw new InterruptedException(); } } catch (Exception e) { throw new InvocationTargetException(e); } } public void doRun(IProgressMonitor monitor) throws CoreException { try { final int totalWork = installableConnectors.size() * 4; monitor.beginTask(Messages.InstallConnectorsJob_task_configuring, totalWork); final String profileId = computeProfileId(); // Tell p2 that it's okay to use these repositories Set<URL> repositoryURLs = new HashSet<URL>(); for (ConnectorDescriptor descriptor : installableConnectors) { URL url = new URL(descriptor.getSiteUrl()); if (repositoryURLs.add(url)) { if (monitor.isCanceled()) { return; } ProvisioningUtil.addMetadataRepository(url.toURI(), true); ProvisioningUtil.addArtifactRepository(url.toURI(), true); ProvisioningUtil.setColocatedRepositoryEnablement(url.toURI(), true); } monitor.worked(1); } if (repositoryURLs.isEmpty()) { // should never happen throw new IllegalStateException(); } // Fetch p2's metadata for these repositories List<IMetadataRepository> repositories = new ArrayList<IMetadataRepository>(); final Map<IMetadataRepository, URL> repositoryToURL = new HashMap<IMetadataRepository, URL>(); { int unit = installableConnectors.size() / repositoryURLs.size(); for (URL updateSiteUrl : repositoryURLs) { if (monitor.isCanceled()) { return; } IMetadataRepository repository = ProvisioningUtil.loadMetadataRepository(updateSiteUrl.toURI(), new SubProgressMonitor(monitor, unit)); repositories.add(repository); repositoryToURL.put(repository, updateSiteUrl); } } // Perform a query to get the installable units. This causes p2 to determine what features are available // in each repository. We select installable units by matching both the feature id and the repository; it // is possible though unlikely that the same feature id is available from more than one of the selected // repositories, and we must ensure that the user gets the one that they asked for. final List<IInstallableUnit> installableUnits = new ArrayList<IInstallableUnit>(); { int unit = installableConnectors.size() / repositories.size(); for (final IMetadataRepository repository : repositories) { if (monitor.isCanceled()) { return; } URL repositoryUrl = repositoryToURL.get(repository); final Set<String> installableUnitIdsThisRepository = new HashSet<String>(); // determine all installable units for this repository for (ConnectorDescriptor descriptor : installableConnectors) { try { if (repositoryUrl.equals(new URL(descriptor.getSiteUrl()))) { installableUnitIdsThisRepository.add(descriptor.getId()); } } catch (MalformedURLException e) { // will never happen, ignore } } Collector collector = new Collector(); Query query = new MatchQuery() { @Override public boolean isMatch(Object object) { if (!(object instanceof IInstallableUnit)) { return false; } IInstallableUnit candidate = (IInstallableUnit) object; if ("true".equalsIgnoreCase(candidate.getProperty("org.eclipse.equinox.p2.type.group"))) { //$NON-NLS-1$ //$NON-NLS-2$ - IProvidedCapability[] providedCapabilities = candidate.getProvidedCapabilities(); - if (providedCapabilities != null && providedCapabilities.length == 1) { - if ("org.eclipse.equinox.p2.iu".equals(providedCapabilities[0].getNamespace())) { //$NON-NLS-1$ - String name = providedCapabilities[0].getName(); - if (name.endsWith(P2_FEATURE_GROUP_SUFFIX)) { - String featureId = name.substring(0, name.indexOf(P2_FEATURE_GROUP_SUFFIX)); - return installableUnitIdsThisRepository.contains(featureId); + String id = candidate.getId(); + if (isQualifyingFeature(installableUnitIdsThisRepository, id)) { + IProvidedCapability[] providedCapabilities = candidate.getProvidedCapabilities(); + if (providedCapabilities != null && providedCapabilities.length > 0) { + for (IProvidedCapability capability : providedCapabilities) { + if ("org.eclipse.equinox.p2.iu".equals(capability.getNamespace())) { //$NON-NLS-1$ + String name = capability.getName(); + if (isQualifyingFeature(installableUnitIdsThisRepository, name)) { + return true; + } + } } } } } return false; } + + private boolean isQualifyingFeature(final Set<String> installableUnitIdsThisRepository, + String id) { + return id.endsWith(P2_FEATURE_GROUP_SUFFIX) + && installableUnitIdsThisRepository.contains(id.substring(0, + id.indexOf(P2_FEATURE_GROUP_SUFFIX))); + } }; repository.query(query, collector, new SubProgressMonitor(monitor, unit)); addAll(installableUnits, collector); } } // filter those installable units that have a duplicate in the list with a higher version number. // it's possible that some repositories will host multiple versions of a particular feature. we assume // that the user wants the highest version. { Map<String, Version> symbolicNameToVersion = new HashMap<String, Version>(); for (IInstallableUnit unit : installableUnits) { Version version = symbolicNameToVersion.get(unit.getId()); if (version == null || version.compareTo(unit.getVersion()) == -1) { symbolicNameToVersion.put(unit.getId(), unit.getVersion()); } } if (symbolicNameToVersion.size() != installableUnits.size()) { for (IInstallableUnit unit : new ArrayList<IInstallableUnit>(installableUnits)) { Version version = symbolicNameToVersion.get(unit.getId()); if (!version.equals(unit.getVersion())) { installableUnits.remove(unit); } } } } // Verify that we found what we were looking for: it's possible that we have connector descriptors // that are no longer available on their respective sites. In that case we must inform the user. // (Unfortunately this is the earliest point at which we can know) if (installableUnits.size() < installableConnectors.size()) { // at least one selected connector could not be found in a repository Set<String> foundIds = new HashSet<String>(); for (IInstallableUnit unit : installableUnits) { String id = unit.getId(); if (id.endsWith(P2_FEATURE_GROUP_SUFFIX)) { id = id.substring(0, id.indexOf(P2_FEATURE_GROUP_SUFFIX)); } foundIds.add(id); } final String notFound; { String temp = ""; //$NON-NLS-1$ for (ConnectorDescriptor descriptor : installableConnectors) { if (!foundIds.contains(descriptor.getId())) { if (temp.length() > 0) { temp += Messages.InstallConnectorsJob_commaSeparator; } temp += descriptor.getName(); } } notFound = temp; } boolean proceed = false; if (!installableUnits.isEmpty()) { // instead of aborting here we ask the user if they wish to proceed anyways final boolean[] okayToProceed = new boolean[1]; Display.getDefault().syncExec(new Runnable() { public void run() { okayToProceed[0] = MessageDialog.openQuestion(PlatformUI.getWorkbench() .getActiveWorkbenchWindow() .getShell(), Messages.InstallConnectorsJob_questionProceed, MessageFormat.format( Messages.InstallConnectorsJob_questionProceed_long, new Object[] { notFound })); } }); proceed = okayToProceed[0]; } if (!proceed) { throw new CoreException(new Status(IStatus.ERROR, DiscoveryUi.BUNDLE_ID, MessageFormat.format( Messages.InstallConnectorsJob_connectorsNotAvailable, new Object[] { notFound }), null)); } } else if (installableUnits.size() > installableConnectors.size()) { // should never ever happen throw new IllegalStateException(); } // now that we've got what we want, do the install Display.getDefault().asyncExec(new Runnable() { public void run() { IAction installAction = new InstallAction(Policy.getDefault(), new SimpleSelectionProvider( new StructuredSelection(installableUnits)), profileId); installAction.run(); } }); monitor.done(); } catch (URISyntaxException e) { // should never happen, since we already validated URLs. throw new CoreException(new Status(IStatus.ERROR, DiscoveryUi.BUNDLE_ID, Messages.InstallConnectorsJob_unexpectedError_url, e)); } catch (MalformedURLException e) { // should never happen, since we already validated URLs. throw new CoreException(new Status(IStatus.ERROR, DiscoveryUi.BUNDLE_ID, Messages.InstallConnectorsJob_unexpectedError_url, e)); } } @SuppressWarnings("unchecked") private boolean addAll(final List<IInstallableUnit> installableUnits, Collector collector) { return installableUnits.addAll(collector.toCollection()); } private String computeProfileId() throws CoreException { IProfile profile = ProvisioningUtil.getProfile(IProfileRegistry.SELF); if (profile != null) { return profile.getProfileId(); } IProfile[] profiles = ProvisioningUtil.getProfiles(); if (profiles.length > 0) { return profiles[0].getProfileId(); } throw new CoreException(new Status(IStatus.ERROR, DiscoveryUi.BUNDLE_ID, Messages.InstallConnectorsJob_profileProblem, null)); } }
false
false
null
null
diff --git a/org.dawb.common.ui/src/org/dawb/common/ui/plot/tools/IDataReductionToolPage.java b/org.dawb.common.ui/src/org/dawb/common/ui/plot/tools/IDataReductionToolPage.java index 4fe92e31..6cb42ba0 100644 --- a/org.dawb.common.ui/src/org/dawb/common/ui/plot/tools/IDataReductionToolPage.java +++ b/org.dawb.common.ui/src/org/dawb/common/ui/plot/tools/IDataReductionToolPage.java @@ -1,220 +1,220 @@ package org.dawb.common.ui.plot.tools; import java.util.List; import ncsa.hdf.object.Group; +import org.dawb.gda.extensions.loaders.H5Utils; import org.dawb.hdf5.IHierarchicalDataFile; import org.dawnsci.plotting.api.tool.IToolPage; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import uk.ac.diamond.scisoft.analysis.dataset.AbstractDataset; -import uk.ac.diamond.scisoft.analysis.io.h5.H5Utils; /** * Interface used to define this tool as a data reduction tool. * * Data Reduction tools generally reduce data from nD to (n-1)D, * for instance radial integration of an image (2d) to 1d. They can also be applied * n+1 data dimensions using the @see DataReductionWizard * * @author fcp94556 * */ public interface IDataReductionToolPage extends IToolPage { /** * Export the tool results to an hdf5 file under the passed in group. * * This method is used to run the tool multiple times on different slices of the data. * * This method will not be called on the UI thread in most instances. * * @param bean */ public DataReductionInfo export(DataReductionSlice bean) throws Exception; /** * Bean to contain data for slice of tool. * @author fcp94556 * */ public final class DataReductionSlice { /** * The file we are writing to. */ private IHierarchicalDataFile file; /** * The Group which the user chose. */ private Group parent; /** * The actual sliced data to operate on. */ private AbstractDataset data; /** * May be null, 0 = x, 1 = y. Y may be omitted, in which case use indexes */ private List<AbstractDataset> axes; /** * May be null, data which the tool may need for persistence. */ private Object userData; private IProgressMonitor monitor; public DataReductionSlice(IHierarchicalDataFile hf, Group group, AbstractDataset set, Object ud, IProgressMonitor mon) { this.file = hf; this.parent = group; this.data = set; this.userData= ud; this.monitor = mon; } public IHierarchicalDataFile getFile() { return file; } public void setFile(IHierarchicalDataFile hf) { this.file = hf; } public Group getParent() { return parent; } public void setParent(Group parent) { this.parent = parent; } public AbstractDataset getData() { return data; } public void setData(AbstractDataset set) { this.data = set; } public void appendData(AbstractDataset more) throws Exception { H5Utils.appendDataset(file, parent, more); } public Object getUserData() { return userData; } public void setUserData(Object userData) { this.userData = userData; } public IProgressMonitor getMonitor() { return monitor; } public void setMonitor(IProgressMonitor monitor) { this.monitor = monitor; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((axes == null) ? 0 : axes.hashCode()); result = prime * result + ((data == null) ? 0 : data.hashCode()); result = prime * result + ((file == null) ? 0 : file.hashCode()); result = prime * result + ((monitor == null) ? 0 : monitor.hashCode()); result = prime * result + ((parent == null) ? 0 : parent.hashCode()); result = prime * result + ((userData == null) ? 0 : userData.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; DataReductionSlice other = (DataReductionSlice) obj; if (axes == null) { if (other.axes != null) return false; } else if (!axes.equals(other.axes)) return false; if (data == null) { if (other.data != null) return false; } else if (!data.equals(other.data)) return false; if (file == null) { if (other.file != null) return false; } else if (!file.equals(other.file)) return false; if (monitor == null) { if (other.monitor != null) return false; } else if (!monitor.equals(other.monitor)) return false; if (parent == null) { if (other.parent != null) return false; } else if (!parent.equals(other.parent)) return false; if (userData == null) { if (other.userData != null) return false; } else if (!userData.equals(other.userData)) return false; return true; } public List<AbstractDataset> getAxes() { return axes; } public void setAxes(List<AbstractDataset> axes) { this.axes = axes; } } /** * TODO May add a method here to define extra wizard pages if a tool requires it. * public IWizardPage getToolExportWizardPage(...) { */ public final class DataReductionInfo { private IStatus status; /** * used to provide data between calls of the tool to maintain * state. For instance used in the peak fitting tool to provide * peaks with state. */ private Object userData; public DataReductionInfo(IStatus status) { this(status, null); } /** * * @param status * @param userData may be null. */ public DataReductionInfo(IStatus status, Object userData) { this.status = status; this.userData = userData; } public IStatus getStatus() { return status; } public void setStatus(IStatus status) { this.status = status; } public Object getUserData() { return userData; } public void setUserData(Object userData) { this.userData = userData; } } } diff --git a/org.dawb.gda.extensions/src/org/dawb/gda/extensions/loaders/H5Utils.java b/org.dawb.gda.extensions/src/org/dawb/gda/extensions/loaders/H5Utils.java index db9ddca6..13720e44 100644 --- a/org.dawb.gda.extensions/src/org/dawb/gda/extensions/loaders/H5Utils.java +++ b/org.dawb.gda.extensions/src/org/dawb/gda/extensions/loaders/H5Utils.java @@ -1,188 +1,188 @@ /* * Copyright (c) 2012 European Synchrotron Radiation Facility, * Diamond Light Source Ltd. * * 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 */ package org.dawb.gda.extensions.loaders; import ncsa.hdf.object.Dataset; import ncsa.hdf.object.Datatype; import ncsa.hdf.object.Group; import ncsa.hdf.object.h5.H5Datatype; import org.dawb.hdf5.IHierarchicalDataFile; import org.dawb.hdf5.Nexus; import uk.ac.diamond.scisoft.analysis.dataset.AbstractDataset; import uk.ac.diamond.scisoft.analysis.dataset.BooleanDataset; import uk.ac.diamond.scisoft.analysis.dataset.ByteDataset; import uk.ac.diamond.scisoft.analysis.dataset.DatasetUtils; import uk.ac.diamond.scisoft.analysis.dataset.DoubleDataset; import uk.ac.diamond.scisoft.analysis.dataset.FloatDataset; import uk.ac.diamond.scisoft.analysis.dataset.IDataset; import uk.ac.diamond.scisoft.analysis.dataset.IntegerDataset; import uk.ac.diamond.scisoft.analysis.dataset.LongDataset; import uk.ac.diamond.scisoft.analysis.dataset.ShortDataset; public class H5Utils { public static int getDataType(Datatype datatype) throws Exception { final int type = datatype.getDatatypeClass(); if (type == Datatype.CLASS_ARRAY) throw new Exception("Cannot read array type data sets!"); final int size = datatype.getDatatypeSize()*4; switch (size) { case 8: return AbstractDataset.INT8; case 16: return AbstractDataset.INT16; case 32: if (type==Datatype.CLASS_INTEGER) return AbstractDataset.INT32; if (type==Datatype.CLASS_FLOAT) return AbstractDataset.FLOAT32; - + //$FALL-THROUGH$ case 64: if (type==Datatype.CLASS_INTEGER) return AbstractDataset.INT64; if (type==Datatype.CLASS_FLOAT) return AbstractDataset.FLOAT64; } return AbstractDataset.FLOAT; } /** - * Gets a data set from the complete dims. + * Gets a dataset from the complete dims. * @param val * @param set - * @return + * @return dataset * @throws Exception */ public static AbstractDataset getSet(final Object val, final Dataset set) throws Exception { return H5Utils.getSet(val, set.getDims(), set); } /** * Used when dims are not the same as the entire set, for instance when doing a slice. * @param val * @param longShape * @param set - * @return + * @return dataset * @throws Exception */ public static AbstractDataset getSet(final Object val, final long[] longShape, final Dataset set) throws Exception { final int[] intShape = getInt(longShape); AbstractDataset ret = null; if (val instanceof byte[]) { ret = new ByteDataset((byte[])val, intShape); } else if (val instanceof short[]) { ret = new ShortDataset((short[])val, intShape); } else if (val instanceof int[]) { ret = new IntegerDataset((int[])val, intShape); } else if (val instanceof long[]) { ret = new LongDataset((long[])val, intShape); } else if (val instanceof float[]) { ret = new FloatDataset((float[])val, intShape); } else if (val instanceof double[]) { ret = new DoubleDataset((double[])val, intShape); } else { throw new Exception("Cannot deal with data type "+set.getDatatype().getDatatypeDescription()); } if (set.getDatatype().isUnsigned()) { switch (ret.getDtype()) { case AbstractDataset.INT32: ret = new LongDataset(ret); DatasetUtils.unwrapUnsigned(ret, 32); break; case AbstractDataset.INT16: ret = new IntegerDataset(ret); DatasetUtils.unwrapUnsigned(ret, 16); break; case AbstractDataset.INT8: ret = new ShortDataset(ret); DatasetUtils.unwrapUnsigned(ret, 8); break; } } return ret; } /** * Get a int[] from a long[] * @param longShape - * @return + * @return int shape */ public static int[] getInt(long[] longShape) { final int[] intShape = new int[longShape.length]; for (int i = 0; i < intShape.length; i++) intShape[i] = (int)longShape[i]; return intShape; } /** * Get a long[] from a int[] - * @param longShape - * @return + * @param intShape + * @return long shape */ public static long[] getLong(int[] intShape) { final long[] longShape = new long[intShape.length]; - for (int i = 0; i < intShape.length; i++) longShape[i] = (long)intShape[i]; + for (int i = 0; i < intShape.length; i++) longShape[i] = intShape[i]; return longShape; } /** * Determines the HDF5 Datatype for an abstract dataset. * @param a - * @return + * @return data type */ public static Datatype getDatatype(IDataset a) throws Exception { // There is a smarter way of doing this, but am in a hurry... if (a instanceof ByteDataset || a instanceof BooleanDataset) { return new H5Datatype(Datatype.CLASS_INTEGER, 8/8, Datatype.NATIVE, Datatype.SIGN_NONE); } else if (a instanceof ShortDataset) { return new H5Datatype(Datatype.CLASS_INTEGER, 16/8, Datatype.NATIVE, Datatype.NATIVE); } else if (a instanceof IntegerDataset) { return new H5Datatype(Datatype.CLASS_INTEGER, 32/8, Datatype.NATIVE, Datatype.NATIVE); } else if (a instanceof LongDataset) { return new H5Datatype(Datatype.CLASS_INTEGER, 64/8, Datatype.NATIVE, Datatype.NATIVE); } else if (a instanceof FloatDataset) { return new H5Datatype(Datatype.CLASS_FLOAT, 32/8, Datatype.NATIVE, Datatype.NATIVE); } else if (a instanceof DoubleDataset) { return new H5Datatype(Datatype.CLASS_FLOAT, 64/8, Datatype.NATIVE, Datatype.NATIVE); } throw new Exception("Cannot deal with data type "+a.getClass().getName()); } /** * Appends a to a dataset of the same name as a and parent Group of parent. * * @param file * @param parent * @param a * @throws Exception */ public static void appendDataset(IHierarchicalDataFile file, Group parent, AbstractDataset a) throws Exception { long[] shape = H5Utils.getLong(a.getShape()); Dataset s = file.appendDataset(a.getName(), H5Utils.getDatatype(a), shape, a.getBuffer(), parent); file.setNexusAttribute(s, Nexus.SDS); } }
false
false
null
null
diff --git a/openjpa-examples/src/main/java/relations/Deity.java b/openjpa-examples/src/main/java/relations/Deity.java index 5cdf4e2ac..0eb357343 100644 --- a/openjpa-examples/src/main/java/relations/Deity.java +++ b/openjpa-examples/src/main/java/relations/Deity.java @@ -1,203 +1,194 @@ /* * Copyright 2006 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package relations; import java.io.Serializable; import java.util.HashSet; import java.util.Set; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.Enumerated; import javax.persistence.EnumType; import javax.persistence.Id; import javax.persistence.NamedQuery; import javax.persistence.NamedQueries; import javax.persistence.OneToMany; import javax.persistence.OneToOne; /** * An entity that contains relations corresponding to family tree relations. * This entity demonstrates the following JPA features: * * 1. Enum fields (gender) * 2. @OneToOne relations * 3. @OneToMany relations * 4. Named queries */ @Entity @NamedQueries({ // a sibling shares a mother and a father @NamedQuery(name="siblings", query="select distinct sibling1 " + "from Deity sibling1, Deity sibling2 where " + "sibling1.father = sibling2.father " + "and sibling1.mother = sibling2.mother " + "and sibling2 = ?1 and sibling1 <> ?1"), // a half-siling shares a mother or a father, but not both @NamedQuery(name="half-siblings", query="select distinct sibling1 " + "from Deity sibling1, Deity sibling2 where " + "((sibling1.father = sibling2.father " + "and sibling1.mother <> sibling2.mother) " + "or (sibling1.father <> sibling2.father " + "and sibling1.mother = sibling2.mother)) " + "and sibling2 = ?1 and sibling1 <> ?1"), - // a half-siling shares a mother or a father, but not both - @NamedQuery(name="half-siblings", query="select distinct sibling1 " - + "from Deity sibling1, Deity sibling2 where " - + "((sibling1.father = sibling2.father " - + "and sibling1.mother <> sibling2.mother) " - + "or (sibling1.father <> sibling2.father " - + "and sibling1.mother = sibling2.mother)) " - + "and sibling2 = ?1 and sibling1 <> ?1"), - // a cousin shares a grandparent, but is not a sibling @NamedQuery(name="cousins", query="select distinct cousin1 " + "from Deity cousin1, Deity cousin2 where " + "(" + "cousin1.father.father = cousin2.father.father " + "or cousin1.father.mother = cousin2.father.mother " + "or cousin1.mother.father = cousin2.mother.father " + "or cousin1.mother.mother = cousin2.mother.mother) " + "and (cousin1.father <> cousin2.father) " + "and (cousin1.mother <> cousin2.mother) " + "and cousin2 = ?1 and cousin1 <> ?1") }) public class Deity implements Serializable { // the Id is the name, which is generally a bad idea, but we are // confident that diety names will be unique @Id private String name; @Basic @Enumerated(EnumType.STRING) private Gender gender; @OneToOne(cascade=CascadeType.ALL) private Deity mother; @OneToOne(cascade=CascadeType.ALL) private Deity father; @OneToMany(cascade=CascadeType.ALL) private Set<Deity> children; public static enum Gender { MALE, FEMALE } public Deity(String name, Gender gender) { this.name = name; this.gender = gender; } ////////////////////////// // Business methods follow ////////////////////////// /** * She's having a baby... * * @param firstName the baby name * @return the new child * * @throws IllegalArgumentException if the person is not a woman, or * if the person is unmarried (illegitimate * children are not yet supported) */ public Deity giveBirth(String childName, Deity childFather, Gender gender) { if (this.gender != Gender.FEMALE) throw new IllegalArgumentException("Only women can have children!"); if (childName == null) throw new IllegalArgumentException("No child name!"); // create the child Deity child = new Deity(childName, gender); // set the parents in the children... child.mother = this; // add the child to this member's children if (children == null) children = new HashSet<Deity>(); children.add(child); if (childFather != null) { child.father = childFather; if (childFather.children == null) childFather.children = new HashSet<Deity>(); childFather.children.add(child); } return child; } //////////////////////////////////// // Property accessor methods follow //////////////////////////////////// public void setName(String name) { this.name = name; } public String getName() { return this.name; } public void setGender(Gender gender) { this.gender = gender; } public Gender getGender() { return this.gender; } public void setMother(Deity mother) { this.mother = mother; } public Deity getMother() { return this.mother; } public void setFather(Deity father) { this.father = father; } public Deity getFather() { return this.father; } public void setChildren(Set<Deity> children) { this.children = children; } public Set<Deity> getChildren() { return this.children; } }
true
false
null
null
diff --git a/src/yabby/yabby/util/XMLProducer.java b/src/yabby/yabby/util/XMLProducer.java index a704df2..50448a0 100644 --- a/src/yabby/yabby/util/XMLProducer.java +++ b/src/yabby/yabby/util/XMLProducer.java @@ -1,799 +1,814 @@ /* * File XMLProducer.java * * Copyright (C) 2010 Remco Bouckaert [email protected] * * This file is part of yabby2. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership and licensing. * * yabby 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 * of the License, or (at your option) any later version. * * yabby 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 yabby; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301 USA */ package yabby.util; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Attr; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import yabby.core.*; import java.io.Reader; import java.io.StringReader; import java.io.StringWriter; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Map; /** * converts MCMC plug in into XML, i.e. does the reverse of XMLParser * but tries to prettify the XML as well. */ public class XMLProducer extends XMLParser { /** * list of objects already converted to XML, so an idref suffices */ HashSet<YABBYObject> isDone; @SuppressWarnings("rawtypes") HashSet<Input> inputsDone; /** * list of IDs of elements produces, used to prevent duplicate ID generation */ HashSet<String> IDs; /** * #spaces before elements in XML * */ int indent; final public static String DEFAULT_NAMESPACE = "yabby.core:yabby.evolution.alignment:yabby.evolution.tree.coalescent:yabby.core.util:yabby.evolution.nuc:yabby.evolution.operators:yabby.evolution.sitemodel:yabby.evolution.substitutionmodel:yabby.evolution.likelihood"; //final public static String DO_NOT_EDIT_WARNING = "DO NOT EDIT the following machine generated text, they are used in Beauti"; public XMLProducer() { super(); } /** * Main entry point for this class * Given a plug-in, produces the XML in yabby 2.0 format * representing the plug-in. This assumes plugin is Runnable */ @SuppressWarnings("rawtypes") public String toXML(YABBYObject plugin) { return toXML(plugin, new ArrayList<YABBYObject>()); } public String toXML(YABBYObject plugin, Collection<YABBYObject> others) { try { StringBuffer buf = new StringBuffer(); buf.append("<" + XMLParser.YABBY_ELEMENT + " version='2.0' namespace='" + DEFAULT_NAMESPACE + "'>\n"); for (String element : element2ClassMap.keySet()) { if (!reservedElements.contains(element)) { buf.append("<map name='" + element + "'>" + element2ClassMap.get(element) +"</map>\n"); } } buf.append("\n\n"); isDone = new HashSet<YABBYObject>(); inputsDone = new HashSet<Input>(); IDs = new HashSet<String>(); indent = 0; pluginToXML(plugin, buf, null, true); String sEndyabby = "</" + XMLParser.YABBY_ELEMENT + ">"; buf.append(sEndyabby); //return buf.toString(); // beautify XML hierarchy String sXML = cleanUpXML(buf.toString(), m_sXMLBeuatifyXSL); // TODO: fix m_sIDRefReplacementXSL script to deal with nested taxon sets // String sXML2 = cleanUpXML(sXML, m_sIDRefReplacementXSL); String sXML2 = sXML; sXML = findPlates(sXML2); // beatify by applying name spaces to spec attributes String[] sNameSpaces = DEFAULT_NAMESPACE.split(":"); for (String sNameSpace : sNameSpaces) { sXML = sXML.replaceAll("spec=\"" + sNameSpace + ".", "spec=\""); } buf = new StringBuffer(); if (others.size() > 0) { for (YABBYObject plugin2 : others) { if (!IDs.contains(plugin2.getID())) { pluginToXML(plugin2, buf, null, false); } } } int iEnd = sXML.indexOf(sEndyabby); String extras = buf.toString(); // prevent double -- inside XML comment, this can happen in sequences extras = extras.replaceAll("--","- - "); sXML = sXML.substring(0, iEnd) //+ "\n\n<!-- " + DO_NOT_EDIT_WARNING + " \n\n" + //extras + "\n\n-->\n\n" + sEndyabby; sXML = sXML.replaceAll("xmlns=\"http://www.w3.org/TR/xhtml1/strict\"", ""); - return sXML; + //insert newlines in alignments + int k = sXML.indexOf("<data "); + StringBuffer buf2 = new StringBuffer(sXML); + while (k > 0) { + while (sXML.charAt(k) != '>') { + if (sXML.charAt(k) == ' ') { + buf2.setCharAt(k, '\n'); + } + k++; + } + k = sXML.indexOf("<data ", k + 1); + } + + + return buf2.toString(); } catch (Exception e) { e.printStackTrace(); return null; } } // toXML /** * like toXML() but without the assumption that plugin is Runnable * */ public String modelToXML(YABBYObject plugin) { try { String sXML0 = toRawXML(plugin); String sXML = cleanUpXML(sXML0, m_sSupressAlignmentXSL); // TODO: fix m_sIDRefReplacementXSL script to deal with nested taxon sets //String sXML2 = cleanUpXML(sXML, m_sIDRefReplacementXSL); String sXML2 = sXML; sXML = findPlates(sXML2); sXML = sXML.replaceAll("<\\?xml version=\"1.0\" encoding=\"UTF-8\"\\?>", ""); sXML = sXML.replaceAll("\\n\\s*\\n", "\n"); return sXML; } catch (Exception e) { e.printStackTrace(); return null; } } // toXML /** * like modelToXML, but without the cleanup * */ @SuppressWarnings("rawtypes") public String toRawXML(YABBYObject plugin) { return toRawXML(plugin, null); } // toRawXML /** * like modelToXML, but without the cleanup * * For plugin without name */ @SuppressWarnings("rawtypes") public String toRawXML(YABBYObject plugin, String sName) { try { StringBuffer buf = new StringBuffer(); isDone = new HashSet<YABBYObject>(); inputsDone = new HashSet<Input>(); IDs = new HashSet<String>(); indent = 0; pluginToXML(plugin, buf, sName, false); return buf.toString(); } catch (Exception e) { e.printStackTrace(); return null; } } // toRawXML public String stateNodeToXML(YABBYObject plugin) { try { StringBuffer buf = new StringBuffer(); //buf.append("<" + XMLParser.yabby_ELEMENT + " version='2.0'>\n"); isDone = new HashSet<YABBYObject>(); IDs = new HashSet<String>(); indent = 0; pluginToXML(plugin, buf, null, false); return buf.toString(); } catch (Exception e) { e.printStackTrace(); return null; } } /** * Applies XSL script (specified in m_sXSL) to make XML a bit * nicer by removing unused IDs and moving data, yabby.tree and likelihood * outside MCMC element. * Tries to compress common parts into plates. */ String cleanUpXML(String sXML, String sXSL) throws TransformerException { StringWriter strWriter = new StringWriter(); Reader xmlInput = new StringReader(sXML); javax.xml.transform.Source xmlSource = new javax.xml.transform.stream.StreamSource(xmlInput); Reader xslInput = new StringReader(sXSL); javax.xml.transform.Source xsltSource = new javax.xml.transform.stream.StreamSource(xslInput); javax.xml.transform.Result result = new javax.xml.transform.stream.StreamResult(strWriter); // create an instance of TransformerFactory javax.xml.transform.TransformerFactory transFact = javax.xml.transform.TransformerFactory.newInstance(); javax.xml.transform.Transformer trans = transFact.newTransformer(xsltSource); trans.transform(xmlSource, result); String sXML2 = strWriter.toString(); return sXML2; } // compress parts into plates String findPlates(String sXML) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); doc = factory.newDocumentBuilder().parse(new InputSource(new StringReader(sXML))); doc.normalize(); Node topNode = doc.getElementsByTagName("*").item(0); findPlates(topNode); //create string from xml tree StringWriter sw = new StringWriter(); StreamResult result = new StreamResult(sw); DOMSource source = new DOMSource(doc); TransformerFactory factory2 = TransformerFactory.newInstance(); Transformer transformer = factory2.newTransformer(); transformer.transform(source, result); return sw.toString(); } /** * tries to compress XML into plates * */ void findPlates(Node node) { NodeList children = node.getChildNodes(); for (int iChild = 0; iChild < children.getLength(); iChild++) { Node child = children.item(iChild); if (child.getNodeType() == Node.ELEMENT_NODE) { List<Node> comparables = new ArrayList<Node>(); for (int iSibling = iChild + 1; iSibling < children.getLength(); iSibling++) { if (children.item(iSibling).getNodeType() == Node.ELEMENT_NODE) { Node sibling = children.item(iSibling); if (comparable(child, sibling, ".p1", ".p" + (comparables.size() + 2))) { comparables.add(sibling); } else { // break iSibling = children.getLength(); } } } if (comparables.size() > 0) { // TODO: FIX THIS SO THAT NOT AN ARBITRARY `1' is used to generate the plate // we can make a plate now // String sRange = "1"; // int k = 2; // for (Node sibling : comparables) { // sRange += "," + k++; // sibling.getParentNode().removeChild(sibling); // } // makePlate(child, "1", "n", sRange); } } } // recurse to lower levels children = node.getChildNodes(); for (int iChild = 0; iChild < children.getLength(); iChild++) { findPlates(children.item(iChild)); } } // findPlates /** * replace node element by a plate element with variable sVar and range sRange * */ void makePlate(Node node, String sPattern, String sVar, String sRange) { Element plate = doc.createElement("plate"); plate.setAttribute("var", sVar); plate.setAttribute("range", sRange); String sIndent = node.getPreviousSibling().getTextContent(); replace(node, sPattern, sVar); node.getParentNode().replaceChild(plate, node); plate.appendChild(doc.createTextNode(sIndent + " ")); plate.appendChild(node); plate.appendChild(doc.createTextNode(sIndent)); } /** * recursively replace all attribute values containing the pattern with variable sVar * */ void replace(Node node, String sPattern, String sVar) { NamedNodeMap atts = node.getAttributes(); if (atts != null) { for (int i = 0; i < atts.getLength(); i++) { Attr attr = (Attr) atts.item(i); String sValue = attr.getValue().replaceAll(sPattern, "\\$\\(" + sVar + "\\)"); ; attr.setValue(sValue); } } NodeList children = node.getChildNodes(); for (int iChild = 0; iChild < children.getLength(); iChild++) { Node child = children.item(iChild); replace(child, sPattern, sVar); } } /** * check if two XML nodes are the same, when sPattern1 is replaced by sPattothersern2 * */ boolean comparable(Node node1, Node node2, String sPattern1, String sPattern2) { // compare name if (!node1.getNodeName().equals(node2.getNodeName())) { return false; } // compare text if (!node1.getTextContent().trim().equals(node2.getTextContent().trim())) { return false; } // compare attributes NamedNodeMap atts = node1.getAttributes(); NamedNodeMap atts2 = node2.getAttributes(); if (atts.getLength() != atts2.getLength()) { return false; } for (int i = 0; i < atts.getLength(); i++) { Attr attr = (Attr) atts.item(i); String sName = attr.getName(); String sValue = attr.getValue(); Node att = atts2.getNamedItem(sName); if (att == null) { return false; } String sValue2 = ((Attr) att).getValue(); if (!sValue.equals(sValue2)) { sValue = sValue.replaceAll(sPattern1, "\\$\\(n\\)"); sValue2 = sValue2.replaceAll(sPattern2, "\\$\\(n\\)"); if (!sValue.equals(sValue2)) { return false; } } } // compare children NodeList children = node1.getChildNodes(); NodeList children2 = node2.getChildNodes(); for (int iChild = 0; iChild < children.getLength(); iChild++) { Node child = children.item(iChild); if (child.getNodeType() == Node.ELEMENT_NODE) { String sName = child.getNodeName(); boolean bMatch = false; for (int iChild2 = 0; !bMatch && iChild2 < children2.getLength(); iChild2++) { Node child2 = children2.item(iChild2); if (child2.getNodeType() == Node.ELEMENT_NODE && sName.equals(child2.getNodeName())) { bMatch = comparable(child, child2, sPattern1, sPattern2); } } if (!bMatch) { return false; } } } return true; } // comparable /** * XSL stylesheet for cleaning up bits and pieces of the vanilla XML * in order to make it more readable * */ String m_sXMLBeuatifyXSL = "<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform' xmlns='http://www.w3.org/TR/xhtml1/strict'>\n" + "\n" + "<xsl:output method='xml' indent='yes'/>\n" + "\n" + "<xsl:template match='yabby'>\n" + " <xsl:copy>\n" + " <xsl:apply-templates select='@*'/>\n" + " <xsl:text>&#x0a;&#x0a;&#x0a; </xsl:text>\n" + " <xsl:apply-templates select='//data[not(@idref)]' mode='copy'/>\n" + " <xsl:text>&#x0a;&#x0a;&#x0a; </xsl:text>\n" + " <xsl:apply-templates select='//yabby.tree[not(@idref)]' mode='copy'/>\n" + " <xsl:text>&#x0a;&#x0a;&#x0a; </xsl:text>\n" + " <xsl:apply-templates select='//distribution[not(@idref) and not(ancestor::distribution)]' mode='copy'/>\n" + " <xsl:text>&#x0a;&#x0a;&#x0a; </xsl:text>\n" + " <xsl:apply-templates select='node()'/> \n" + " </xsl:copy>\n" + "</xsl:template>\n" + "\n" + "<xsl:template match='*' mode='copy'>\n" + " <xsl:copy>\n" + " <xsl:attribute name='id'>\n" + " <xsl:value-of select='@id'/>\n" + " </xsl:attribute>\n" + " <xsl:apply-templates select='@*|node()'/>\n" + " </xsl:copy>\n" + "</xsl:template>\n" + "\n" + "<xsl:template match='data|yabby.tree|distribution[not(ancestor::distribution)]'>\n" + " <xsl:copy>\n" + " <xsl:attribute name='idref'>\n" + " <xsl:choose>\n" + " <xsl:when test='@idref!=\"\"'><xsl:value-of select='@idref'/></xsl:when>\n" + " <xsl:otherwise><xsl:value-of select='@id'/></xsl:otherwise>\n" + " </xsl:choose>\n" + " </xsl:attribute>\n" + " <xsl:apply-templates select='@name'/>\n" + " </xsl:copy>\n" + "</xsl:template>\n" + "\n" + "<xsl:template match='input'>\n" + " <xsl:element name='{@name}'>" + " <xsl:apply-templates select='node()|@*[name()!=\"name\"]'/>" + " </xsl:element>\n" + "</xsl:template>\n" + "<xsl:template match='log/log'>\n" + " <xsl:copy><xsl:apply-templates select='*[@*!=\"\"]'/> </xsl:copy>\n" + "</xsl:template>\n" + "\n" + // Better not suppress unused id's; used for example in reporting Operators //"<xsl:template match='@id'>\n" + //" <xsl:if test='//@idref=. or not(contains(../@spec,substring(.,string-length(.)-2)))'>\n" + //" <xsl:copy/>\n" + //" </xsl:if>\n" + //"</xsl:template>\n" + "\n" + "<xsl:template match='@*|node()'>\n" + " <xsl:copy>\n" + " <xsl:apply-templates select='@*|node()'/>\n" + " </xsl:copy>\n" + "</xsl:template>\n" + "\n" + "</xsl:stylesheet>\n"; /** * script to reduce elements of the form <name idref='xyz'/> to name='@xyz' attributes * */ String m_sIDRefReplacementXSL = "<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform' xmlns='http://www.w3.org/TR/xhtml1/strict'>\n" + "\n" + "<xsl:output method='xml' indent='yes'/>\n" + "\n" + "<xsl:template match='yabby'>\n" + " <xsl:copy>\n" + " <xsl:apply-templates select='@*|node()'/>\n" + " </xsl:copy>\n" + "</xsl:template>\n" + "\n" + "<xsl:template match='node()'>\n" + " <xsl:choose>\n" + " <xsl:when test='count(@idref)=1 and count(@name)=1 and count(@*)=2'>\n" + " <xsl:element name='{@name}'>\n" + " <xsl:attribute name='idref'>\n" + " <xsl:value-of select='@idref'/>\n" + " </xsl:attribute>\n" + " </xsl:element>\n" + " </xsl:when>\n" + " <xsl:when test='not(count(@idref)=1 and count(@*)=1)'>\n" + " <xsl:copy>\n" + " <xsl:apply-templates select='@*'/>\n" + " <xsl:for-each select='*'>\n" + " <xsl:if test='count(@idref)=1 and count(@*)=1'>\n" + " <xsl:attribute name='{name()}'>@<xsl:value-of select='@idref'/></xsl:attribute>\n" + " </xsl:if>\n" + " </xsl:for-each>\n" + " <xsl:apply-templates/>\n" + " </xsl:copy>\n" + " </xsl:when>\n" + " </xsl:choose>\n" + "</xsl:template>\n" + "\n" + "<xsl:template match='@*'>\n" + " <xsl:copy>\n" + " <xsl:apply-templates select='@*|node()'/>\n" + " </xsl:copy>\n" + "</xsl:template>\n" + "\n" + "</xsl:stylesheet>"; String s = "<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform' xmlns='http://www.w3.org/TR/xhtml1/strict'>\n" + "\n" + "<xsl:output method='xml' indent='yes'/>\n" + "\n" + "<xsl:template match='yabby'>\n" + " <xsl:copy>\n" + " <xsl:apply-templates select='@*|node()'/>\n" + " </xsl:copy>\n" + "</xsl:template>\n" + "\n" + "<xsl:template match='node()'>\n" + " <xsl:if test='not(count(@idref)=1 and count(@*)=1)'>\n" + " <xsl:copy>\n" + " <xsl:apply-templates select='@*'/>\n" + " <xsl:for-each select='*'>\n" + " <xsl:if test='count(@idref)=1 and count(@*)=1'>\n" + " <xsl:attribute name='{name()}'>@<xsl:value-of select='@idref'/></xsl:attribute>\n" + " </xsl:if>\n" + " </xsl:for-each>\n" + " <xsl:apply-templates/>\n" + " </xsl:copy>\n" + " </xsl:if>\n" + "</xsl:template>\n" + "\n" + "<xsl:template match='@*'>\n" + " <xsl:copy>\n" + " <xsl:apply-templates select='@*|node()'/>\n" + " </xsl:copy>\n" + "</xsl:template>\n" + "\n" + "</xsl:stylesheet>\n"; /** * XSL stylesheet for suppressing alignment* */ String m_sSupressAlignmentXSL = "<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform' xmlns='http://www.w3.org/TR/xhtml1/strict'>\n" + "\n" + "<xsl:output method='xml'/>\n" + "\n" + "<xsl:template match='data'/>\n" + "\n" + "<xsl:template match='input[@name]'>\n" + " <xsl:element name='{@name}'>" + " <xsl:apply-templates select='node()|@*[name()!=\"name\"]'/>" + " </xsl:element>\n" + "</xsl:template>\n" + "\n" + "<xsl:template match='@*|node()'>\n" + " <xsl:copy>\n" + " <xsl:apply-templates select='@*|node()'/>\n" + " </xsl:copy>\n" + "</xsl:template>\n" + "\n" + "</xsl:stylesheet>\n"; /** * produce elements for a plugin with name sName, putting results in buf. * It tries to create XML conforming to the XML transformation rules (see XMLParser) * that is moderately readable. */ @SuppressWarnings("rawtypes") void pluginToXML(YABBYObject plugin, StringBuffer buf, String sName, boolean bIsTopLevel) throws Exception { // determine element name, default is input, otherswise find one of the defaults String sElementName = "input"; for (String key : element2ClassMap.keySet()) { String className = element2ClassMap.get(key); Class _class = Class.forName(className); if (_class.equals(plugin.getClass())) { sElementName = key; } } // if (plugin instanceof Alignment) { // sElementName = XMLParser.DATA_ELEMENT; // } // if (plugin instanceof Sequence) { // sElementName = XMLParser.SEQUENCE_ELEMENT; // } // if (plugin instanceof State) { // sElementName = XMLParser.STATE_ELEMENT; // } // if (plugin instanceof Distribution) { // sElementName = XMLParser.DISTRIBUTION_ELEMENT; // } // if (plugin instanceof Logger) { // sElementName = XMLParser.LOG_ELEMENT; // } // if (plugin instanceof Operator) { // sElementName = XMLParser.OPERATOR_ELEMENT; // } // if (plugin instanceof RealParameter) { // sElementName = XMLParser.REAL_PARAMETER_ELEMENT; // } // if (plugin instanceof Tree) { // sElementName = XMLParser.TREE_ELEMENT; // } if (bIsTopLevel) { sElementName = XMLParser.RUN_ELEMENT; } for (int i = 0; i < indent; i++) { buf.append(" "); } indent++; // open element buf.append("<").append(sElementName); boolean bSkipInputs = false; if (isDone.contains(plugin)) { // XML is already produced, we can idref it buf.append(" idref='" + plugin.getID() + "'"); bSkipInputs = true; } else { // see whether a reasonable id can be generated if (plugin.getID() != null && !plugin.getID().equals("")) { String sID = plugin.getID(); // ensure ID is unique if (IDs.contains(sID)) { int k = 1; while (IDs.contains(sID + k)) { k++; } sID = sID + k; } buf.append(" id='" + sID + "'"); IDs.add(sID); } isDone.add(plugin); } String sClassName = plugin.getClass().getName(); if (bSkipInputs == false && (!element2ClassMap.containsKey(sElementName) || !element2ClassMap.get(sElementName).equals(sClassName))) { // only add spec element if it cannot be deduced otherwise (i.e., by idref or default mapping buf.append(" spec='" + sClassName + "'"); } if (sName != null && !sName.equals(sElementName)) { // only add name element if it differs from element = default name buf.append(" name='" + sName + "'"); } if (!bSkipInputs) { // process inputs of this plugin // first, collect values as attributes List<Input<?>> sInputs = plugin.listInputs(); for (Input sInput : sInputs) { inputToXML(sInput.getName(), plugin, buf, true); } // next, collect values as input elements StringBuffer buf2 = new StringBuffer(); for (Input sInput : sInputs) { inputToXML(sInput.getName(), plugin, buf2, false); } if (buf2.length() == 0) { // if nothing was added by the inputs, close element indent--; buf.append("/>\n"); } else { // add contribution of inputs buf.append(">\n"); buf.append(buf2); indent--; for (int i = 0; i < indent; i++) { buf.append(" "); } // add closing element buf.append("</" + sElementName + ">\n"); } } else { // close element indent--; buf.append("/>\n"); } if (indent < 2) { buf.append("\n"); } } // pluginToXML /** * produce XML for an input of a plugin, both as attribute/value pairs for * primitive inputs (if bShort=true) and as individual elements (if bShort=false) * * @param sInput: name of the input * @param plugin: plugin to produce this input XML for * @param buf: gets XML results are appended * @param bShort: flag to indicate attribute/value format (true) or element format (false) * @throws Exception */ @SuppressWarnings("rawtypes") void inputToXML(String sInput, YABBYObject plugin, StringBuffer buf, boolean isShort) throws Exception { Field[] fields = plugin.getClass().getFields(); for (int i = 0; i < fields.length; i++) { if (fields[i].getType().isAssignableFrom(Input.class)) { Input input = (Input) fields[i].get(plugin); if (input.getName().equals(sInput)) { // found the input with name sInput if (input.get() != null) { if (input.get() instanceof Map) { // distinguish between List, Plugin and primitive input types - if (!isShort) { + if (isShort) { Map<String,?> map = (Map<String,?>) input.get(); - // determine label widith + // determine label width int whiteSpaceWidth = 0; for (String key : map.keySet()) { whiteSpaceWidth = Math.max(whiteSpaceWidth, key.length()); } for (String key : map.keySet()) { - buf.append(" <input name='" + key + "'>"); + //buf.append(" <input name='" + key + "'>"); + buf.append("\n " + key); for (int k = key.length(); k < whiteSpaceWidth; k++) { buf.append(' '); } - buf.append(normalise(input.get().toString()) + "</input>\n"); + buf.append("=\"" + normalise(map.get(key).toString()) + "\""); } } return; } else if (input.get() instanceof List) { if (!isShort) { int k = 0; List list = (List) input.get(); for (Object o2 : list) { if (o2 instanceof YABBYObject) { pluginToXML((YABBYObject) o2, buf, sInput, false); } else { k++; buf.append(o2.toString()); if (k < list.size()-1) { buf.append(' '); } } } } return; } else if (input.get() instanceof YABBYObject) { if (!input.get().equals(input.defaultValue)) { if (isShort && isDone.contains((YABBYObject) input.get())) { buf.append(" " + sInput + "='@" + ((YABBYObject) input.get()).getID() + "'"); inputsDone.add(input); } if (!isShort && !inputsDone.contains(input)) { pluginToXML((YABBYObject) input.get(), buf, sInput, false); } } return; } else { if (!input.get().equals(input.defaultValue)) { // primitive type, see if String sValue = input.get().toString(); if (isShort) { if (sValue.indexOf('\n') < 0) { buf.append(" " + sInput + "='" + normalise(input.get().toString()) + "'"); } } else { if (sValue.indexOf('\n') >= 0) { for (int j = 0; j < indent; j++) { buf.append(" "); } if (sInput.equals("value")) { buf.append(input.get().toString()); } else { buf.append("<input name='" + sInput + "'>" + normalise(input.get().toString()) + "</input>\n"); } } } } return; } } else { // value=null, no XML to produce return; } } } } // should never get here throw new Exception("Could not find input " + sInput + " in plugin " + plugin.getID() + " " + plugin.getClass().getName()); } // inputToXML /** convert plain text string to XML string, replacing some entities **/ String normalise(String str) { str = str.replaceAll("&", "&amp;"); str = str.replaceAll("'", "&apos;"); str = str.replaceAll("\"", "&quot;"); str = str.replaceAll("<", "&lt;"); str = str.replaceAll(">", "&gt;"); return str; } } // class XMLProducer
false
false
null
null
diff --git a/src/com/android/gallery3d/filtershow/imageshow/ImageDraw.java b/src/com/android/gallery3d/filtershow/imageshow/ImageDraw.java index 6c3417ad3..8fcc028af 100644 --- a/src/com/android/gallery3d/filtershow/imageshow/ImageDraw.java +++ b/src/com/android/gallery3d/filtershow/imageshow/ImageDraw.java @@ -1,150 +1,150 @@ package com.android.gallery3d.filtershow.imageshow; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.MotionEvent; import com.android.gallery3d.filtershow.editors.EditorDraw; import com.android.gallery3d.filtershow.filters.FilterDrawRepresentation; import com.android.gallery3d.filtershow.filters.ImageFilterDraw; public class ImageDraw extends ImageShow { private static final String LOGTAG = "ImageDraw"; private int mCurrentColor = Color.RED; final static float INITAL_STROKE_RADIUS = 40; private float mCurrentSize = INITAL_STROKE_RADIUS; private byte mType = 0; private FilterDrawRepresentation mFRep; private EditorDraw mEditorDraw; public ImageDraw(Context context, AttributeSet attrs) { super(context, attrs); resetParameter(); super.setOriginalDisabled(true); } public ImageDraw(Context context) { super(context); resetParameter(); super.setOriginalDisabled(true); } public void setEditor(EditorDraw editorDraw) { mEditorDraw = editorDraw; } public void setFilterDrawRepresentation(FilterDrawRepresentation fr) { mFRep = fr; } public Drawable getIcon(Context context) { return null; } @Override public void resetParameter() { if (mFRep != null) { mFRep.clear(); } } public void setColor(int color) { mCurrentColor = color; } public void setSize(int size) { mCurrentSize = size; } public void setStyle(byte style) { mType = (byte) (style % ImageFilterDraw.NUMBER_OF_STYLES); } public int getStyle() { return mType; } public int getSize() { return (int) mCurrentSize; } @Override public void updateImage() { super.updateImage(); invalidate(); } float[] mTmpPoint = new float[2]; // so we do not malloc @Override public boolean onTouchEvent(MotionEvent event) { - boolean ret = super.onTouchEvent(event); if (event.getPointerCount() > 1) { + boolean ret = super.onTouchEvent(event); if (mFRep.getCurrentDrawing() != null) { mFRep.clearCurrentSection(); mEditorDraw.commitLocalRepresentation(); } return ret; } if (event.getAction() != MotionEvent.ACTION_DOWN) { if (mFRep.getCurrentDrawing() == null) { - return ret; + return super.onTouchEvent(event); } } ImageFilterDraw filter = (ImageFilterDraw) getCurrentFilter(); if (event.getAction() == MotionEvent.ACTION_DOWN) { calcScreenMapping(); mTmpPoint[0] = event.getX(); mTmpPoint[1] = event.getY(); mToOrig.mapPoints(mTmpPoint); mFRep.startNewSection(mType, mCurrentColor, mCurrentSize, mTmpPoint[0], mTmpPoint[1]); } if (event.getAction() == MotionEvent.ACTION_MOVE) { int historySize = event.getHistorySize(); final int pointerCount = event.getPointerCount(); for (int h = 0; h < historySize; h++) { int p = 0; { mTmpPoint[0] = event.getHistoricalX(p, h); mTmpPoint[1] = event.getHistoricalY(p, h); mToOrig.mapPoints(mTmpPoint); mFRep.addPoint(mTmpPoint[0], mTmpPoint[1]); } } } if (event.getAction() == MotionEvent.ACTION_UP) { mTmpPoint[0] = event.getX(); mTmpPoint[1] = event.getY(); mToOrig.mapPoints(mTmpPoint); mFRep.endSection(mTmpPoint[0], mTmpPoint[1]); } mEditorDraw.commitLocalRepresentation(); invalidate(); return true; } Matrix mRotateToScreen = new Matrix(); Matrix mToOrig; private void calcScreenMapping() { mToOrig = getScreenToImageMatrix(true); mToOrig.invert(mRotateToScreen); } @Override public void onDraw(Canvas canvas) { super.onDraw(canvas); calcScreenMapping(); } }
false
true
public boolean onTouchEvent(MotionEvent event) { boolean ret = super.onTouchEvent(event); if (event.getPointerCount() > 1) { if (mFRep.getCurrentDrawing() != null) { mFRep.clearCurrentSection(); mEditorDraw.commitLocalRepresentation(); } return ret; } if (event.getAction() != MotionEvent.ACTION_DOWN) { if (mFRep.getCurrentDrawing() == null) { return ret; } } ImageFilterDraw filter = (ImageFilterDraw) getCurrentFilter(); if (event.getAction() == MotionEvent.ACTION_DOWN) { calcScreenMapping(); mTmpPoint[0] = event.getX(); mTmpPoint[1] = event.getY(); mToOrig.mapPoints(mTmpPoint); mFRep.startNewSection(mType, mCurrentColor, mCurrentSize, mTmpPoint[0], mTmpPoint[1]); } if (event.getAction() == MotionEvent.ACTION_MOVE) { int historySize = event.getHistorySize(); final int pointerCount = event.getPointerCount(); for (int h = 0; h < historySize; h++) { int p = 0; { mTmpPoint[0] = event.getHistoricalX(p, h); mTmpPoint[1] = event.getHistoricalY(p, h); mToOrig.mapPoints(mTmpPoint); mFRep.addPoint(mTmpPoint[0], mTmpPoint[1]); } } } if (event.getAction() == MotionEvent.ACTION_UP) { mTmpPoint[0] = event.getX(); mTmpPoint[1] = event.getY(); mToOrig.mapPoints(mTmpPoint); mFRep.endSection(mTmpPoint[0], mTmpPoint[1]); } mEditorDraw.commitLocalRepresentation(); invalidate(); return true; }
public boolean onTouchEvent(MotionEvent event) { if (event.getPointerCount() > 1) { boolean ret = super.onTouchEvent(event); if (mFRep.getCurrentDrawing() != null) { mFRep.clearCurrentSection(); mEditorDraw.commitLocalRepresentation(); } return ret; } if (event.getAction() != MotionEvent.ACTION_DOWN) { if (mFRep.getCurrentDrawing() == null) { return super.onTouchEvent(event); } } ImageFilterDraw filter = (ImageFilterDraw) getCurrentFilter(); if (event.getAction() == MotionEvent.ACTION_DOWN) { calcScreenMapping(); mTmpPoint[0] = event.getX(); mTmpPoint[1] = event.getY(); mToOrig.mapPoints(mTmpPoint); mFRep.startNewSection(mType, mCurrentColor, mCurrentSize, mTmpPoint[0], mTmpPoint[1]); } if (event.getAction() == MotionEvent.ACTION_MOVE) { int historySize = event.getHistorySize(); final int pointerCount = event.getPointerCount(); for (int h = 0; h < historySize; h++) { int p = 0; { mTmpPoint[0] = event.getHistoricalX(p, h); mTmpPoint[1] = event.getHistoricalY(p, h); mToOrig.mapPoints(mTmpPoint); mFRep.addPoint(mTmpPoint[0], mTmpPoint[1]); } } } if (event.getAction() == MotionEvent.ACTION_UP) { mTmpPoint[0] = event.getX(); mTmpPoint[1] = event.getY(); mToOrig.mapPoints(mTmpPoint); mFRep.endSection(mTmpPoint[0], mTmpPoint[1]); } mEditorDraw.commitLocalRepresentation(); invalidate(); return true; }
diff --git a/javafx.platform/src/org/netbeans/modules/javafx/platform/platformdefinition/JavaFXPlatformImpl.java b/javafx.platform/src/org/netbeans/modules/javafx/platform/platformdefinition/JavaFXPlatformImpl.java index e2b26dde..84bcf239 100644 --- a/javafx.platform/src/org/netbeans/modules/javafx/platform/platformdefinition/JavaFXPlatformImpl.java +++ b/javafx.platform/src/org/netbeans/modules/javafx/platform/platformdefinition/JavaFXPlatformImpl.java @@ -1,390 +1,392 @@ /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): * * The Original Software is NetBeans. The Initial Developer of the Original * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun * Microsystems, Inc. All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. */ package org.netbeans.modules.javafx.platform.platformdefinition; import java.lang.ref.Reference; import java.lang.ref.WeakReference; import java.util.*; import java.net.URL; import java.io.File; import java.net.URISyntaxException; import org.netbeans.api.java.classpath.ClassPath; import org.netbeans.api.java.platform.Specification; import org.netbeans.api.javafx.platform.JavaFXPlatform; import org.netbeans.api.project.ProjectManager; import org.netbeans.spi.java.classpath.PathResourceImplementation; import org.netbeans.spi.java.classpath.support.ClassPathSupport; import org.netbeans.spi.project.support.ant.EditableProperties; import org.netbeans.spi.project.support.ant.PropertyUtils; import org.openide.filesystems.FileUtil; import org.openide.filesystems.FileObject; import org.openide.filesystems.URLMapper; import org.openide.util.Exceptions; /** * Implementation of the JavaPlatform API class, which serves proper * bootstrap classpath information. */ public class JavaFXPlatformImpl extends JavaFXPlatform { public static final String PROP_ANT_NAME = "antName"; //NOI18N public static final String PLATFORM_JAVAFX = "JavaFX"; //NOI18N protected static final String PLAT_PROP_ANT_NAME="platform.ant.name"; //NOI18N protected static final String PLAT_PROP_FX_HOME="platform.fx.home"; //NOI18N protected static final String PLAT_PROP_ARCH_FOLDER="platform.arch.folder"; //NOI18N protected static final String SYSPROP_BOOT_CLASSPATH = "sun.boot.class.path"; // NOI18N protected static final String SYSPROP_JAVA_CLASS_PATH = "java.class.path"; // NOI18N protected static final String SYSPROP_JAVA_EXT_PATH = "java.ext.dirs"; //NOI18N protected static final String SYSPROP_USER_DIR = "user.dir"; //NOI18N /** * Holds the display name of the platform */ private String displayName; /** * Holds the properties of the platform */ private Map<String,String> properties; /** * List&lt;URL&gt; */ private ClassPath sources; /** * List&lt;URL&gt; */ private List<URL> javadoc; /** * List&lt;URL&gt; */ private List<URL> installFolders; private List<URL> javaFolders; private URL fxFolder; /** * Holds bootstrap libraries for the platform */ Reference<ClassPath> bootstrap = new WeakReference<ClassPath>(null); /** * Holds standard libraries of the platform */ Reference<ClassPath> standardLibs = new WeakReference<ClassPath>(null); /** * Holds the specification of the platform */ private Specification spec; JavaFXPlatformImpl (String dispName, List<URL> javaFolders, URL fxFolder, Map<String,String> initialProperties, Map<String,String> sysProperties, List<URL> sources, List<URL> javadoc) { super(); this.displayName = dispName; this.javaFolders = javaFolders; this.fxFolder = fxFolder; this.installFolders = new ArrayList<URL>(); this.installFolders.addAll(javaFolders); // if (fxFolder != null) // this.installFolders.add(fxFolder); this.properties = initialProperties; this.sources = createClassPath(sources); if (javadoc != null) { this.javadoc = Collections.unmodifiableList(javadoc); //No copy needed, called from this module => safe } else { this.javadoc = Collections.<URL>emptyList(); } setSystemProperties(filterProbe(sysProperties)); addPlatformProperties(this); } protected JavaFXPlatformImpl (String dispName, String antName, List<URL> javaFolders, URL fxFolder, Map<String,String> initialProperties, Map<String,String> sysProperties, List<URL> sources, List<URL> javadoc) { this (dispName, javaFolders, fxFolder, initialProperties, sysProperties,sources, javadoc); this.properties.put (PLAT_PROP_ANT_NAME,antName); this.properties.put (PLAT_PROP_FX_HOME,fxFolder.toString()); + addPlatformProperties(this); } /** * @return a descriptive, human-readable name of the platform */ public String getDisplayName() { return displayName; } /** * Alters the human-readable name of the platform * @param name the new display name */ public void setDisplayName(String name) { this.displayName = name; firePropertyChange(PROP_DISPLAY_NAME, null, null); // NOI18N } /** * Alters the human-readable name of the platform without firing * events. This method is an internal contract to allow lazy creation * of display name * @param name the new display name */ final protected void internalSetDisplayName (String name) { this.displayName = name; } public String getAntName () { return (String) this.properties.get (PLAT_PROP_ANT_NAME); } public void setAntName (String antName) { if (antName == null || antName.length()==0) { throw new IllegalArgumentException (); } this.properties.put(PLAT_PROP_ANT_NAME, antName); this.firePropertyChange (PROP_ANT_NAME,null,null); } public void setArchFolder (final String folder) { if (folder == null || folder.length() == 0) { throw new IllegalArgumentException (); } this.properties.put (PLAT_PROP_ARCH_FOLDER, folder); } public ClassPath getBootstrapLibraries() { synchronized (this) { ClassPath cp = (bootstrap == null ? null : bootstrap.get()); if (cp != null) return cp; String pathSpec = getSystemProperties().get(SYSPROP_BOOT_CLASSPATH); if (installFolders.size() == 2) try { String fxRT = new File(installFolders.get(1).toURI()).getAbsolutePath(); pathSpec = pathSpec + File.pathSeparator + fxRT; fxRT = Util.getExtensions(fxRT); if (fxRT != null) pathSpec = pathSpec + File.pathSeparator + fxRT; } catch (URISyntaxException e) { Exceptions.printStackTrace(e); } String extPathSpec = Util.getExtensions((String)getSystemProperties().get(SYSPROP_JAVA_EXT_PATH)); if (extPathSpec != null) { pathSpec = pathSpec + File.pathSeparator + extPathSpec; } cp = Util.createClassPath (pathSpec); bootstrap = new WeakReference<ClassPath>(cp); return cp; } } /** * This implementation simply reads and parses `java.class.path' property and creates a ClassPath * out of it. * @return ClassPath that represents contents of system property java.class.path. */ public ClassPath getStandardLibraries() { synchronized (this) { ClassPath cp = (standardLibs == null ? null : standardLibs.get()); if (cp != null) return cp; String pathSpec = getSystemProperties().get(SYSPROP_JAVA_CLASS_PATH); cp = Util.createClassPath (pathSpec); standardLibs = new WeakReference<ClassPath>(cp); return cp; } } /** * Retrieves a collection of {@link org.openide.filesystems.FileObject}s of one or more folders * where the Platform is installed. Typically it returns one folder, but * in some cases there can be more of them. */ public final Collection<FileObject> getInstallFolders() { Collection<FileObject> result = new ArrayList<FileObject> (); for (Iterator<URL> it = this.installFolders.iterator(); it.hasNext();) { URL url = it.next (); FileObject root = URLMapper.findFileObject(url); if (root != null) { result.add (root); } } return result; } public URL getJavaFXFolder() { return fxFolder; } public final FileObject findTool(final String toolName) { String archFolder = getProperties().get(PLAT_PROP_ARCH_FOLDER); FileObject tool = null; if (archFolder != null) { tool = Util.findTool (toolName, this.getInstallFolders(), archFolder); } if (tool == null) { tool = Util.findTool (toolName, this.getInstallFolders()); } return tool; } /** * Returns the location of the source of platform * @return List&lt;URL&gt; */ public final ClassPath getSourceFolders () { return this.sources; } public final void setSourceFolders (ClassPath c) { assert c != null; this.sources = c; this.firePropertyChange(PROP_SOURCE_FOLDER, null, null); } /** * Returns the location of the Javadoc for this platform * @return FileObject */ public final List<URL> getJavadocFolders () { return this.javadoc; } public final void setJavadocFolders (List<URL> c) { assert c != null; List<URL> safeCopy = Collections.unmodifiableList (new ArrayList<URL> (c)); for (Iterator<URL> it = safeCopy.iterator(); it.hasNext();) { URL url = it.next (); if (!"jar".equals (url.getProtocol()) && FileUtil.isArchiveFile(url)) { throw new IllegalArgumentException ("JavadocFolder must be a folder."); } } this.javadoc = safeCopy; this.firePropertyChange(PROP_JAVADOC_FOLDER, null, null); } public String getVendor() { String s = getSystemProperties().get("java.vm.vendor"); // NOI18N return s == null ? "" : s; // NOI18N } public Specification getSpecification() { if (spec == null) { spec = new Specification (PLATFORM_JAVAFX, Util.getSpecificationVersion(this)); //NOI18N } return spec; } public Map<String,String> getProperties() { return Collections.unmodifiableMap (this.properties); } Collection getInstallFolderURLs () { return Collections.unmodifiableList(this.installFolders); } protected static String filterProbe (String v, final String probePath) { if (v != null) { final String[] pes = PropertyUtils.tokenizePath(v); final StringBuilder sb = new StringBuilder (); for (String pe : pes) { if (probePath != null ? probePath.equals(pe) : (pe != null && pe.endsWith("org-netbeans-modules-javafx-platform-probe.jar"))) { //NOI18N //Skeep } else { if (sb.length() > 0) { sb.append(File.pathSeparatorChar); } sb.append(pe); } } v = sb.toString(); } return v; } private void addPlatformProperties(final JavaFXPlatformImpl platform){ final Thread tt = Thread.currentThread(); Thread t = new Thread(new Runnable(){ public void run(){ try{ - tt.join(); //hack to avoid overwriting by J2EEPlatform module the properties we put + if (platform instanceof DefaultPlatformImpl) + tt.join(); //hack to avoid overwriting by J2EEPlatform module the properties we put }catch(Exception e){} ProjectManager.mutex().writeAccess( new Runnable(){ public void run (){ try{ EditableProperties props = PropertyUtils.getGlobalProperties(); PlatformConvertor.generatePlatformProperties(platform, platform.getAntName(), props); PropertyUtils.putGlobalProperties (props); }catch(Exception e){ e.printStackTrace(); } }}); } }); t.start(); } private static Map<String,String> filterProbe (final Map<String,String> p) { if (p!=null) { final String val = p.get(SYSPROP_JAVA_CLASS_PATH); if (val != null) { p.put(SYSPROP_JAVA_CLASS_PATH, filterProbe(val, null)); } } return p; } private static ClassPath createClassPath (final List<? extends URL> urls) { List<PathResourceImplementation> resources = new ArrayList<PathResourceImplementation> (); if (urls != null) { for (URL url : urls) { resources.add (ClassPathSupport.createResource (url)); } } return ClassPathSupport.createClassPath (resources); } }
false
false
null
null
diff --git a/src/com/jme/util/export/binary/BinaryClassLoader.java b/src/com/jme/util/export/binary/BinaryClassLoader.java index f9c2f7123..0a78d46f7 100755 --- a/src/com/jme/util/export/binary/BinaryClassLoader.java +++ b/src/com/jme/util/export/binary/BinaryClassLoader.java @@ -1,130 +1,145 @@ /* * Copyright (c) 2003-2007 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.util.export.binary; import java.io.IOException; import java.util.HashMap; +import java.util.logging.Logger; import com.jme.util.export.InputCapsule; import com.jme.util.export.Savable; import com.jme.util.export.binary.modules.BinaryAbstractCameraModule; import com.jme.util.export.binary.modules.BinaryAlphaStateModule; import com.jme.util.export.binary.modules.BinaryAttributeStateModule; import com.jme.util.export.binary.modules.BinaryClipStateModule; import com.jme.util.export.binary.modules.BinaryColorMaskStateModule; import com.jme.util.export.binary.modules.BinaryCullStateModule; import com.jme.util.export.binary.modules.BinaryDitherStateModule; import com.jme.util.export.binary.modules.BinaryFogStateModule; import com.jme.util.export.binary.modules.BinaryFragmentProgramStateModule; import com.jme.util.export.binary.modules.BinaryGLSLShaderObjectsStateModule; import com.jme.util.export.binary.modules.BinaryLightStateModule; import com.jme.util.export.binary.modules.BinaryMaterialStateModule; import com.jme.util.export.binary.modules.BinaryShadeStateModule; import com.jme.util.export.binary.modules.BinaryStencilStateModule; import com.jme.util.export.binary.modules.BinaryTextureStateModule; import com.jme.util.export.binary.modules.BinaryVertexProgramStateModule; import com.jme.util.export.binary.modules.BinaryWireframeStateModule; import com.jme.util.export.binary.modules.BinaryZBufferStateModule; /** * @author mpowell * */ public class BinaryClassLoader { //list of modules maintained in the loader private static HashMap<String, BinaryLoaderModule> modules = new HashMap<String, BinaryLoaderModule>(); //use a core module to handle render states. static { BinaryClassLoader.registerModule(new BinaryAbstractCameraModule()); BinaryClassLoader.registerModule(new BinaryAlphaStateModule()); BinaryClassLoader.registerModule(new BinaryAttributeStateModule()); BinaryClassLoader.registerModule(new BinaryClipStateModule()); BinaryClassLoader.registerModule(new BinaryColorMaskStateModule()); BinaryClassLoader.registerModule(new BinaryCullStateModule()); BinaryClassLoader.registerModule(new BinaryDitherStateModule()); BinaryClassLoader.registerModule(new BinaryFogStateModule()); BinaryClassLoader.registerModule(new BinaryFragmentProgramStateModule()); BinaryClassLoader.registerModule(new BinaryGLSLShaderObjectsStateModule()); BinaryClassLoader.registerModule(new BinaryLightStateModule()); BinaryClassLoader.registerModule(new BinaryMaterialStateModule()); BinaryClassLoader.registerModule(new BinaryShadeStateModule()); BinaryClassLoader.registerModule(new BinaryStencilStateModule()); BinaryClassLoader.registerModule(new BinaryTextureStateModule()); BinaryClassLoader.registerModule(new BinaryVertexProgramStateModule()); BinaryClassLoader.registerModule(new BinaryWireframeStateModule()); BinaryClassLoader.registerModule(new BinaryZBufferStateModule()); } /** * registrrModule adds a module to the loader for handling special case class names. * @param m the module to register with this loader. */ public static void registerModule(BinaryLoaderModule m) { modules.put(m.getKey(), m); } /** * unregisterModule removes a module from the loader, no longer using it to handle * special case class names. * @param m the module to remove from the loader. */ public static void unregisterModule(BinaryLoaderModule m) { modules.remove(m.getKey()); } /** * fromName creates a new Savable from the provided class name. First registered modules * are checked to handle special cases, if the modules do not handle the class name, the * class is instantiated directly. * @param className the class name to create. * @param inputCapsule the InputCapsule that will be used for loading the Savable (to look up ctor parameters) * @return the Savable instance of the class. * @throws InstantiationException thrown if the class does not have an empty constructor. * @throws IllegalAccessException thrown if the class is not accessable. * @throws ClassNotFoundException thrown if the class name is not in the classpath. * @throws IOException when loading ctor parameters fails */ public static Savable fromName(String className, InputCapsule inputCapsule) throws InstantiationException, IllegalAccessException, ClassNotFoundException, IOException { BinaryLoaderModule m = modules.get(className); if(m != null) { return m.load(inputCapsule); } - return (Savable)Class.forName(className).newInstance(); + try { + return (Savable)Class.forName(className).newInstance(); + } + catch (InstantiationException e) { + Logger.getLogger(BinaryClassLoader.class.getName()).severe( + "Could not access constructor of class '" + className + "'! \n" + + "Some types need to have the BinaryImporter set up in a special way. Please doublecheck the setup."); + throw e; + } + catch (IllegalAccessException e) { + Logger.getLogger(BinaryClassLoader.class.getName()).severe( + e.getMessage() + " \n" + + "Some types need to have the BinaryImporter set up in a special way. Please doublecheck the setup."); + throw e; + } } }
false
false
null
null
diff --git a/src/tdanford/json/schema/OptionalType.java b/src/tdanford/json/schema/OptionalType.java index ca62c9d..5dccc2f 100644 --- a/src/tdanford/json/schema/OptionalType.java +++ b/src/tdanford/json/schema/OptionalType.java @@ -1,19 +1,19 @@ package tdanford.json.schema; public class OptionalType implements JSONType { private JSONType innerType; public OptionalType(JSONType t) { innerType = t; } public boolean contains(Object obj) { - return obj == null || innerType.contains(obj); + return JSONObject.NULL.equals(obj) || innerType.contains(obj); } public java.lang.String explain(Object obj) { return innerType.explain(obj); } }
true
false
null
null
diff --git a/src/mulan/data/Statistics.java b/src/mulan/data/Statistics.java index 657f521..08c6703 100644 --- a/src/mulan/data/Statistics.java +++ b/src/mulan/data/Statistics.java @@ -1,479 +1,475 @@ /* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* * Statistics.java * Copyright (C) 2009-2010 Aristotle University of Thessaloniki, Thessaloniki, Greece */ package mulan.data; import java.io.Serializable; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.Set; import weka.core.Instance; import weka.core.Instances; import weka.core.Utils; import weka.filters.Filter; import weka.filters.unsupervised.attribute.Remove; /** <!-- globalinfo-start --> * Class for calculating statistics of a multilabel dataset <p> * <br/> * For more information, see<br/> * <br/> * G. Tsoumakas, I. Katakis (2007). Multi-Label Classification: An Overview. International Journal of Data Warehousing and Mining, 3(3):1-13. * </p> <!-- globalinfo-end --> * <!-- technical-bibtex-start --> * BibTeX: * <pre> * &#64;article{tsoumakas+katakis:2007, * author = {G. Tsoumakas, I. Katakis}, * journal = {International Journal of Data Warehousing and Mining}, * pages = {1-13}, * title = {Multi-Label Classification: An Overview}, * volume = {3}, * number = {3}, * year = {2007} * } * </pre> * <p/> <!-- technical-bibtex-end --> * <!-- options-start --> * Valid options are: <p/> * * <pre> -F &lt;filename&gt; * The filename (including full path) of the multilabel mlData set).</pre> * * <pre> -L &lt;number of labels&gt; * Number of labels. </pre> * <!-- options-end --> * * @author Grigorios Tsoumakas * @author Robert Friberg * @version $Revision: 0.03 $ */ public class Statistics implements Serializable { private static final long serialVersionUID = 1206845794397561633L; /** the number of instances */ private int numInstances; /** the number of predictive attributes */ private int numPredictors = 0; /** the number of nominal predictive attributes */ private int numNominal = 0; /** the number of numeric attributes */ private int numNumeric = 0; /** the number of labels */ private int numLabels; /** the label density */ private double labelDensity; /** the label cardinality */ private double labelCardinality; /** percentage of instances per label */ private double[] examplesPerLabel; /** number of examples per cardinality, <br><br> * note that this array has size equal to the number of elements plus one, <br> * because the first element is the number of examples for cardinality=0 */ private double[] cardinalityDistribution; /** labelsets and their frequency */ private HashMap<LabelSet, Integer> labelsets; /** the array holding the phi correlations*/ double[][] phi; /** * returns the HashMap containing the distinct labelsets and their frequencies * * @return HashMap with distinct labelsest and their frequencies */ public HashMap<LabelSet, Integer> labelCombCount() { return labelsets; } /** * This method calculates and prints a matrix with the coocurrences of <br> * pairs of labels * * @param mdata a multi-label data set * @return a matrix of co-occurences */ public double[][] calculateCoocurrence(MultiLabelInstances mdata) { Instances data = mdata.getDataSet(); int labels = mdata.getNumLabels(); double[][] coocurrenceMatrix = new double[labels][labels]; numPredictors = data.numAttributes() - labels; for (int k = 0; k < data.numInstances(); k++) { Instance temp = data.instance(k); for (int i = 0; i < labels; i++) { for (int j = 0; j < labels; j++) { if (i >= j) { continue; } if (temp.stringValue(numPredictors + i).equals("1") && temp.stringValue(numPredictors + j).equals("1")) { coocurrenceMatrix[i][j]++; } } } } for (int i = 0; i < labels; i++) { for (int j = 0; j < labels; j++) { System.out.print(coocurrenceMatrix[i][j] + "\t"); } System.out.println(); } return coocurrenceMatrix; } /** * calculates various multilabel statistics, such as label cardinality, <br> * label density and the set of distinct labels along with their frequency * * @param mlData a multi-label dataset */ public void calculateStats(MultiLabelInstances mlData) { // initialize statistics Instances data = mlData.getDataSet(); numLabels = mlData.getNumLabels(); int[] labelIndices = mlData.getLabelIndices(); int[] featureIndices = mlData.getFeatureIndices(); numPredictors = featureIndices.length; labelCardinality = 0; numNominal = 0; numNumeric = 0; examplesPerLabel = new double[numLabels]; cardinalityDistribution = new double[numLabels + 1]; labelsets = new HashMap<LabelSet, Integer>(); // gather statistics for (int i = 0; i < featureIndices.length; i++) { if (data.attribute(featureIndices[i]).isNominal()) { numNominal++; } if (data.attribute(featureIndices[i]).isNumeric()) { numNumeric++; } } numInstances = data.numInstances(); for (int i = 0; i < numInstances; i++) { int exampleCardinality = 0; double[] dblLabels = new double[numLabels]; for (int j = 0; j < numLabels; j++) { if (data.instance(i).stringValue(labelIndices[j]).equals("1")) { dblLabels[j] = 1; exampleCardinality++; labelCardinality++; examplesPerLabel[j]++; } else { dblLabels[j] = 0; } } cardinalityDistribution[exampleCardinality]++; LabelSet labelSet = new LabelSet(dblLabels); if (labelsets.containsKey(labelSet)) { labelsets.put(labelSet, labelsets.get(labelSet) + 1); } else { labelsets.put(labelSet, 1); } } labelCardinality /= numInstances; labelDensity = labelCardinality / numLabels; for (int j = 0; j < numLabels; j++) { examplesPerLabel[j] /= numInstances; } } /** * Calculates phi correlation * * @param dataSet a multi-label dataset * @return a matrix containing phi correlations * @throws java.lang.Exception */ public double[][] calculatePhi(MultiLabelInstances dataSet) throws Exception { numLabels = dataSet.getNumLabels(); /** the indices of the label attributes */ int[] labelIndices; labelIndices = dataSet.getLabelIndices(); numLabels = dataSet.getNumLabels(); phi = new double[numLabels][numLabels]; Remove remove = new Remove(); remove.setInvertSelection(true); remove.setAttributeIndicesArray(labelIndices); remove.setInputFormat(dataSet.getDataSet()); Instances result = Filter.useFilter(dataSet.getDataSet(), remove); result.setClassIndex(result.numAttributes() - 1); for (int i = 0; i < numLabels; i++) { int a[] = new int[numLabels]; int b[] = new int[numLabels]; int c[] = new int[numLabels]; int d[] = new int[numLabels]; double e[] = new double[numLabels]; double f[] = new double[numLabels]; double g[] = new double[numLabels]; double h[] = new double[numLabels]; for (int j = 0; j < result.numInstances(); j++) { for (int l = 0; l < numLabels; l++) { if (result.instance(j).stringValue(i).equals("0")) { if (result.instance(j).stringValue(l).equals("0")) { a[l]++; } else { c[l]++; } } else { if (result.instance(j).stringValue(l).equals("0")) { b[l]++; } else { d[l]++; } } } } for (int l = 0; l < numLabels; l++) { e[l] = a[l] + b[l]; f[l] = c[l] + d[l]; g[l] = a[l] + c[l]; h[l] = b[l] + d[l]; double mult = e[l] * f[l] * g[l] * h[l]; double denominator = Math.sqrt(mult); double nominator = a[l] * d[l] - b[l] * c[l]; phi[i][l] = nominator / denominator; } } return phi; } /** * Prints out phi correlations */ public void printPhiCorrelations() { String pattern = "0.00"; DecimalFormat myFormatter = new DecimalFormat(pattern); for (int i = 0; i < numLabels; i++) { for (int j = 0; j < numLabels; j++) { System.out.print(myFormatter.format(phi[i][j]) + " "); } System.out.println(""); } } /** * Calculates a histogram of phi correlations * * @return an array with phi correlations */ public double[] getPhiHistogram() { double[] pairs = new double[numLabels * (numLabels - 1) / 2]; int counter = 0; for (int i = 0; i < numLabels - 1; i++) { for (int j = i + 1; j < numLabels; j++) { pairs[counter] = phi[i][j]; counter++; } } return pairs; } /** * returns the indices of the labels whose phi coefficient values lie * between -bound <= phi <= bound * * @param labelIndex * @param bound * @return the indices of the labels whose phi coefficient values lie between -bound <= phi <= bound */ public int[] uncorrelatedLabels(int labelIndex, double bound) { ArrayList<Integer> indiceslist = new ArrayList<Integer>(); for (int i = 0; i < numLabels; i++) { if (Math.abs(phi[labelIndex][i]) <= bound) { indiceslist.add(i); } } int[] indices = new int[indiceslist.size()]; for (int i = 0; i < indiceslist.size(); i++) { indices[i] = indiceslist.get(i); } return indices; } /** * Returns the indices of the labels that have the strongest phi correlation * with the label which is given as a parameter. The second parameter is * the number of labels that will be returned. * * @param labelIndex * @param k * @return the indices of the k most correlated labels */ public int[] topPhiCorrelatedLabels(int labelIndex, int k) { //create a new array containing the absolute values of the original array double[] absCorrelations = new double[numLabels]; for (int i = 0; i < numLabels; i++) { absCorrelations[i] = Math.abs(phi[labelIndex][i]); } //sort the array of correlations int[] sorted = Utils.stableSort(absCorrelations); int[] topPhiCorrelated = new int[k + 1]; //the k last values of the sorted array are the indices of the top k correlated labels for (int i = 0; i < k; i++) { topPhiCorrelated[i] = sorted[numLabels - 1 - i]; } // one more for the class topPhiCorrelated[k] = numLabels; return topPhiCorrelated; } /** * This method prints data, useful for the visualization of Phi per dataset. * It prints int(1/step) + 1 pairs of values. The first value of each pair * is the phi value and the second is the average number of labels that * correlate to the rest of the labels with correlation higher than the * specified phi value; * * @param step * the phi value increment step */ public void printPhiDiagram(double step) { String pattern = "0.00"; DecimalFormat myFormatter = new DecimalFormat(pattern); System.out.println("Phi AvgCorrelated"); double tempPhi = 0; while (tempPhi <= 1.001) { double avgCorrelated = 0; for (int i = 0; i < numLabels; i++) { int[] temp = uncorrelatedLabels(i, tempPhi); avgCorrelated += (numLabels - temp.length); } avgCorrelated /= numLabels; System.out.println(myFormatter.format(phi) + " " + avgCorrelated); tempPhi += step; } } /** * returns various multilabel statistics in textual representation */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Examples: " + numInstances + "\n"); sb.append("Predictors: " + numPredictors + "\n"); sb.append("--Nominal: " + numNominal + "\n"); sb.append("--Numeric: " + numNumeric + "\n"); sb.append("Labels: " + numLabels + "\n"); sb.append("\n"); sb.append("Cardinality: " + labelCardinality + "\n"); sb.append("Density: " + labelDensity + "\n"); sb.append("Distinct Labelsets: " + labelsets.size() + "\n"); sb.append("\n"); for (int j = 0; j < numLabels; j++) { sb.append("Percentage of examples with label " + (j + 1) + ": " + examplesPerLabel[j] + "\n"); } sb.append("\n"); for (int j = 0; j <= numLabels; j++) { sb.append("Examples of cardinality " + j + ": " + cardinalityDistribution[j] + "\n"); } sb.append("\n"); for (LabelSet set : labelsets.keySet()) { sb.append("Examples of combination " + set + ": " + labelsets.get(set) + "\n"); } return sb.toString(); } /** * returns the prior probabilities of the labels * * @return array of prior probabilities of labels */ public double[] priors() { - double[] pr = new double[numLabels]; - for (int i = 0; i < numLabels; i++) { - pr[i] = examplesPerLabel[i] / numInstances; - } - return pr; + return examplesPerLabel; } /** * returns the label cardinality of the dataset * * @return label cardinality */ public double cardinality() { return labelCardinality; } /** * returns the label density of the dataset * * @return label density */ public double density() { return labelDensity; } /** * returns a set with the distinct labelsets of the dataset * * @return set of distinct labelsets */ public Set<LabelSet> labelSets() { return labelsets.keySet(); } /** * returns the frequency of a labelset in the dataset * * @param x a labelset * @return the frequency of the given labelset */ public int labelFrequency(LabelSet x) { return labelsets.get(x); } }
true
false
null
null
diff --git a/jxls-core/src/main/java/net/sf/jxls/parser/CellParser.java b/jxls-core/src/main/java/net/sf/jxls/parser/CellParser.java index 86b342f..28e15aa 100644 --- a/jxls-core/src/main/java/net/sf/jxls/parser/CellParser.java +++ b/jxls-core/src/main/java/net/sf/jxls/parser/CellParser.java @@ -1,307 +1,308 @@ package net.sf.jxls.parser; import java.io.IOException; import java.io.StringReader; import java.util.Map; import net.sf.jxls.exception.ParsePropertyException; import net.sf.jxls.formula.Formula; import net.sf.jxls.tag.Block; import net.sf.jxls.tag.Tag; import net.sf.jxls.tag.TagContext; import net.sf.jxls.transformer.Configuration; import net.sf.jxls.transformer.Row; import net.sf.jxls.util.Util; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.xml.sax.SAXException; /** * Class for parsing excel cell * @author Leonid Vysochyn */ public class CellParser { protected final Log log = LogFactory.getLog(getClass()); private final Cell cell; private Configuration configuration; public CellParser(HSSFCell hssfCell, Row row, Configuration configuration) { this.cell = new Cell( hssfCell, row ); if( configuration!=null ){ this.configuration = configuration; }else{ this.configuration = new Configuration(); } } public CellParser(Cell cell) { this.cell = cell; } public Cell getCell() { return cell; } public Cell parseCell(Map beans){ if (cell.getHssfCell() != null) { try { if( cell.getHssfCell().getCellType() == HSSFCell.CELL_TYPE_STRING ){ cell.setHssfCellValue(cell.getHssfCell().getRichStringCellValue().getString()); parseCellValue( beans); } } catch (ParsePropertyException e) { log.error("Can't get value for property=" + cell.getCollectionProperty().getProperty(), e); throw new RuntimeException(e); } updateMergedRegions(); } return cell; } public Formula parseCellFormula(){ if( cell.getHssfCell() != null && (cell.getHssfCell().getCellType() == HSSFCell.CELL_TYPE_STRING)) { cell.setHssfCellValue( cell.getHssfCell().getRichStringCellValue().getString() ); if( cell.getHssfCellValue().startsWith(configuration.getStartFormulaToken()) && cell.getHssfCellValue().lastIndexOf(configuration.getEndFormulaToken()) > 0 ){ parseFormula(); } } return cell.getFormula(); } private void parseFormula() { // process formula cell int i = cell.getHssfCellValue().lastIndexOf(configuration.getEndFormulaToken()); String expr = cell.getHssfCellValue().substring(2, i); cell.setFormula(new Formula(expr)); cell.getFormula().setRowNum(new Integer(cell.getRow().getHssfRow().getRowNum())); cell.getFormula().setCellNum(new Integer(cell.getHssfCell().getCellNum())); if (i + 1 < cell.getHssfCellValue().length()) { String tail = cell.getHssfCellValue().substring(i+1); int j = tail.indexOf(configuration.getMetaInfoToken()); if( j >= 0 ){ cell.setMetaInfo(tail.substring(j)); if( j > 0 ){ cell.setLabel(tail.substring(0, j)); } cell.setCollectionName(tail.substring(j + 2)); }else{ cell.setLabel(tail); } } cell.setStringCellValue(cell.getHssfCellValue().substring(0, i+1)); } private void parseCellExpression(Map beans) { cell.setCollectionProperty(null); String curValue = cell.getHssfCellValue(); int depRowNum = 0; int j = curValue.lastIndexOf(configuration.getMetaInfoToken()); if( j>=0 ){ cell.setStringCellValue(cell.getHssfCellValue().substring(0, j)); cell.setMetaInfo(cell.getHssfCellValue().substring(j + 2)); String tail = curValue.substring(j + 2); // processing additional parameters // check if there is collection property name specified int k = tail.indexOf(":"); if( k >= 0 ){ try { depRowNum = Integer.parseInt( tail.substring(k+1) ); } catch (NumberFormatException e) { // ignore it if not an integer } cell.setCollectionName(tail.substring(0, k)); }else{ cell.setCollectionName(tail); } curValue = curValue.substring(0, j); }else{ cell.setStringCellValue(cell.getHssfCellValue()); } try { while( curValue.length()>0 ){ int i = curValue.indexOf(configuration.getStartExpressionToken()); if( i>=0 ) { int k = curValue.indexOf(configuration.getEndExpressionToken(), i+2); if( k>=0 ){ // new bean property found String expr = curValue.substring(i+2, k); if( i>0 ){ String before = curValue.substring(0, i); cell.getExpressions().add( new Expression( before, configuration ) ); } Expression expression = new Expression(expr, beans, configuration); if( expression.getCollectionProperty() != null ){ if( cell.getCollectionProperty() == null ){ cell.setCollectionName(expression.getCollectionProperty().getFullCollectionName()); cell.setCollectionProperty(expression.getCollectionProperty()); cell.setDependentRowNumber(depRowNum); }else{ if( log.isInfoEnabled() ){ log.info("Only the same collection property in a cell is allowed."); } } } cell.getExpressions().add( expression ); curValue = curValue.substring(k+1, curValue.length()); }else{ cell.getExpressions().add( new Expression(curValue, configuration) ); + curValue = ""; } }else{ if( curValue.length()!=cell.getHssfCellValue().length() ){ cell.getExpressions().add( new Expression( curValue, configuration )); } curValue = ""; } } } catch (Exception e) { e.printStackTrace(); log.error("Can't parse expression", e); } } private void parseCellValue(Map beans) throws ParsePropertyException { if( cell.getHssfCellValue() !=null ){ if( cell.getHssfCellValue().startsWith(configuration.getStartFormulaToken()) && cell.getHssfCellValue().lastIndexOf(configuration.getEndFormulaToken()) > 0 ){ parseFormula(); }else if(cell.getHssfCellValue().startsWith( "<" + configuration.getTagPrefix() )){ // String tagName = cell.getHssfCellValue().split("(?<=<" + configuration.getTagPrefix() + ")\\w+", 2)[0]; String tagName = getTagName( cell.getHssfCellValue() ); if( tagName!=null ){ if (cell.getHssfCellValue().endsWith("/>")) { Block tagBody = new Block(cell.getRow().getHssfRow().getRowNum(), cell.getHssfCell().getCellNum(), cell.getRow().getHssfRow().getRowNum(), cell.getHssfCell().getCellNum()); parseTag( tagName, tagBody, beans, false); } else { HSSFCell hssfCell = findMatchingPairInRow( cell.getRow().getHssfRow(), tagName ); if( hssfCell!=null ){ // closing tag is in the same row Block tagBody = new Block(cell.getRow().getHssfRow().getRowNum(), cell.getHssfCell().getCellNum(), cell.getRow().getHssfRow().getRowNum(), hssfCell.getCellNum()); parseTag( tagName, tagBody, beans, true); }else{ HSSFRow hssfRow = findMatchingPair( tagName ); if( hssfRow!=null ){ // closing tag is in hssfRow int lastTagBodyRowNum = hssfRow.getRowNum() ; Block tagBody = new Block(null, cell.getRow().getHssfRow().getRowNum(), lastTagBodyRowNum); parseTag( tagName, tagBody, beans , true); }else{ log.warn("Can't find matching tag pair for " + cell.getHssfCellValue()); } } } } }else{ parseCellExpression(beans); } } } private HSSFCell findMatchingPairInRow(HSSFRow hssfRow, String tagName) { int count = 0; if( hssfRow!=null ){ for(short j = (short) (cell.getHssfCell().getCellNum() + 1); j <= hssfRow.getLastCellNum(); j++){ HSSFCell hssfCell = hssfRow.getCell( j ); if( hssfCell != null && hssfCell.getCellType() == HSSFCell.CELL_TYPE_STRING ){ String cellValue = hssfCell.getRichStringCellValue().getString(); if( cellValue.matches("<" + configuration.getTagPrefix() + tagName + "\\b.*")){ count++; }else{ if( cellValue.matches("</" + configuration.getTagPrefix() + tagName + ">" )){ if( count == 0 ){ return hssfCell; } count--; } } } } } return null; } private String getTagName(String xmlTag){ int i = configuration.getTagPrefix().length() + 1; int j = i; while( j < xmlTag.length() && Character.isLetterOrDigit( xmlTag.charAt( j ) ) ){ j++; } if( j == xmlTag.length() ){ log.warn("can't determine tag name"); return null; } return xmlTag.substring(i, j); } private HSSFRow findMatchingPair(String tagName) { HSSFSheet hssfSheet = cell.getRow().getSheet().getHssfSheet(); int count = 0; for( int i = cell.getRow().getHssfRow().getRowNum() + 1; i <= hssfSheet.getLastRowNum(); i++ ){ HSSFRow hssfRow = hssfSheet.getRow( i ); if( hssfRow!=null ){ for(short j = hssfRow.getFirstCellNum(); j <= hssfRow.getLastCellNum(); j++){ HSSFCell hssfCell = hssfRow.getCell( j ); if( hssfCell != null && hssfCell.getCellType() == HSSFCell.CELL_TYPE_STRING ){ String cellValue = hssfCell.getRichStringCellValue().getString(); if( cellValue.matches("<" + configuration.getTagPrefix() + tagName + "\\b.*")){ count++; }else{ if( cellValue.matches("</" + configuration.getTagPrefix() + tagName + ">" )){ if( count == 0 ){ return hssfRow; } count--; } } } } } } return null; } private void parseTag(String tagName, Block tagBody, Map beans, boolean appendCloseTag){ String xml = null; try { if (appendCloseTag) { xml = configuration.getJXLSRoot() + cell.getHssfCellValue() + "</" + configuration.getTagPrefix() + tagName + ">" + configuration.getJXLSRootEnd(); } else { xml = configuration.getJXLSRoot() + cell.getHssfCellValue() + configuration.getJXLSRootEnd(); } if (configuration.getEncodeXMLAttributes()) { xml = Util.escapeAttributes( xml ); } Tag tag = (Tag) configuration.getDigester().parse(new StringReader( xml ) ); if (tag == null) { throw new RuntimeException("Invalid tag: " + tagName); } cell.setTag( tag ); TagContext tagContext = new TagContext( cell.getRow().getSheet(), tagBody, beans ); tag.init( tagContext ); } catch (IOException e) { log.warn( "Can't parse cell tag " + cell.getHssfCellValue() + ": fullXML: " + xml, e); throw new RuntimeException("Can't parse cell tag " + cell.getHssfCellValue() + ": fullXML: " + xml, e); } catch (SAXException e) { log.warn( "Can't parse cell tag " + cell.getHssfCellValue() + ": fullXML: " + xml, e); throw new RuntimeException("Can't parse cell tag " + cell.getHssfCellValue() + ": fullXML: " + xml, e); } } private void updateMergedRegions() { cell.setMergedRegion(Util.getMergedRegion( cell.getRow().getSheet().getHssfSheet(), cell.getRow().getHssfRow().getRowNum(), cell.getHssfCell().getCellNum() )); } } diff --git a/jxls-core/src/test/java/net/sf/jxls/XLSTransformerTest.java b/jxls-core/src/test/java/net/sf/jxls/XLSTransformerTest.java index d1c35f3..a3537ab 100644 --- a/jxls-core/src/test/java/net/sf/jxls/XLSTransformerTest.java +++ b/jxls-core/src/test/java/net/sf/jxls/XLSTransformerTest.java @@ -1,2059 +1,2077 @@ package net.sf.jxls; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import junit.framework.TestCase; import net.sf.jxls.bean.Bean; import net.sf.jxls.bean.BeanWithList; import net.sf.jxls.bean.Column; import net.sf.jxls.bean.Department; import net.sf.jxls.bean.Employee; import net.sf.jxls.bean.Item; import net.sf.jxls.bean.MyBean; import net.sf.jxls.bean.SimpleBean; import net.sf.jxls.exception.ParsePropertyException; import net.sf.jxls.transformer.Configuration; import net.sf.jxls.transformer.XLSTransformer; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.util.Region; import org.apache.poi.poifs.filesystem.POIFSFileSystem; /** * @author Leonid Vysochyn */ public class XLSTransformerTest extends TestCase { protected final Log log = LogFactory.getLog(getClass()); public static final String simpleBeanXLS = "/templates/simplebean.xls"; public static final String simpeBeanDestXLS = "target/simplebean_output.xls"; public static final String hideSheetsXLS = "/templates/hidesheets.xls"; public static final String hideSheetsDestXLS = "target/hidesheets_output.xls"; public static final String beanWithListXLS = "/templates/beanwithlist.xls"; public static final String beanWithListDestXLS = "target/beanwithlist_output.xls"; public static final String emptyBeansXLS = "/templates/beanwithlist.xls"; public static final String emptyBeansDestXLS = "target/emptybeans_output.xls"; public static final String formulasXLS = "/templates/formulas.xls"; public static final String formulasDestXLS = "target/formulas_output.xls"; public static final String formulas2XLS = "/templates/formulas2.xls"; public static final String formulas2DestXLS = "target/formulas2_output.xls"; public static final String multipleListRowsXLS = "/templates/multiplelistrows.xls"; public static final String multipleListRowsDestXLS = "target/multiplelistrows_output.xls"; public static final String grouping1XLS = "/templates/grouping1.xls"; public static final String grouping1DestXLS = "target/grouping1_output.xls"; public static final String groupingFormulasXLS = "/templates/groupingformulas.xls"; public static final String groupingFormulasDestXLS = "target/groupingformulas_output.xls"; public static final String grouping2XLS = "/templates/grouping2.xls"; public static final String grouping2DestXLS = "target/grouping2_output.xls"; public static final String grouping3XLS = "/templates/grouping3.xls"; public static final String grouping3DestXLS = "target/grouping3_output.xls"; public static final String mergeCellsListXLS = "/templates/mergecellslist.xls"; public static final String mergeCellsListDestXLS = "target/mergecellslist_output.xls"; public static final String mergeMultipleListRowsXLS = "/templates/mergemultiplelistrows.xls"; public static final String mergeMultipleListRowsDestXLS = "target/mergemultiplelistrows_output.xls"; public static final String severalPropertiesInCellXLS = "/templates/severalpropertiesincell.xls"; public static final String severalPropertiesInCellDestXLS = "target/severalpropertiesincell_output.xls"; public static final String parallelTablesXLS = "/templates/paralleltables.xls"; public static final String parallelTablesDestXLS = "target/paralleltables_output.xls"; public static final String severalListsInRowXLS = "/templates/severallistsinrow.xls"; public static final String severalListsInRowDestXLS = "target/severallistsinrow_output.xls"; public static final String fixedSizeListXLS = "/templates/fixedsizelist.xls"; public static final String fixedSizeListDestXLS = "target/fixedsizelist_output.xls"; public static final String expressions1XLS = "/templates/expressions1.xls"; public static final String expressions1DestXLS = "target/expressions1_output.xls"; public static final String iftagXLS = "/templates/iftag.xls"; public static final String iftagDestXLS = "target/iftag_output.xls"; public static final String forifTag2XLS = "/templates/foriftag2.xls"; public static final String forifTag2DestXLS = "target/foriftag2_output.xls"; public static final String poiobjectsXLS = "/templates/poiobjects.xls"; public static final String poiobjectsDestXLS = "target/poiobjects_output.xls"; public static final String forifTag3XLS = "/templates/foriftag3.xls"; public static final String forifTag3DestXLS = "target/foriftag3_output.xls"; public static final String forifTag3OutTagXLS = "/templates/foriftag3OutTag.xls"; public static final String forifTag3OutTagDestXLS = "target/foriftag3OutTag_output.xls"; public static final String forifTagMergeXLS = "/templates/foriftagmerge.xls"; public static final String forifTagMergeDestXLS = "target/foriftagmerge_output.xls"; public static final String employeeNotesXLS = "/templates/employeeNotes.xls"; public static final String employeeNotesDestXLS = "target/employeeNotes_output.xls"; public static final String employeeNotesRusDestXLS = "target/employeeNotesRus_output.xls"; public static final String varStatusXLS = "/templates/varstatus.xls"; public static final String varStatusDestXLS = "/target/varstatus_output.xls"; public static final String forifTagOneRowXLS = "/templates/foriftagOneRow.xls"; public static final String forifTagOneRowDestXLS = "target/foriftagOneRow_output.xls"; public static final String dynamicColumnsXLS = "/templates/dynamicColumns.xls"; public static final String dynamicColumnsDestXLS = "target/dynamicColumns_output.xls"; public static final String forifTagOneRow2XLS = "/templates/foriftagOneRow2.xls"; public static final String forifTagOneRowDest2XLS = "target/foriftagOneRow2_output.xls"; public static final String multipleSheetListXLS = "/templates/multipleSheetList.xls"; public static final String multipleSheetListDestXLS = "target/multipleSheetList_output.xls"; public static final String multipleSheetList2XLS = "/templates/multipleSheetList2.xls"; public static final String multipleSheetList2DestXLS = "target/multipleSheetList2_output.xls"; public static final String multiTabXLS = "/templates/multi-tab-template.xls"; public static final String multiTabDestXLS = "target/multi-tab_output.xls"; public static final String groupTagXLS = "/templates/groupTag.xls"; public static final String groupTagDestXLS = "target/groupTag_output.xls"; public static final String jexlXLS = "/templates/jexl.xls"; public static final String jexlDestXLS = "target/jexl_output.xls"; public static final String forGroupByXLS = "/templates/forgroup.xls"; public static final String forGroupByDestXLS = "target/forgroup_output.xls"; public static final String outlineXLS = "/templates/outline.xls"; public static final String outlineDestXLS = "target/outline_output.xls"; public static final String selectXLS = "/templates/select.xls"; public static final String selectDestXLS = "/templates/select_output.xls"; public static final String outTagOneRowXLS = "/templates/outtaginonerow.xls"; public static final String outTagOneRowDestXLS = "/templates/outtaginonerow_output.xls"; SimpleBean simpleBean1; SimpleBean simpleBean2; SimpleBean simpleBean3; BeanWithList beanWithList; List beanList = new ArrayList(); List itEmployees = new ArrayList(); BeanWithList listBean1 = new BeanWithList("List bean 1"); BeanWithList listBean2 = new BeanWithList("List bean 2"); Object[] names = new Object[]{"Bean 1", "Bean 2", "Bean 3"}; Object[] doubleValues = new Object[]{new Double(100.34567), new Double(555.3), new Double(777.569)}; Object[] intValues = new Object[]{new Integer(10), new Integer(123), new Integer(10234)}; Object[] dateValues = new Object[]{new Date(), null, new Date()}; Object[] names2 = new Object[]{"Bean 1", "Bean 2", "Bean 3", "Bean 4", "Bean 5", "Bean 6", "Bean 7"}; Object[] doubleValues2 = new Object[]{new Double(111.222), new Double(222.333), new Double(333.444), new Double(444.555), new Double(555.666), new Double(666.777), new Double(777.888)}; Object[] intValues2 = new Object[]{new Integer(11), new Integer(12), new Integer(13), new Integer(14), new Integer(15), new Integer(16), new Integer(17)}; String[] itEmployeeNames = new String[] {"Elsa", "Oleg", "Neil", "Maria", "John"}; String[] hrEmployeeNames = new String[] {"Olga", "Helen", "Keith", "Cat"}; String[] baEmployeeNames = new String[] {"Denise", "LeAnn", "Natali"}; String[] mgrEmployeeNames = new String[] {"Sean", "John", "Joerg"}; Double[] itPayments = new Double[] {new Double(1500), new Double(2300), new Double(2500), new Double(1700), new Double(2800)}; Double[] hrPayments = new Double[] {new Double(1400), new Double(2100), new Double(1800), new Double(1900)}; Double[] baPayments = new Double[] {new Double(2400), new Double(2200), new Double(2600)}; Double[] mgrPayments = new Double[] {null, new Double(6000), null}; Double[] itBonuses = new Double[] {new Double(0.15), new Double(0.25), new Double(0.00), new Double(0.15), new Double(0.20)}; Double[] hrBonuses = new Double[] {new Double(0.20), new Double(0.10), new Double(0.15), new Double(0.15)}; Double[] baBonuses = new Double[] {new Double(0.20), new Double(0.15), new Double(0.10)}; Double[] mgrBonuses = new Double[] {new Double(0.20), null, new Double(0.20)}; Integer[] itAges = new Integer[] {new Integer(34), new Integer(30), new Integer(25), new Integer(25), new Integer(35)}; Integer[] hrAges = new Integer[] {new Integer(26), new Integer(28), new Integer(26), new Integer(26)}; Integer[] baAges = new Integer[] {new Integer(30), new Integer(30), new Integer(30)}; Integer[] mgrAges = new Integer[] {null, new Integer(35), null}; List departments = new ArrayList(); Department mgrDepartment, itDepartment; int[] amounts = {1, 2, 4, 6, 7, 8, 9, 10, 11, 13, 15, 18, 20, 21, 22}; List amountBeans = new ArrayList(); public XLSTransformerTest() { } public XLSTransformerTest(String s) { super(s); } protected void setUp() throws Exception { super.setUp(); simpleBean1 = new SimpleBean(names[0].toString(), (Double) doubleValues[0], (Integer) intValues[0], (Date) dateValues[0]); simpleBean2 = new SimpleBean(names[1].toString(), (Double) doubleValues[1], (Integer) intValues[1], (Date) dateValues[1]); simpleBean3 = new SimpleBean(names[2].toString(), (Double) doubleValues[2], (Integer) intValues[2], (Date) dateValues[2]); listBean2.addBean( new SimpleBean(names2[0].toString(), (Double) doubleValues2[0], (Integer) intValues2[0]) ); listBean2.addBean( new SimpleBean(names2[1].toString(), (Double) doubleValues2[1], (Integer) intValues2[1]) ); listBean2.addBean( new SimpleBean(names2[2].toString(), (Double) doubleValues2[2], (Integer) intValues2[2]) ); listBean2.addBean( new SimpleBean(names2[3].toString(), (Double) doubleValues2[3], (Integer) intValues2[3]) ); listBean2.addBean( new SimpleBean(names2[4].toString(), (Double) doubleValues2[4], (Integer) intValues2[4]) ); listBean2.addBean( new SimpleBean(names2[5].toString(), (Double) doubleValues2[5], (Integer) intValues2[5]) ); listBean2.addBean( new SimpleBean(names2[6].toString(), (Double) doubleValues2[6], (Integer) intValues2[6]) ); simpleBean1.setOther(simpleBean2); simpleBean2.setOther(simpleBean3); // simpleBean3.setOther( simpleBean1 ); beanWithList = new BeanWithList("Bean With List", new Double(1976.1202)); beanList.add(simpleBean1); beanList.add(simpleBean2); beanList.add(simpleBean3); listBean1.addBean( simpleBean1 ); listBean1.addBean( simpleBean2 ); listBean1.addBean( simpleBean3 ); Department department = new Department("IT"); for(int i = 0; i < itEmployeeNames.length; i++){ Employee employee = new Employee(itEmployeeNames[i], itAges[i], itPayments[i], itBonuses[i]); employee.setNotes( generateNotes(employee.getName()) ); department.addEmployee( employee ); itEmployees.add( employee ); } itDepartment = department; departments.add( department ); department = new Department("HR"); for(int i = 0; i < hrEmployeeNames.length; i++){ department.addEmployee( new Employee(hrEmployeeNames[i], hrAges[i], hrPayments[i], hrBonuses[i]) ); } departments.add( department ); department = new Department("BA"); for(int i = 0; i < baEmployeeNames.length; i++){ department.addEmployee( new Employee(baEmployeeNames[i], baAges[i], baPayments[i], baBonuses[i]) ); } departments.add( department ); department = new Department("MGR"); for(int i = 0; i < mgrEmployeeNames.length; i++){ department.addEmployee( new Employee(mgrEmployeeNames[i], mgrAges[i], mgrPayments[i], mgrBonuses[i]) ); } mgrDepartment = department; beanWithList.setBeans(beanList); propertyMap.put("${bean.name}", simpleBean1.getName()); propertyMap.put("${bean.doubleValue}", simpleBean1.getDoubleValue()); propertyMap.put("${bean.intValue}", simpleBean1.getIntValue()); propertyMap.put("${bean.dateValue}", simpleBean1.getDateValue()); propertyMap.put("${bean.other.name}", simpleBean1.getOther().getName()); propertyMap.put("${bean.other.intValue}", simpleBean1.getOther().getIntValue()); propertyMap.put("${bean.other.doubleValue}", simpleBean1.getOther().getDoubleValue()); propertyMap.put("${bean.other.dateValue}", simpleBean1.getOther().getDateValue()); propertyMap.put("${listBean.name}", beanWithList.getName()); // propertyMap.put("${listBean.beans.name}", beanWithList.getBeans()); for (int i = 0; i < amounts.length; i++) { int amount = amounts[i]; amountBeans.add( new SimpleBean( amount ) ); } } protected List generateNotes(String name) { Random r = new Random( System.currentTimeMillis() ); int n = 1 + r.nextInt(7); List notes = new ArrayList(); for(int i = 0 ; i < n; i++){ notes.add("Note " + i + " for " + name); } return notes; } Map propertyMap = new HashMap(); public void testSimpleBeanExport() throws IOException, ParsePropertyException { Map beans = new HashMap(); beans.put("bean", simpleBean1); Calendar calendar = Calendar.getInstance(); calendar.set(2006, 8, 19); beans.put("calendar", calendar); InputStream is = new BufferedInputStream(getClass().getResourceAsStream(simpleBeanXLS)); XLSTransformer transformer = new XLSTransformer(); HSSFWorkbook resultWorkbook = transformer.transformXLS(is, beans); is.close(); is = new BufferedInputStream(getClass().getResourceAsStream(simpleBeanXLS)); POIFSFileSystem fs = new POIFSFileSystem(is); HSSFWorkbook sourceWorkbook = new HSSFWorkbook(fs); HSSFSheet sourceSheet = sourceWorkbook.getSheetAt(0); HSSFSheet resultSheet = resultWorkbook.getSheetAt(0); assertEquals("First Row Numbers differ in source and result sheets", sourceSheet.getFirstRowNum(), resultSheet.getFirstRowNum()); assertEquals("Last Row Numbers differ in source and result sheets", sourceSheet.getLastRowNum(), resultSheet.getLastRowNum()); CellsChecker checker = new CellsChecker(propertyMap); propertyMap.put("${calendar}", calendar); checker.checkRows(sourceSheet, resultSheet, 0, 0, 6); is.close(); saveWorkbook(resultWorkbook, simpeBeanDestXLS); } public void testBeanWithListExport() throws IOException, ParsePropertyException { Map beans = new HashMap(); beans.put("listBean", beanWithList); beans.put("beans", beanWithList.getBeans()); InputStream is = new BufferedInputStream(getClass().getResourceAsStream(beanWithListXLS)); XLSTransformer transformer = new XLSTransformer(); HSSFWorkbook resultWorkbook = transformer.transformXLS(is, beans); is.close(); is = new BufferedInputStream(getClass().getResourceAsStream(beanWithListXLS)); POIFSFileSystem fs = new POIFSFileSystem(is); HSSFWorkbook sourceWorkbook = new HSSFWorkbook(fs); HSSFSheet sourceSheet = sourceWorkbook.getSheetAt(0); HSSFSheet resultSheet = resultWorkbook.getSheetAt(0); assertEquals("First Row Numbers differ in source and result sheets", sourceSheet.getFirstRowNum(), resultSheet.getFirstRowNum()); assertEquals("Last Row Number is incorrect", sourceSheet.getLastRowNum() + beanWithList.getBeans().size() - 1, resultSheet.getLastRowNum()); Map listPropMap = new HashMap(); listPropMap.put("${listBean.name}", beanWithList.getName()); CellsChecker checker = new CellsChecker(listPropMap); checker.checkRows(sourceSheet, resultSheet, 0, 0, 3); checker.checkListCells(sourceSheet, 3, resultSheet, 3, (short) 0, names); checker.checkListCells(sourceSheet, 3, resultSheet, 3, (short) 1, doubleValues); checker.checkListCells(sourceSheet, 3, resultSheet, 3, (short) 2, new Object[]{new Integer(123), new Integer(10234), null}); checker.checkListCells(sourceSheet, 3, resultSheet, 3, (short) 3, dateValues); is.close(); saveWorkbook(resultWorkbook, beanWithListDestXLS); } public void testFormulas2() throws IOException { Map beans = new HashMap(); beans.put("departments", departments); InputStream is = new BufferedInputStream(getClass().getResourceAsStream(formulas2XLS)); XLSTransformer transformer = new XLSTransformer(); HSSFWorkbook resultWorkbook = transformer.transformXLS(is, beans); is.close(); saveWorkbook(resultWorkbook, formulasDestXLS); } public void testFormulas() throws IOException, ParsePropertyException { Map beans = new HashMap(); beans.put("listBean", beanWithList); beans.put("departments", departments); beans.put( "t1", amountBeans ); //todo comment this line to work on #VALUE! formula cell problem // simpleBean3.setOther( simpleBean1 ); InputStream is = new BufferedInputStream(getClass().getResourceAsStream(formulasXLS)); XLSTransformer transformer = new XLSTransformer(); HSSFWorkbook resultWorkbook = transformer.transformXLS(is, beans); is.close(); is = new BufferedInputStream(getClass().getResourceAsStream(formulasXLS)); POIFSFileSystem fs = new POIFSFileSystem(is); HSSFWorkbook sourceWorkbook = new HSSFWorkbook(fs); HSSFSheet sourceSheet = sourceWorkbook.getSheetAt(0); HSSFSheet resultSheet = resultWorkbook.getSheetAt(0); assertEquals("First Row Numbers differ in source and result sheets", sourceSheet.getFirstRowNum(), resultSheet.getFirstRowNum()); // assertEquals("Last Row Number is incorrect", sourceSheet.getLastRowNum() + beanWithList.getBeans().size() - 1, resultSheet.getLastRowNum()); Map props = new HashMap(); props.put("${listBean.name}", beanWithList.getName()); CellsChecker checker = new CellsChecker(props); checker.checkRows(sourceSheet, resultSheet, 0, 0, 3); checker.checkListCells(sourceSheet, 3, resultSheet, 3, (short) 0, names); checker.checkListCells(sourceSheet, 3, resultSheet, 3, (short) 1, doubleValues); checker.checkListCells(sourceSheet, 3, resultSheet, 3, (short) 2, new Object[]{new Integer(123), new Integer(10234)}); checker.checkListCells(sourceSheet, 3, resultSheet, 3, (short) 3, dateValues); checker.checkFormulaCell(sourceSheet, 4, resultSheet, 6, (short) 1, "SUM(B4:B6)"); checker.checkFormulaCell(sourceSheet, 4, resultSheet, 6, (short) 2, "SUM(C4:C6)"); checker.checkFormulaCell(sourceSheet, 6, resultSheet, 8, (short) 1, "MAX(B7,C7)"); checker.checkFormulaCell(sourceSheet, 3, resultSheet, 3, (short) 4, "B4+C4"); checker.checkFormulaCell(sourceSheet, 3, resultSheet, 4, (short) 4, "B5+C5"); checker.checkFormulaCell(sourceSheet, 3, resultSheet, 5, (short) 4, "B6+C6"); checker.checkFormulaCell(sourceSheet, 4, resultSheet, 6, (short) 4, "SUM(E4:E6)"); checker.checkFormulaCell( sourceSheet, 8, resultSheet, 10, (short) 1, "SUM(B4:B6)"); checker.checkFormulaCell( sourceSheet, 8, resultSheet, 10, (short) 2, "SUM(C4:C6)"); checker.checkFormulaCell( sourceSheet, 8, resultSheet, 10, (short) 4, "SUM(E4:E6)"); checker.checkFormulaCell(sourceSheet, 10, resultSheet, 12, (short) 1, "MAX(B7,C7)"); checker.checkFormulaCell( sourceSheet, 20, resultSheet, 23, (short)1, "SUM(B19:B23)"); checker.checkFormulaCell( sourceSheet, 20, resultSheet, 32, (short)1, "SUM(B29:B32)"); checker.checkFormulaCell( sourceSheet, 20, resultSheet, 40, (short)1, "SUM(B38:B40)"); checker.checkFormulaCell( sourceSheet, 20, resultSheet, 23, (short)3, "SUM(D19:D23)"); checker.checkFormulaCell( sourceSheet, 20, resultSheet, 32, (short)3, "SUM(D29:D32)"); checker.checkFormulaCell( sourceSheet, 20, resultSheet, 40, (short)3, "SUM(D38:D40)"); checker.checkFormulaCell( sourceSheet, 22, resultSheet, 41, (short)1, "SUM(B24,B33,B41)"); checker.checkFormulaCell( sourceSheet, 22, resultSheet, 41, (short)3, "SUM(D24,D33,D41)"); checker.checkFormulaCell( sourceSheet, 18, resultSheet, 18, (short)3, "B19*(1+C19)"); checker.checkFormulaCell( sourceSheet, 18, resultSheet, 22, (short)3, "B23*(1+C23)"); checker.checkFormulaCell( sourceSheet, 18, resultSheet, 28, (short)3, "B29*(1+C29)"); checker.checkFormulaCell( sourceSheet, 19, resultSheet, 31, (short)3, "B32*(1+C32)"); checker.checkFormulaCell( sourceSheet, 19, resultSheet, 37, (short)3, "B38*(1+C38)"); checker.checkFormulaCell( sourceSheet, 19, resultSheet, 39, (short)3, "B40*(1+C40)"); checker.checkFormulaCell( sourceSheet, 24, resultSheet, 43, (short)1, "'Sheet 2'!B55"); sourceSheet = sourceWorkbook.getSheetAt( 1 ); resultSheet = resultWorkbook.getSheetAt( 1 ); checker.checkFormulaCell( sourceSheet, 0, resultSheet, 0, (short)1, "SUM(Sheet1!B4:B6)"); checker.checkFormulaCell( sourceSheet, 0, resultSheet, 0, (short)2, "SUM(Sheet1!C4:C6)"); checker.checkFormulaCell( sourceSheet, 0, resultSheet, 0, (short)4, "SUM(Sheet1!E4:E6)"); checker.checkFormulaCell( sourceSheet, 2, resultSheet, 2, (short)1, "MAX(Sheet1!B7,Sheet1!C7)"); checker.checkFormulaCell( sourceSheet, 4, resultSheet, 4, (short)1, "Sheet1!B13"); checker.checkFormulaCell( sourceSheet, 15, resultSheet, 24, (short)1, "SUM(B10,B13,B16,B19,B22)"); checker.checkFormulaCell( sourceSheet, 15, resultSheet, 40, (short)1, "SUM(B29,B32,B35,B38)"); checker.checkFormulaCell( sourceSheet, 15, resultSheet, 53, (short)1, "SUM(B45,B48,B51)"); checker.checkFormulaCell( sourceSheet, 18, resultSheet, 55, (short)1, "Sheet1!D24"); checker.checkFormulaCell( sourceSheet, 19, resultSheet, 56, (short)1, "Sheet1!D33"); checker.checkFormulaCell( sourceSheet, 20, resultSheet, 57, (short)1, "Sheet1!D41"); // todo Create checks for "Sheet 3" is.close(); saveWorkbook(resultWorkbook, formulasDestXLS); } public void testMultipleListRows() throws IOException, ParsePropertyException { Map beans = new HashMap(); beans.put("listBean", beanWithList); InputStream is = new BufferedInputStream(getClass().getResourceAsStream(multipleListRowsXLS)); XLSTransformer transformer = new XLSTransformer(); HSSFWorkbook resultWorkbook = transformer.transformXLS(is, beans); is.close(); is = new BufferedInputStream(getClass().getResourceAsStream(multipleListRowsXLS)); POIFSFileSystem fs = new POIFSFileSystem(is); HSSFWorkbook sourceWorkbook = new HSSFWorkbook(fs); HSSFSheet sourceSheet = sourceWorkbook.getSheetAt(0); HSSFSheet resultSheet = resultWorkbook.getSheetAt(0); assertEquals("First Row Numbers differ in source and result sheets", sourceSheet.getFirstRowNum(), resultSheet.getFirstRowNum()); assertEquals("Last Row Number is incorrect", sourceSheet.getLastRowNum() + (beanWithList.getBeans().size() - 1) * 4, resultSheet.getLastRowNum()); Map props = new HashMap(); props.put("${listBean.beans.name}//:3", names[0]); props.put("${listBean.beans.doubleValue}", doubleValues[0]); props.put("${listBean.beans.other.intValue}", simpleBean1.getOther().getIntValue()); props.put("${listBean.beans.dateValue}", dateValues[0]); props.put("//listBean.beans", ""); props.put("Int Value://listBean.beans", "Int Value:"); CellsChecker checker = new CellsChecker(props); checker.checkRows(sourceSheet, resultSheet, 3, 3, 4); props.clear(); props.put("${listBean.beans.name}//:3", names[1]); props.put("${listBean.beans.doubleValue}", doubleValues[1]); props.put("${listBean.beans.other.intValue}", simpleBean2.getOther().getIntValue()); props.put("${listBean.beans.dateValue}", dateValues[1]); props.put("//listBean.beans", ""); props.put("Int Value://listBean.beans", "Int Value:"); checker = new CellsChecker(props); checker.checkRows(sourceSheet, resultSheet, 3, 7, 4); props.clear(); props.put("${listBean.beans.name}//:3", names[2]); props.put("${listBean.beans.doubleValue}", doubleValues[2]); props.put("${listBean.beans.other.intValue}", ""); props.put("${listBean.beans.dateValue}", dateValues[2]); props.put("//listBean.beans", ""); props.put("Int Value://listBean.beans", "Int Value:"); checker = new CellsChecker(props); checker.checkRows(sourceSheet, resultSheet, 3, 11, 4); is.close(); saveWorkbook(resultWorkbook, multipleListRowsDestXLS); } public void testMergedMultipleListRows() throws IOException, ParsePropertyException { Map beans = new HashMap(); beans.put("listBean", beanWithList); InputStream is = new BufferedInputStream(getClass().getResourceAsStream(mergeMultipleListRowsXLS)); XLSTransformer transformer = new XLSTransformer(); HSSFWorkbook resultWorkbook = transformer.transformXLS(is, beans); is.close(); is = new BufferedInputStream(getClass().getResourceAsStream(mergeMultipleListRowsXLS)); POIFSFileSystem fs = new POIFSFileSystem(is); HSSFWorkbook sourceWorkbook = new HSSFWorkbook(fs); HSSFSheet sourceSheet = sourceWorkbook.getSheetAt(0); HSSFSheet resultSheet = resultWorkbook.getSheetAt(0); assertEquals("First Row Numbers differ in source and result sheets", sourceSheet.getFirstRowNum(), resultSheet.getFirstRowNum()); assertEquals("Last Row Number is incorrect", sourceSheet.getLastRowNum() + (beanWithList.getBeans().size() - 1) * 4, resultSheet.getLastRowNum()); Map props = new HashMap(); props.put("${listBean.beans.name}//:3", names[0]); props.put("${listBean.beans.doubleValue}", doubleValues[0]); props.put("${listBean.beans.dateValue}", dateValues[0]); CellsChecker checker = new CellsChecker(props); checker.checkRows(sourceSheet, resultSheet, 3, 3, 4); props.clear(); props.put("${listBean.beans.name}//:3", names[1]); props.put("${listBean.beans.doubleValue}", doubleValues[1]); props.put("${listBean.beans.dateValue}", dateValues[1]); checker = new CellsChecker(props); checker.checkRows(sourceSheet, resultSheet, 3, 7, 4); props.clear(); props.put("${listBean.beans.name}//:3", names[2]); props.put("${listBean.beans.doubleValue}", doubleValues[2]); props.put("${listBean.beans.dateValue}", dateValues[2]); checker = new CellsChecker(props); checker.checkRows(sourceSheet, resultSheet, 3, 11, 4); assertEquals( "Incorrect number of merged regions", 9, resultSheet.getNumMergedRegions() ); assertTrue( "Merged Region not found", isMergedRegion( resultSheet, new Region(3, (short)0, 3, (short)2) ) ); assertTrue( "Merged Region not found", isMergedRegion( resultSheet, new Region(7, (short)0, 7, (short)2) ) ); assertTrue( "Merged Region not found", isMergedRegion( resultSheet, new Region(11, (short)0, 11, (short)2) ) ); assertTrue( "Merged Region not found", isMergedRegion( resultSheet, new Region(4, (short)1, 4, (short)2) ) ); assertTrue( "Merged Region not found", isMergedRegion( resultSheet, new Region(8, (short)1, 8, (short)2) ) ); assertTrue( "Merged Region not found", isMergedRegion( resultSheet, new Region(12, (short)1, 12, (short)2) ) ); assertTrue( "Merged Region not found", isMergedRegion( resultSheet, new Region(5, (short)1, 6, (short)2) ) ); assertTrue( "Merged Region not found", isMergedRegion( resultSheet, new Region(9, (short)1, 10, (short)2) ) ); assertTrue( "Merged Region not found", isMergedRegion( resultSheet, new Region(13, (short)1, 14, (short)2) ) ); is.close(); saveWorkbook(resultWorkbook, mergeMultipleListRowsDestXLS); } public void testGrouping1() throws IOException, ParsePropertyException { BeanWithList beanWithList2 = new BeanWithList("2nd bean with list", new Double(22.22)); List beans2 = new ArrayList(); beans2.add(new SimpleBean("bean 21", new Double(21.21), new Integer(21), new Date())); beans2.add(new SimpleBean("bean 22", new Double(22.22), new Integer(22), new Date())); beanWithList2.setBeans(beans2); BeanWithList beanWithList3 = new BeanWithList("3d bean with list", new Double(333.333)); List beans3 = new ArrayList(); beans3.add(new SimpleBean("bean 31", new Double(31.31), new Integer(31), new Date())); beans3.add(new SimpleBean("bean 32", new Double(32.32), new Integer(32), new Date())); beanWithList3.setBeans(beans3); List mainList = new ArrayList(); mainList.add(beanWithList2); mainList.add(beanWithList3); BeanWithList bean = new BeanWithList("Root", new Double(1111.1111)); bean.setBeans(mainList); Map beans = new HashMap(); beans.put("mainBean", bean); InputStream is = new BufferedInputStream(getClass().getResourceAsStream(grouping1XLS)); XLSTransformer transformer = new XLSTransformer(); HSSFWorkbook resultWorkbook = transformer.transformXLS(is, beans); is.close(); is = new BufferedInputStream(getClass().getResourceAsStream(grouping1XLS)); POIFSFileSystem fs = new POIFSFileSystem(is); HSSFWorkbook sourceWorkbook = new HSSFWorkbook(fs); HSSFSheet sourceSheet = sourceWorkbook.getSheetAt(0); HSSFSheet resultSheet = resultWorkbook.getSheetAt(0); assertEquals("First Row Numbers differ in source and result sheets", sourceSheet.getFirstRowNum(), resultSheet.getFirstRowNum()); assertEquals("Last Row Number is incorrect", sourceSheet.getLastRowNum() + 6, resultSheet.getLastRowNum()); Map props = new HashMap(); props.put("${mainBean.beans.name}//:3", "2nd bean with list"); props.put("${mainBean.beans.beans.name}", "bean 21"); props.put("${mainBean.beans.beans.doubleValue}", new Double(21.21)); props.put("${mainBean.name}", bean.getName()); props.put("Name://mainBean.beans", "Name:"); props.put("${mainBean.name}//mainBean.beans.beans", bean.getName()); CellsChecker checker = new CellsChecker(props); checker.checkRows(sourceSheet, resultSheet, 1, 1, 3); props.clear(); props.put("${mainBean.beans.beans.name}", "bean 22"); props.put("${mainBean.beans.beans.doubleValue}", new Double(22.22)); props.put("${mainBean.name}", bean.getName()); props.put("Name://mainBean.beans", "Name:"); props.put("${mainBean.name}//mainBean.beans.beans", bean.getName()); checker = new CellsChecker(props); checker.checkRows(sourceSheet, resultSheet, 3, 4, 1); checker.checkRows(sourceSheet, resultSheet, 4, 5, 1); props.clear(); props.put("${mainBean.beans.name}//:3", "3d bean with list"); props.put("${mainBean.beans.beans.name}", "bean 31"); props.put("${mainBean.beans.beans.doubleValue}", new Double(31.31)); props.put("${mainBean.name}", bean.getName()); props.put("Name://mainBean.beans", "Name:"); props.put("${mainBean.name}//mainBean.beans.beans", bean.getName()); checker = new CellsChecker(props); checker.checkRows(sourceSheet, resultSheet, 1, 6, 3); props.clear(); props.put("${mainBean.beans.beans.name}", "bean 32"); props.put("${mainBean.beans.beans.doubleValue}", new Double(32.32)); props.put("${mainBean.name}", bean.getName()); props.put("Name://mainBean.beans", "Name:"); props.put("${mainBean.name}//mainBean.beans.beans", bean.getName()); checker = new CellsChecker(props); checker.checkRows(sourceSheet, resultSheet, 3, 9, 1); checker.checkRows(sourceSheet, resultSheet, 4, 10, 1); is.close(); saveWorkbook(resultWorkbook, grouping1DestXLS); } public void testMergeCellsList() throws IOException, ParsePropertyException { Map beans = new HashMap(); beans.put("listBean", beanWithList); InputStream is = new BufferedInputStream(getClass().getResourceAsStream(mergeCellsListXLS)); XLSTransformer transformer = new XLSTransformer(); HSSFWorkbook resultWorkbook = transformer.transformXLS(is, beans); is.close(); is = new BufferedInputStream(getClass().getResourceAsStream(mergeCellsListXLS)); POIFSFileSystem fs = new POIFSFileSystem(is); HSSFWorkbook sourceWorkbook = new HSSFWorkbook(fs); HSSFSheet sourceSheet = sourceWorkbook.getSheetAt(0); HSSFSheet resultSheet = resultWorkbook.getSheetAt(0); assertEquals("First Row Numbers differ in source and result sheets", sourceSheet.getFirstRowNum(), resultSheet.getFirstRowNum()); assertEquals("Last Row Number is incorrect", sourceSheet.getLastRowNum() + beanWithList.getBeans().size() - 1, resultSheet.getLastRowNum()); Map listPropMap = new HashMap(); listPropMap.put("${listBean.name}", beanWithList.getName()); CellsChecker checker = new CellsChecker(listPropMap); checker.checkRows(sourceSheet, resultSheet, 0, 0, 3); checker.checkListCells(sourceSheet, 3, resultSheet, 3, (short) 0, names); checker.checkListCells(sourceSheet, 3, resultSheet, 3, (short) 1, intValues); checker.checkListCells(sourceSheet, 3, resultSheet, 3, (short) 3, doubleValues); assertEquals( "Incorrect number of merged regions", 3, resultSheet.getNumMergedRegions() ); assertTrue( "Merged Region (3,1,3,2) not found", isMergedRegion( resultSheet, new Region(3, (short)1, 3, (short)2) ) ); assertTrue( "Merged Region (4,1,4,2) not found", isMergedRegion( resultSheet, new Region(4, (short)1, 4, (short)2) ) ); assertTrue( "Merged Region (5,1,5,2) not found", isMergedRegion( resultSheet, new Region(5, (short)1, 5, (short)2) ) ); is.close(); saveWorkbook(resultWorkbook, mergeCellsListDestXLS); } protected static boolean isMergedRegion(HSSFSheet sheet, Region region){ for(int i = 0; i < sheet.getNumMergedRegions(); i++){ Region mgdRegion = sheet.getMergedRegionAt( i ); if( mgdRegion.equals( region ) ){ return true; } // log.info("(" + mgdRegion.getRowFrom() + ", " + mgdRegion.getColumnFrom() + ", " + mgdRegion.getRowTo() + ", " + mgdRegion.getColumnTo() + ")"); } return false; } public void testGrouping2() throws IOException, ParsePropertyException { BeanWithList beanWithList2 = new BeanWithList("2nd bean with list", new Double(22.22)); List beans2 = new ArrayList(); beans2.add(new SimpleBean("bean 21", new Double(21.21), new Integer(21), new Date())); beans2.add(new SimpleBean("bean 22", new Double(22.22), new Integer(22), new Date())); beanWithList2.setBeans(beans2); BeanWithList beanWithList3 = new BeanWithList("3d bean with list", new Double(333.333)); List beans3 = new ArrayList(); beans3.add(new SimpleBean("bean 31", new Double(31.31), new Integer(31), new Date())); beans3.add(new SimpleBean("bean 32", new Double(32.32), new Integer(32), new Date())); beanWithList3.setBeans(beans3); List mainList = new ArrayList(); mainList.add(beanWithList2); mainList.add(beanWithList3); BeanWithList bean = new BeanWithList("Root", new Double(1111.1111)); bean.setBeans(mainList); Map beans = new HashMap(); beans.put("mainBean", bean); InputStream is = new BufferedInputStream(getClass().getResourceAsStream(grouping2XLS)); XLSTransformer transformer = new XLSTransformer(); HSSFWorkbook resultWorkbook = transformer.transformXLS(is, beans); is.close(); is = new BufferedInputStream(getClass().getResourceAsStream(grouping2XLS)); POIFSFileSystem fs = new POIFSFileSystem(is); HSSFWorkbook sourceWorkbook = new HSSFWorkbook(fs); HSSFSheet sourceSheet = sourceWorkbook.getSheetAt(0); HSSFSheet resultSheet = resultWorkbook.getSheetAt(0); assertEquals("First Row Numbers differ in source and result sheets", sourceSheet.getFirstRowNum(), resultSheet.getFirstRowNum()); assertEquals("Last Row Number is incorrect", 14, resultSheet.getLastRowNum()); Map props = new HashMap(); props.put("${mainBean.beans.name}//:4", "2nd bean with list"); props.put("${mainBean.beans.beans.name}//:1", "bean 21"); props.put("${mainBean.beans.beans.doubleValue}", new Double(21.21)); props.put("${mainBean.name}//mainBean.beans.beans", bean.getName()); props.put("Name://mainBean.beans", "Name:"); CellsChecker checker = new CellsChecker(props); checker.checkRows(sourceSheet, resultSheet, 1, 1, 4); props.clear(); props.put("${mainBean.beans.beans.name}//:1", "bean 22"); props.put("${mainBean.beans.beans.doubleValue}", new Double(22.22)); props.put("${mainBean.name}//mainBean.beans.beans", bean.getName()); checker = new CellsChecker(props); checker.checkRows(sourceSheet, resultSheet, 3, 5, 3); props.clear(); props.put("${mainBean.beans.name}//:4", "3d bean with list"); props.put("${mainBean.beans.beans.name}//:1", "bean 31"); props.put("${mainBean.beans.beans.doubleValue}", new Double(31.31)); props.put("${mainBean.name}//mainBean.beans.beans", bean.getName()); props.put("Name://mainBean.beans", "Name:"); checker = new CellsChecker(props); checker.checkRows(sourceSheet, resultSheet, 1, 8, 4); props.clear(); props.put("${mainBean.beans.beans.name}//:1", "bean 32"); props.put("${mainBean.beans.beans.doubleValue}", new Double(32.32)); props.put("${mainBean.name}//mainBean.beans.beans", bean.getName()); props.put("Name://mainBean.beans", "Name:"); checker = new CellsChecker(props); checker.checkRows(sourceSheet, resultSheet, 3, 12, 3); is.close(); saveWorkbook(resultWorkbook, grouping2DestXLS); } public void testGrouping3() throws IOException, ParsePropertyException { Map beans = new HashMap(); beans.put("departments", departments); InputStream is = new BufferedInputStream(getClass().getResourceAsStream(grouping3XLS)); XLSTransformer transformer = new XLSTransformer(); HSSFWorkbook resultWorkbook = transformer.transformXLS(is, beans); is.close(); is = new BufferedInputStream(getClass().getResourceAsStream(grouping3XLS)); POIFSFileSystem fs = new POIFSFileSystem(is); HSSFWorkbook sourceWorkbook = new HSSFWorkbook(fs); HSSFSheet sourceSheet = sourceWorkbook.getSheetAt(0); HSSFSheet resultSheet = resultWorkbook.getSheetAt(0); Map props = new HashMap(); props.put("${departments.name}//:4", "IT"); props.put("Department//departments", "Department"); CellsChecker checker = new CellsChecker(props); checker.checkRows(sourceSheet, resultSheet, 0, 0, 3); checker.checkListCells(sourceSheet, 3, resultSheet, 3, (short) 0, itEmployeeNames); checker.checkListCells(sourceSheet, 3, resultSheet, 3, (short) 1, itPayments); checker.checkListCells(sourceSheet, 3, resultSheet, 3, (short) 2, itBonuses); checker.checkFormulaCell( sourceSheet, 3, resultSheet, 3, (short)3, "B4*(1+C4)"); checker.checkFormulaCell( sourceSheet, 3, resultSheet, 4, (short)3, "B5*(1+C5)"); checker.checkFormulaCell( sourceSheet, 3, resultSheet, 7, (short)3, "B8*(1+C8)"); // checker.checkFormulaCell( sourceSheet, 4, resultSheet, 8, (short)1, "SUM(B4:B8)"); // checker.checkFormulaCell( sourceSheet, 4, resultSheet, 6, (short)3, "SUM(D4:D8)"); props.clear(); props.put("${departments.name}//:4", "HR"); props.put("Department//departments", "Department"); checker = new CellsChecker(props); checker.checkRows(sourceSheet, resultSheet, 0, 9, 3); props.clear(); checker.checkListCells(sourceSheet, 3, resultSheet, 12, (short) 0, hrEmployeeNames); checker.checkListCells(sourceSheet, 3, resultSheet, 12, (short) 1, hrPayments); checker.checkListCells(sourceSheet, 3, resultSheet, 12, (short) 2, hrBonuses); checker.checkFormulaCell( sourceSheet, 3, resultSheet, 12, (short)3, "B13*(1+C13)"); checker.checkFormulaCell( sourceSheet, 3, resultSheet, 13, (short)3, "B14*(1+C14)"); checker.checkFormulaCell( sourceSheet, 3, resultSheet, 15, (short)3, "B16*(1+C16)"); // checker.checkFormulaCell( sourceSheet, 4, resultSheet, 16, (short)1, "SUM(B13:B16)"); // checker.checkFormulaCell( sourceSheet, 4, resultSheet, 16, (short)3, "SUM(D13:D16)"); props.clear(); props.put("${departments.name}//:4", "BA"); props.put("Department//departments", "Department"); checker = new CellsChecker(props); checker.checkRows(sourceSheet, resultSheet, 0, 17, 3); props.clear(); checker.checkListCells(sourceSheet, 3, resultSheet, 20, (short) 0, baEmployeeNames); checker.checkListCells(sourceSheet, 3, resultSheet, 20, (short) 1, baPayments); checker.checkListCells(sourceSheet, 3, resultSheet, 20, (short) 2, baBonuses); checker.checkFormulaCell( sourceSheet, 3, resultSheet, 20, (short)3, "B21*(1+C21)"); checker.checkFormulaCell( sourceSheet, 3, resultSheet, 21, (short)3, "B22*(1+C22)"); checker.checkFormulaCell( sourceSheet, 3, resultSheet, 22, (short)3, "B23*(1+C23)"); checker.checkFormulaCell( sourceSheet, 4, resultSheet, 23, (short)1, "SUM(B21:B23)"); checker.checkFormulaCell( sourceSheet, 4, resultSheet, 23, (short)3, "SUM(D21:D23)"); saveWorkbook(resultWorkbook, grouping3DestXLS); } public void testGroupingFormulas() throws IOException, ParsePropertyException { BeanWithList beanWithList2 = new BeanWithList("2nd bean with list", new Double(22.22)); List beans2 = new ArrayList(); beans2.add(new SimpleBean("bean 21", new Double(21.21), new Integer(21), new Date())); beans2.add(new SimpleBean("bean 22", new Double(22.22), new Integer(22), new Date())); beanWithList2.setBeans(beans2); BeanWithList beanWithList3 = new BeanWithList("3d bean with list", new Double(333.333)); List beans3 = new ArrayList(); beans3.add(new SimpleBean("bean 31", new Double(31.31), new Integer(31), new Date())); beans3.add(new SimpleBean("bean 32", new Double(32.32), new Integer(32), new Date())); beanWithList3.setBeans(beans3); List mainList = new ArrayList(); mainList.add(beanWithList2); mainList.add(beanWithList3); BeanWithList bean = new BeanWithList("Root", new Double(1111.1111)); bean.setBeans(mainList); Map beans = new HashMap(); beans.put("mainBean", bean); InputStream is = new BufferedInputStream(getClass().getResourceAsStream(groupingFormulasXLS)); XLSTransformer transformer = new XLSTransformer(); HSSFWorkbook resultWorkbook = transformer.transformXLS(is, beans); is.close(); is = new BufferedInputStream(getClass().getResourceAsStream(groupingFormulasXLS)); POIFSFileSystem fs = new POIFSFileSystem(is); HSSFWorkbook sourceWorkbook = new HSSFWorkbook(fs); is.close(); // HSSFWorkbook resultWorkbook = new HSSFWorkbook( new POIFSFileSystem( new BufferedInputStream(getClass().getResourceAsStream(groupingFormulasDestXLS)))); HSSFSheet sourceSheet = sourceWorkbook.getSheetAt(0); HSSFSheet resultSheet = resultWorkbook.getSheetAt(0); assertEquals("First Row Numbers differ in source and result sheets", sourceSheet.getFirstRowNum(), resultSheet.getFirstRowNum()); assertEquals("Last Row Number is incorrect", sourceSheet.getLastRowNum() + 6, resultSheet.getLastRowNum()); Map props = new HashMap(); props.put("${mainBean.beans.name}//:3", "2nd bean with list"); props.put("${mainBean.beans.beans.name}", "bean 21"); props.put("${mainBean.beans.beans.doubleValue}", new Double(21.21)); props.put("${mainBean.name}//mainBean.beans.beans", bean.getName()); props.put("Name://mainBean.beans", "Name:"); CellsChecker checker = new CellsChecker(props); checker.checkRows(sourceSheet, resultSheet, 1, 1, 3); props.clear(); props.put("${mainBean.beans.beans.name}", "bean 22"); props.put("${mainBean.beans.beans.doubleValue}", new Double(22.22)); props.put("${mainBean.name}//mainBean.beans.beans", bean.getName()); props.put("Name://mainBean.beans", "Name:"); checker = new CellsChecker(props); checker.checkRows(sourceSheet, resultSheet, 3, 4, 1); // Todo: next check requires investigation // Next check currently fails. It seems POI does not get the value of this formula cell correctly. // It returns "SUM(B9:B10)" instead of "SUM(B4:B5)". But in the output XLS file the formula is correct. // checker.checkFormulaCell(sourceSheet, 4, resultSheet, 5, (short)1, "SUM(B4:B5)"); props.clear(); props.put("${mainBean.beans.name}//:3", "3d bean with list"); props.put("${mainBean.beans.beans.name}", "bean 31"); props.put("${mainBean.beans.beans.doubleValue}", new Double(31.31)); props.put("${mainBean.name}//mainBean.beans.beans", bean.getName()); props.put("Name://mainBean.beans", "Name:"); checker = new CellsChecker(props); checker.checkRows(sourceSheet, resultSheet, 1, 6, 3); props.clear(); props.put("${mainBean.beans.beans.name}", "bean 32"); props.put("${mainBean.beans.beans.doubleValue}", new Double(32.32)); props.put("${mainBean.name}//mainBean.beans.beans", bean.getName()); props.put("Name://mainBean.beans", "Name:"); checker = new CellsChecker(props); checker.checkRows(sourceSheet, resultSheet, 3, 9, 1); checker.checkFormulaCell(sourceSheet, 4, resultSheet, 10, (short) 1, "SUM(B9:B10)"); saveWorkbook(resultWorkbook, groupingFormulasDestXLS); } public void testSeveralPropertiesInCell() throws IOException, ParsePropertyException { Map beans = new HashMap(); beans.put("bean", simpleBean1); beans.put("listBean", beanWithList); InputStream is = new BufferedInputStream(getClass().getResourceAsStream(severalPropertiesInCellXLS)); XLSTransformer transformer = new XLSTransformer(); HSSFWorkbook resultWorkbook = transformer.transformXLS(is, beans); is.close(); is = new BufferedInputStream(getClass().getResourceAsStream(severalPropertiesInCellXLS)); POIFSFileSystem fs = new POIFSFileSystem(is); HSSFWorkbook sourceWorkbook = new HSSFWorkbook(fs); HSSFSheet sourceSheet = sourceWorkbook.getSheetAt(0); HSSFSheet resultSheet = resultWorkbook.getSheetAt(0); assertEquals("First Row Numbers differ in source and result sheets", sourceSheet.getFirstRowNum(), resultSheet.getFirstRowNum()); assertEquals("Last Row Number is incorrect", sourceSheet.getLastRowNum() + beanWithList.getBeans().size() - 1, resultSheet.getLastRowNum()); Map props = new HashMap(); props.put("Name: ${bean.name}", "Name: " + simpleBean1.getName()); props.put("${bean.other.name} - ${bean.doubleValue},${bean.other.intValue}", simpleBean1.getOther().getName() + " - " + simpleBean1.getDoubleValue() + "," + simpleBean1.getOther().getIntValue()); props.put("${bean.dateValue}", simpleBean1.getDateValue()); CellsChecker checker = new CellsChecker(props); checker.checkRows(sourceSheet, resultSheet, sourceSheet.getFirstRowNum(), resultSheet.getFirstRowNum(), 6); Map listPropMap = new HashMap(); listPropMap.put("[${listBean.beans.name}]", "[" + beanWithList.getName() + "]"); checker = new CellsChecker(listPropMap); checker.checkListCells(sourceSheet, 6, resultSheet, 6, (short) 0, new String[]{ "[" +((SimpleBean)beanWithList.getBeans().get(0)).getName() + "]", "[" + ((SimpleBean)beanWithList.getBeans().get(1)).getName() + "]", "[" + ((SimpleBean)beanWithList.getBeans().get(2)).getName() + "]" }); checker.checkListCells(sourceSheet, 6, resultSheet, 6, (short) 1, new String[]{((SimpleBean)beanWithList.getBeans().get(0)).getDoubleValue() + " yeah", ((SimpleBean)beanWithList.getBeans().get(1)).getDoubleValue() + " yeah", ((SimpleBean)beanWithList.getBeans().get(2)).getDoubleValue() + " yeah" }); checker.checkListCells(sourceSheet, 6, resultSheet, 6, (short) 2, new String[]{((SimpleBean)beanWithList.getBeans().get(0)).getName() + " : " + ((SimpleBean)beanWithList.getBeans().get(0)).getDoubleValue() + "!", ((SimpleBean)beanWithList.getBeans().get(1)).getName() + " : " + ((SimpleBean)beanWithList.getBeans().get(1)).getDoubleValue() + "!", ((SimpleBean)beanWithList.getBeans().get(2)).getName() + " : " + ((SimpleBean)beanWithList.getBeans().get(2)).getDoubleValue() + "!" }); is.close(); saveWorkbook( resultWorkbook, severalPropertiesInCellDestXLS); } public void testParallelTablesExport() throws IOException, ParsePropertyException { Map beans = new HashMap(); beans.put("listBean", beanWithList); beans.put("bean", simpleBean2); InputStream is = new BufferedInputStream(getClass().getResourceAsStream(parallelTablesXLS)); XLSTransformer transformer = new XLSTransformer(); HSSFWorkbook resultWorkbook = transformer.transformXLS(is, beans); is.close(); is = new BufferedInputStream(getClass().getResourceAsStream(parallelTablesXLS)); POIFSFileSystem fs = new POIFSFileSystem(is); HSSFWorkbook sourceWorkbook = new HSSFWorkbook(fs); HSSFSheet sourceSheet = sourceWorkbook.getSheetAt(0); HSSFSheet resultSheet = resultWorkbook.getSheetAt(0); assertEquals("First Row Numbers differ in source and result sheets", sourceSheet.getFirstRowNum(), resultSheet.getFirstRowNum()); // assertEquals("Last Row Number is incorrect", 11, resultSheet.getLastRowNum()); Map listPropMap = new HashMap(); listPropMap.put("${listBean.name}", beanWithList.getName()); listPropMap.put("Name: ${bean.name}", "Name: " + simpleBean2.getName()); listPropMap.put("${bean.doubleValue}", simpleBean2.getDoubleValue() ); listPropMap.put("Merged - ${bean.intValue}", "Merged - " + simpleBean2.getIntValue() ); listPropMap.put("${bean.intValue}", simpleBean2.getIntValue() ); CellsChecker checker = new CellsChecker(listPropMap); checker.checkRows(sourceSheet, resultSheet, 0, 0, 3); checker.checkListCells(sourceSheet, 3, resultSheet, 3, (short) 2, names); checker.checkListCells(sourceSheet, 3, resultSheet, 3, (short) 3, doubleValues); checker.checkListCells(sourceSheet, 3, resultSheet, 3, (short) 5, intValues); checker.checkFormulaCell(sourceSheet, 3, resultSheet, 3, (short) 4, "D4+F4"); checker.checkFormulaCell(sourceSheet, 4, resultSheet, 4, (short) 4, "D5+F5", true); checker.checkFormulaCell(sourceSheet, 5, resultSheet, 5, (short) 4, "D6+F6", true); checker.checkSection( sourceSheet, resultSheet, 0, 0, (short)0, (short)1, 7, true, true); checker.checkSection( sourceSheet, resultSheet, 0, 0, (short)6, (short)7, 14, true, true); assertEquals( "Incorrect number of merged regions", 2, resultSheet.getNumMergedRegions() ); assertTrue( "Merged Region (4,0,4,1) not found", isMergedRegion( resultSheet, new Region(4, (short)0, 4, (short)1) ) ); assertTrue( "Merged Region (3,6,3,7) not found", isMergedRegion( resultSheet, new Region(3, (short)6, 3, (short)7) ) ); is.close(); saveWorkbook( resultWorkbook, parallelTablesDestXLS); } public void testSeveralListsInRowExport() throws IOException, ParsePropertyException { Map beans = new HashMap(); beans.put("list1", listBean1); beans.put("list2", listBean2); beans.put("bean", simpleBean2); beans.put("staticBean", simpleBean1); InputStream is = new BufferedInputStream(getClass().getResourceAsStream(severalListsInRowXLS)); XLSTransformer transformer = new XLSTransformer(); HSSFWorkbook resultWorkbook = transformer.transformXLS(is, beans); is.close(); is = new BufferedInputStream(getClass().getResourceAsStream(severalListsInRowXLS)); POIFSFileSystem fs = new POIFSFileSystem(is); HSSFWorkbook sourceWorkbook = new HSSFWorkbook(fs); HSSFSheet sourceSheet = sourceWorkbook.getSheetAt(0); HSSFSheet resultSheet = resultWorkbook.getSheetAt(0); assertEquals("First Row Numbers differ in source and result sheets", sourceSheet.getFirstRowNum(), resultSheet.getFirstRowNum()); // assertEquals("Last Row Number is incorrect", 10, resultSheet.getLastRowNum()); Map listPropMap = new HashMap(); listPropMap.put("Name: ${list1.name}", "Name: " + listBean1.getName()); listPropMap.put("Name: ${list2.name}", "Name: " + listBean2.getName()); // static tables check listPropMap.put("Name: ${bean.name}", "Name: " + simpleBean2.getName()); listPropMap.put("${bean.doubleValue}", simpleBean2.getDoubleValue() ); listPropMap.put("Merged - ${bean.intValue}", "Merged - " + simpleBean2.getIntValue() ); listPropMap.put("${bean.intValue}", simpleBean2.getIntValue() ); listPropMap.put("Name: ${staticBean.name}", "Name: " + simpleBean1.getName() ); listPropMap.put("${staticBean.intValue}", simpleBean1.getIntValue() ); listPropMap.put("${staticBean.doubleValue}", simpleBean1.getDoubleValue() ); CellsChecker checker = new CellsChecker(listPropMap); checker.checkRows(sourceSheet, resultSheet, 0, 0, 3); checker.checkSection( sourceSheet, resultSheet, 0, 0, (short)0, (short)1, 7, true, true); checker.checkSection( sourceSheet, resultSheet, 0, 0, (short)7, (short)8, 8, true, true); checker.checkSection( sourceSheet, resultSheet, 0, 0, (short)13, (short)14, 10, true, true); checker.checkListCells(sourceSheet, 3, resultSheet, 3, (short) 2, new String[]{"Name: " + names[0], "Name: " + names[1], "Name: " + names[2]} ); checker.checkListCells(sourceSheet, 3, resultSheet, 3, (short) 3, new String[]{names[0] + " - " + names[0] + " : " + intValues[0], names[1] + " - " + names[1] + " : " + intValues[1],names[2] + " - " + names[2] + " : " + intValues[2] }); checker.checkListCells(sourceSheet, 3, resultSheet, 3, (short) 5, doubleValues); checker.checkListCells(sourceSheet, 3, resultSheet, 3, (short) 12, intValues); // checker.checkFormulaCell(sourceSheet, 3, resultSheet, 3, (short) 6, "F4+M4"); checker.checkFormulaCell(sourceSheet, 4, resultSheet, 4, (short) 6, "F5+M5", true); checker.checkFormulaCell(sourceSheet, 5, resultSheet, 5, (short) 6, "F6+M6", true); checker.checkFormulaCell(sourceSheet, 4, resultSheet, 6, (short) 5, "SUM(F4:F6)"); checker.checkListCells( sourceSheet, 3, resultSheet, 3, (short)10, doubleValues2); checker.checkListCells( sourceSheet, 3, resultSheet, 3, (short)11, intValues2); checker.checkFormulaCell(sourceSheet, 3, resultSheet, 3, (short) 9, "K4+L4"); checker.checkFormulaCell(sourceSheet, 4, resultSheet, 4, (short) 9, "K5+L5", true); checker.checkFormulaCell(sourceSheet, 5, resultSheet, 5, (short) 9, "K6+L6", true); checker.checkFormulaCell(sourceSheet, 4, resultSheet, 10, (short) 9, "SUM(J4:J10)"); checker.checkFormulaCell(sourceSheet, 4, resultSheet, 10, (short) 11, "SUM(L4:L10)"); assertEquals( "Incorrect number of merged regions", 6, resultSheet.getNumMergedRegions() ); assertTrue( "Merged Region (4,0,4,1) not found", isMergedRegion( resultSheet, new Region(4, (short)0, 4, (short)1) ) ); assertTrue( "Merged Region (3,7,3,8) not found", isMergedRegion( resultSheet, new Region(3, (short)7, 3, (short)8) ) ); assertTrue( "Merged Region (3,13,3,14) not found", isMergedRegion( resultSheet, new Region(3, (short)13, 3, (short)14) ) ); assertTrue( "Merged Region (3,3,3,4) not found", isMergedRegion( resultSheet, new Region(3, (short)3, 3, (short)4) ) ); assertTrue( "Merged Region (4,3,4,4) not found", isMergedRegion( resultSheet, new Region(4, (short)3, 4, (short)4) ) ); assertTrue( "Merged Region (5,3,5,4) not found", isMergedRegion( resultSheet, new Region(5, (short)3, 5, (short)4) ) ); is.close(); saveWorkbook( resultWorkbook, severalListsInRowDestXLS ); } public void testFixedSizeCollections() throws IOException, ParsePropertyException { Map beans = new HashMap(); beans.put("employee", itEmployees); InputStream is = new BufferedInputStream(getClass().getResourceAsStream(fixedSizeListXLS)); XLSTransformer transformer = new XLSTransformer(); transformer.markAsFixedSizeCollection( "employee" ); HSSFWorkbook resultWorkbook = transformer.transformXLS(is, beans); is.close(); is = new BufferedInputStream(getClass().getResourceAsStream(fixedSizeListXLS)); POIFSFileSystem fs = new POIFSFileSystem(is); HSSFWorkbook sourceWorkbook = new HSSFWorkbook(fs); HSSFSheet sourceSheet = sourceWorkbook.getSheetAt(0); HSSFSheet resultSheet = resultWorkbook.getSheetAt(0); assertEquals("First Row Numbers differ in source and result sheets", sourceSheet.getFirstRowNum(), resultSheet.getFirstRowNum()); assertEquals("Last Row Number is incorrect", sourceSheet.getLastRowNum(), resultSheet.getLastRowNum()); Map props = new HashMap(); CellsChecker checker; checker = new CellsChecker(props); checker.checkRows(sourceSheet, resultSheet, 0, 0, 2); checker.checkFixedListCells( sourceSheet, 2, resultSheet, 2, (short)0, itEmployeeNames); checker.checkFixedListCells( sourceSheet, 2, resultSheet, 2, (short)1, itPayments); checker.checkFixedListCells( sourceSheet, 2, resultSheet, 2, (short)2, itBonuses); is.close(); saveWorkbook(resultWorkbook, fixedSizeListDestXLS); } public void testExpressions1() throws IOException, ParsePropertyException { Map beans = new HashMap(); beans.put("bean", simpleBean1); beans.put("listBean", beanWithList); InputStream is = new BufferedInputStream(getClass().getResourceAsStream(expressions1XLS)); XLSTransformer transformer = new XLSTransformer(); HSSFWorkbook resultWorkbook = transformer.transformXLS(is, beans); is.close(); is = new BufferedInputStream(getClass().getResourceAsStream(expressions1XLS)); POIFSFileSystem fs = new POIFSFileSystem(is); HSSFWorkbook sourceWorkbook = new HSSFWorkbook(fs); HSSFSheet sourceSheet = sourceWorkbook.getSheetAt(0); HSSFSheet resultSheet = resultWorkbook.getSheetAt(0); assertEquals("First Row Numbers differ in source and result sheets", sourceSheet.getFirstRowNum(), resultSheet.getFirstRowNum()); assertEquals("Last Row Number is incorrect", sourceSheet.getLastRowNum() + beanWithList.getBeans().size() - 1, resultSheet.getLastRowNum()); Map props = new HashMap(); props.put("Name: ${bean.name}", "Name: " + simpleBean1.getName()); props.put("${bean.other.name} - ${bean.doubleValue*2},${(bean.other.intValue + bean.doubleValue)/0.5}", simpleBean1.getOther().getName() + " - " + simpleBean1.getDoubleValue().doubleValue()*2 + "," + (simpleBean1.getOther().getIntValue().intValue() + simpleBean1.getDoubleValue().doubleValue())/0.5); props.put("${10*bean.doubleValue + 2.55}", new Double(simpleBean1.getDoubleValue().doubleValue() * 10 + 2.55)); CellsChecker checker = new CellsChecker(props); checker.checkRows(sourceSheet, resultSheet, sourceSheet.getFirstRowNum(), resultSheet.getFirstRowNum(), 6); Map listPropMap = new HashMap(); listPropMap.put("[${listBean.beans.name}]", "[" + beanWithList.getName() + "]"); checker = new CellsChecker(listPropMap); checker.checkListCells(sourceSheet, 6, resultSheet, 6, (short) 0, new String[]{ "[" +((SimpleBean)beanWithList.getBeans().get(0)).getName() + "]", "[" + ((SimpleBean)beanWithList.getBeans().get(1)).getName() + "]", "[" + ((SimpleBean)beanWithList.getBeans().get(2)).getName() + "]" }); checker.checkListCells(sourceSheet, 6, resultSheet, 6, (short) 1, new String[]{(((SimpleBean)beanWithList.getBeans().get(0)).getDoubleValue().doubleValue()*10.2)/10 + 1.567 + " yeah", (((SimpleBean)beanWithList.getBeans().get(1)).getDoubleValue().doubleValue()*10.2)/10 + 1.567 + " yeah", (((SimpleBean)beanWithList.getBeans().get(2)).getDoubleValue().doubleValue()*10.2)/10 + 1.567 + " yeah" }); checker.checkListCells(sourceSheet, 6, resultSheet, 6, (short) 2, new String[]{((SimpleBean)beanWithList.getBeans().get(0)).getDoubleValue().doubleValue() + ((SimpleBean)beanWithList.getBeans().get(0)).getIntValue().intValue()*2.1 + " - " + (((SimpleBean)beanWithList.getBeans().get(0)).getIntValue().intValue()*(10 + 1.1)), ((SimpleBean)beanWithList.getBeans().get(1)).getDoubleValue().doubleValue() + ((SimpleBean)beanWithList.getBeans().get(1)).getIntValue().intValue()*2.1 + " - " + (((SimpleBean)beanWithList.getBeans().get(1)).getIntValue().intValue()*(10 + 1.1)), ((SimpleBean)beanWithList.getBeans().get(2)).getDoubleValue().doubleValue() + ((SimpleBean)beanWithList.getBeans().get(2)).getIntValue().intValue()*2.1 + " - " + (((SimpleBean)beanWithList.getBeans().get(2)).getIntValue().intValue()*(10 + 1.1))}); is.close(); saveWorkbook( resultWorkbook, expressions1DestXLS); } public void testIfTag() throws IOException, ParsePropertyException { Map beans = new HashMap(); BeanWithList listBean = new BeanWithList("Main bean", new Double(10.0)); listBean.addBean(simpleBean1); listBean.addBean(simpleBean2); listBean.addBean(simpleBean3); beans.put("bean", simpleBean1); beans.put("listBean", listBean); InputStream is = new BufferedInputStream(getClass().getResourceAsStream(iftagXLS)); XLSTransformer transformer = new XLSTransformer(); HSSFWorkbook resultWorkbook = transformer.transformXLS(is, beans); is.close(); is = new BufferedInputStream(getClass().getResourceAsStream(iftagXLS)); POIFSFileSystem fs = new POIFSFileSystem(is); HSSFWorkbook sourceWorkbook = new HSSFWorkbook(fs); HSSFSheet sourceSheet = sourceWorkbook.getSheetAt(0); HSSFSheet resultSheet = resultWorkbook.getSheetAt(0); assertEquals("First Row Numbers differ in source and result sheets", sourceSheet.getFirstRowNum(), resultSheet.getFirstRowNum()); // assertEquals("Last Row Number is incorrect", 11, resultSheet.getLastRowNum()); Map props = new HashMap(); props.put( "${listBean.name}", listBean.getName()); props.put( "${listBean.doubleValue}", listBean.getDoubleValue()); CellsChecker checker = new CellsChecker(props); checker.checkRows( sourceSheet, resultSheet, 4, 3, 1); checker.checkRows( sourceSheet, resultSheet, 4, 6, 1); checker.checkRows( sourceSheet, resultSheet, 4, 8, 1); checker.checkRows( sourceSheet, resultSheet, 8, 5, 1); checker.checkRows( sourceSheet, resultSheet, 8, 7, 1); checker.checkRows( sourceSheet, resultSheet, 8, 10, 1); props.clear(); props.put("${sb.name}",names[0]); props.put("${sb.doubleValue}",doubleValues[0]); checker.checkRows( sourceSheet, resultSheet, 6, 4, 1); props.clear(); props.put("${sb.name}",names[2]); props.put("${sb.doubleValue}",doubleValues[2]); checker.checkRows( sourceSheet, resultSheet, 6, 9, 1); is.close(); saveWorkbook( resultWorkbook, iftagDestXLS); } public void testForIfTag2() throws IOException, ParsePropertyException { Map beans = new HashMap(); beans.put( "departments", departments ); beans.put("depUrl", "http://www.somesite.com"); Configuration config = new Configuration(); config.setMetaInfoToken("\\\\"); InputStream is = new BufferedInputStream(getClass().getResourceAsStream(forifTag2XLS)); XLSTransformer transformer = new XLSTransformer( config ); HSSFWorkbook resultWorkbook = transformer.transformXLS(is, beans); is.close(); is = new BufferedInputStream(getClass().getResourceAsStream(forifTag2XLS)); POIFSFileSystem fs = new POIFSFileSystem(is); HSSFWorkbook sourceWorkbook = new HSSFWorkbook(fs); HSSFSheet sourceSheet = sourceWorkbook.getSheetAt(0); HSSFSheet resultSheet = resultWorkbook.getSheetAt(0); assertEquals("First Row Numbers differ in source and result sheets", sourceSheet.getFirstRowNum(), resultSheet.getFirstRowNum()); // assertEquals("Last Row Number is incorrect", 11, resultSheet.getLastRowNum()); Map props = new HashMap(); props.put("${department.name}", "IT"); props.put("${depUrl}", "http://www.somesite.com"); CellsChecker checker = new CellsChecker(props); checker.checkRows(sourceSheet, resultSheet, 1, 0, 3); checker.checkListCells(sourceSheet, 5, resultSheet, 3, (short) 0, itEmployeeNames); checker.checkListCells(sourceSheet, 5, resultSheet, 3, (short) 1, itPayments); checker.checkListCells(sourceSheet, 5, resultSheet, 3, (short) 2, itBonuses); //todo: checker.checkFormulaCell( sourceSheet, 3, resultSheet, 3, (short)3, "B4*(1+C4)"); //todo: checker.checkFormulaCell( sourceSheet, 3, resultSheet, 4, (short)3, "B5*(1+C5)"); //todo: checker.checkFormulaCell( sourceSheet, 3, resultSheet, 7, (short)3, "B8*(1+C8)"); // checker.checkFormulaCell( sourceSheet, 4, resultSheet, 8, (short)1, "SUM(B4:B8)"); // checker.checkFormulaCell( sourceSheet, 4, resultSheet, 6, (short)3, "SUM(D4:D8)"); props.clear(); props.put("${department.name}", "HR"); props.put("${depUrl}", "http://www.somesite.com"); checker = new CellsChecker(props); checker.checkRows(sourceSheet, resultSheet, 1, 9, 3); props.clear(); checker.checkListCells(sourceSheet, 5, resultSheet, 12, (short) 0, hrEmployeeNames); checker.checkListCells(sourceSheet, 5, resultSheet, 12, (short) 1, hrPayments); checker.checkListCells(sourceSheet, 5, resultSheet, 12, (short) 2, hrBonuses); //todo checker.checkFormulaCell( sourceSheet, 3, resultSheet, 12, (short)3, "B13*(1+C13)"); //todo checker.checkFormulaCell( sourceSheet, 3, resultSheet, 13, (short)3, "B14*(1+C14)"); //todo checker.checkFormulaCell( sourceSheet, 3, resultSheet, 15, (short)3, "B16*(1+C16)"); // checker.checkFormulaCell( sourceSheet, 4, resultSheet, 16, (short)1, "SUM(B13:B16)"); // checker.checkFormulaCell( sourceSheet, 4, resultSheet, 16, (short)3, "SUM(D13:D16)"); props.clear(); props.put("${department.name}", "BA"); props.put("${depUrl}", "http://www.somesite.com"); checker = new CellsChecker(props); checker.checkRows(sourceSheet, resultSheet, 1, 17, 3); props.clear(); checker.checkListCells(sourceSheet, 5, resultSheet, 20, (short) 0, baEmployeeNames); checker.checkListCells(sourceSheet, 5, resultSheet, 20, (short) 1, baPayments); checker.checkListCells(sourceSheet, 5, resultSheet, 20, (short) 2, baBonuses); //todo: // checker.checkFormulaCell( sourceSheet, 3, resultSheet, 20, (short)3, "B21*(1+C21)"); // checker.checkFormulaCell( sourceSheet, 3, resultSheet, 21, (short)3, "B22*(1+C22)"); // checker.checkFormulaCell( sourceSheet, 3, resultSheet, 22, (short)3, "B23*(1+C23)"); // checker.checkFormulaCell( sourceSheet, 4, resultSheet, 23, (short)1, "SUM(B21:B23)"); // checker.checkFormulaCell( sourceSheet, 4, resultSheet, 23, (short)3, "SUM(D21:D23)"); is.close(); saveWorkbook( resultWorkbook, forifTag2DestXLS); } public void testForIfTag3() throws IOException, ParsePropertyException { Map beans = new HashMap(); beans.put( "departments", departments ); beans.put("depUrl", "http://www.somesite.com"); List deps = new ArrayList(); Department testDep = new Department("Test"); deps.add( testDep ); beans.put( "deps", deps ); List employees = new ArrayList(); beans.put("employees", employees); Configuration config = new Configuration(); config.setMetaInfoToken("\\\\"); InputStream is = new BufferedInputStream(getClass().getResourceAsStream(forifTag3XLS)); XLSTransformer transformer = new XLSTransformer( config ); HSSFWorkbook resultWorkbook = transformer.transformXLS(is, beans); is.close(); is = new BufferedInputStream(getClass().getResourceAsStream(forifTag3XLS)); POIFSFileSystem fs = new POIFSFileSystem(is); HSSFWorkbook sourceWorkbook = new HSSFWorkbook(fs); HSSFSheet sourceSheet = sourceWorkbook.getSheetAt(0); HSSFSheet resultSheet = resultWorkbook.getSheetAt(0); assertEquals("First Row Numbers differ in source and result sheets", sourceSheet.getFirstRowNum(), resultSheet.getFirstRowNum()); assertEquals("Last Row Number is incorrect", 54, resultSheet.getLastRowNum()); // check 1st forEach loop output Map props = new HashMap(); CellsChecker checker = new CellsChecker(props); props.put("${department.name}", "IT"); checker.checkRows(sourceSheet, resultSheet, 1, 0, 3); props.put("${department.name}", "HR"); checker.checkRows(sourceSheet, resultSheet, 1, 4, 3); props.put("${department.name}", "BA"); checker.checkRows(sourceSheet, resultSheet, 1, 8, 3); checker.checkRows(sourceSheet, resultSheet, 11, 3, 1); checker.checkRows(sourceSheet, resultSheet, 11, 7, 1); checker.checkRows(sourceSheet, resultSheet, 11, 11, 1); // check 2nd forEach loop output props.put("${department.name}", "IT"); checker.checkRows(sourceSheet, resultSheet, 1, 12, 3); checker.checkListCells( sourceSheet, 19, resultSheet, 15, (short)0, new String[]{"Oleg", "Neil", "John"}); checker.checkListCells( sourceSheet, 19, resultSheet, 15, (short)1, new Double[]{new Double(2300), new Double(2500), new Double(2800)}); checker.checkListCells( sourceSheet, 19, resultSheet, 15, (short)2, new Double[]{new Double(0.25), new Double(0.00), new Double(0.20)}); checker.checkRows(sourceSheet, resultSheet, 11, 18, 1); props.put("${department.name}", "HR"); checker.checkRows(sourceSheet, resultSheet, 1, 19, 3); checker.checkListCells( sourceSheet, 19, resultSheet, 22, (short)0, new String[]{"Helen"}); checker.checkListCells( sourceSheet, 19, resultSheet, 22, (short)1, new Double[]{new Double(2100)}); checker.checkListCells( sourceSheet, 19, resultSheet, 22, (short)2, new Double[]{new Double(0.10)}); checker.checkRows(sourceSheet, resultSheet, 11, 23, 1); props.put("${department.name}", "BA"); checker.checkRows(sourceSheet, resultSheet, 1, 24, 3); checker.checkListCells( sourceSheet, 19, resultSheet, 27, (short)0, new String[]{"Denise", "LeAnn", "Natali"}); checker.checkListCells( sourceSheet, 19, resultSheet, 27, (short)1, new Double[]{new Double(2400), new Double(2200), new Double(2600)}); checker.checkListCells( sourceSheet, 19, resultSheet, 27, (short)2, new Double[]{new Double(0.20),new Double(0.15),new Double(0.10)}); checker.checkRows(sourceSheet, resultSheet, 11, 30, 1); // check 3rd forEach loop output props.put("${department.name}", "IT"); checker.checkRows(sourceSheet, resultSheet, 14, 12, 3); checker.checkListCells( sourceSheet, 19, resultSheet, 15, (short)0, new String[]{"Oleg", "Neil", "John"}); checker.checkListCells( sourceSheet, 19, resultSheet, 15, (short)1, new Double[]{new Double(2300), new Double(2500), new Double(2800)}); checker.checkListCells( sourceSheet, 19, resultSheet, 15, (short)2, new Double[]{new Double(0.25), new Double(0.00), new Double(0.20)}); checker.checkRows(sourceSheet, resultSheet, 22, 18, 1); props.put("${department.name}", "HR"); checker.checkRows(sourceSheet, resultSheet, 14, 19, 3); checker.checkListCells( sourceSheet, 19, resultSheet, 22, (short)0, new String[]{"Helen"}); checker.checkListCells( sourceSheet, 19, resultSheet, 22, (short)1, new Double[]{new Double(2100)}); checker.checkListCells( sourceSheet, 19, resultSheet, 22, (short)2, new Double[]{new Double(0.10)}); checker.checkRows(sourceSheet, resultSheet, 22, 23, 1); props.put("${department.name}", "BA"); checker.checkRows(sourceSheet, resultSheet, 14, 24, 3); checker.checkListCells( sourceSheet, 19, resultSheet, 27, (short)0, new String[]{"Denise", "LeAnn", "Natali"}); checker.checkListCells( sourceSheet, 19, resultSheet, 27, (short)1, new Double[]{new Double(2400), new Double(2200), new Double(2600)}); checker.checkListCells( sourceSheet, 19, resultSheet, 27, (short)2, new Double[]{new Double(0.20),new Double(0.15),new Double(0.10)}); checker.checkRows(sourceSheet, resultSheet, 22, 30, 1); // check 3rd forEach loop output props.put("${department.name}", "IT"); checker.checkRows(sourceSheet, resultSheet, 25, 31, 3); checker.checkListCells( sourceSheet, 29, resultSheet, 34, (short)0, itEmployeeNames); checker.checkListCells( sourceSheet, 29, resultSheet, 34, (short)1, itPayments); checker.checkListCells( sourceSheet, 29, resultSheet, 34, (short)2, itBonuses); checker.checkRows(sourceSheet, resultSheet, 31, 18, 1); props.put("${department.name}", "HR"); checker.checkRows(sourceSheet, resultSheet, 25, 40, 3); checker.checkListCells( sourceSheet, 29, resultSheet, 43, (short)0, hrEmployeeNames); checker.checkListCells( sourceSheet, 29, resultSheet, 43, (short)1, hrPayments); checker.checkListCells( sourceSheet, 29, resultSheet, 43, (short)2, hrBonuses); checker.checkRows(sourceSheet, resultSheet, 31, 23, 1); props.put("${department.name}", "BA"); checker.checkRows(sourceSheet, resultSheet, 25, 48, 3); checker.checkListCells( sourceSheet, 29, resultSheet, 51, (short)0, baEmployeeNames); checker.checkListCells( sourceSheet, 29, resultSheet, 51, (short)1, baPayments); checker.checkListCells( sourceSheet, 29, resultSheet, 51, (short)2, baBonuses); checker.checkRows(sourceSheet, resultSheet, 31, 30, 1); sourceSheet = sourceWorkbook.getSheetAt( 1 ); resultSheet = resultWorkbook.getSheetAt( 1 ); assertEquals("Number of rows on Sheet 2 is not correct", 1, resultSheet.getLastRowNum() + 1); checker.setIgnoreFirstLastCellNums( true ); checker.checkRows( sourceSheet, resultSheet, 11, 0, 1); is.close(); saveWorkbook( resultWorkbook, forifTag3DestXLS); } public void testForIfTag3OutTag() throws IOException, ParsePropertyException { Map beans = new HashMap(); beans.put( "departments", departments ); beans.put("depUrl", "http://www.somesite.com"); List deps = new ArrayList(); Department testDep = new Department("Test"); deps.add( testDep ); beans.put( "deps", deps ); List employees = new ArrayList(); beans.put("employees", employees); Configuration config = new Configuration(); config.setMetaInfoToken("\\\\"); InputStream is = new BufferedInputStream(getClass().getResourceAsStream(forifTag3OutTagXLS)); XLSTransformer transformer = new XLSTransformer( config ); HSSFWorkbook resultWorkbook = transformer.transformXLS(is, beans); is.close(); is = new BufferedInputStream(getClass().getResourceAsStream(forifTag3OutTagXLS)); POIFSFileSystem fs = new POIFSFileSystem(is); HSSFWorkbook sourceWorkbook = new HSSFWorkbook(fs); HSSFSheet sourceSheet = sourceWorkbook.getSheetAt(0); HSSFSheet resultSheet = resultWorkbook.getSheetAt(0); assertEquals("First Row Numbers differ in source and result sheets", sourceSheet.getFirstRowNum(), resultSheet.getFirstRowNum()); assertEquals("Last Row Number is incorrect", 54, resultSheet.getLastRowNum()); // check 1st forEach loop output Map props = new HashMap(); CellsChecker checker = new CellsChecker(props); props.put("${department.name}", "IT"); checker.checkRows(sourceSheet, resultSheet, 1, 0, 3); props.put("${department.name}", "HR"); checker.checkRows(sourceSheet, resultSheet, 1, 4, 3); props.put("${department.name}", "BA"); checker.checkRows(sourceSheet, resultSheet, 1, 8, 3); checker.checkRows(sourceSheet, resultSheet, 11, 3, 1); checker.checkRows(sourceSheet, resultSheet, 11, 7, 1); checker.checkRows(sourceSheet, resultSheet, 11, 11, 1); // check 2nd forEach loop output props.put("${department.name}", "IT"); checker.checkRows(sourceSheet, resultSheet, 1, 12, 3); checker.checkListCells( sourceSheet, 19, resultSheet, 15, (short)0, new String[]{"Oleg", "Neil", "John"}); checker.checkListCells( sourceSheet, 19, resultSheet, 15, (short)1, new Double[]{new Double(2300), new Double(2500), new Double(2800)}); checker.checkListCells( sourceSheet, 19, resultSheet, 15, (short)2, new Double[]{new Double(0.25), new Double(0.00), new Double(0.20)}); checker.checkRows(sourceSheet, resultSheet, 11, 18, 1); props.put("${department.name}", "HR"); checker.checkRows(sourceSheet, resultSheet, 1, 19, 3); checker.checkListCells( sourceSheet, 19, resultSheet, 22, (short)0, new String[]{"Helen"}); checker.checkListCells( sourceSheet, 19, resultSheet, 22, (short)1, new Double[]{new Double(2100)}); checker.checkListCells( sourceSheet, 19, resultSheet, 22, (short)2, new Double[]{new Double(0.10)}); checker.checkRows(sourceSheet, resultSheet, 11, 23, 1); props.put("${department.name}", "BA"); checker.checkRows(sourceSheet, resultSheet, 1, 24, 3); checker.checkListCells( sourceSheet, 19, resultSheet, 27, (short)0, new String[]{"Denise", "LeAnn", "Natali"}); checker.checkListCells( sourceSheet, 19, resultSheet, 27, (short)1, new Double[]{new Double(2400), new Double(2200), new Double(2600)}); checker.checkListCells( sourceSheet, 19, resultSheet, 27, (short)2, new Double[]{new Double(0.20),new Double(0.15),new Double(0.10)}); checker.checkRows(sourceSheet, resultSheet, 11, 30, 1); // check 3rd forEach loop output props.put("${department.name}", "IT"); checker.checkRows(sourceSheet, resultSheet, 14, 12, 3); checker.checkListCells( sourceSheet, 19, resultSheet, 15, (short)0, new String[]{"Oleg", "Neil", "John"}); checker.checkListCells( sourceSheet, 19, resultSheet, 15, (short)1, new Double[]{new Double(2300), new Double(2500), new Double(2800)}); checker.checkListCells( sourceSheet, 19, resultSheet, 15, (short)2, new Double[]{new Double(0.25), new Double(0.00), new Double(0.20)}); checker.checkRows(sourceSheet, resultSheet, 22, 18, 1); props.put("${department.name}", "HR"); checker.checkRows(sourceSheet, resultSheet, 14, 19, 3); checker.checkListCells( sourceSheet, 19, resultSheet, 22, (short)0, new String[]{"Helen"}); checker.checkListCells( sourceSheet, 19, resultSheet, 22, (short)1, new Double[]{new Double(2100)}); checker.checkListCells( sourceSheet, 19, resultSheet, 22, (short)2, new Double[]{new Double(0.10)}); checker.checkRows(sourceSheet, resultSheet, 22, 23, 1); props.put("${department.name}", "BA"); checker.checkRows(sourceSheet, resultSheet, 14, 24, 3); checker.checkListCells( sourceSheet, 19, resultSheet, 27, (short)0, new String[]{"Denise", "LeAnn", "Natali"}); checker.checkListCells( sourceSheet, 19, resultSheet, 27, (short)1, new Double[]{new Double(2400), new Double(2200), new Double(2600)}); checker.checkListCells( sourceSheet, 19, resultSheet, 27, (short)2, new Double[]{new Double(0.20),new Double(0.15),new Double(0.10)}); checker.checkRows(sourceSheet, resultSheet, 22, 30, 1); // check 3rd forEach loop output props.put("${department.name}", "IT"); checker.checkRows(sourceSheet, resultSheet, 25, 31, 3); checker.checkListCells( sourceSheet, 29, resultSheet, 34, (short)0, itEmployeeNames); checker.checkListCells( sourceSheet, 29, resultSheet, 34, (short)1, itPayments); checker.checkListCells( sourceSheet, 29, resultSheet, 34, (short)2, itBonuses); checker.checkRows(sourceSheet, resultSheet, 31, 18, 1); props.put("${department.name}", "HR"); checker.checkRows(sourceSheet, resultSheet, 25, 40, 3); checker.checkListCells( sourceSheet, 29, resultSheet, 43, (short)0, hrEmployeeNames); checker.checkListCells( sourceSheet, 29, resultSheet, 43, (short)1, hrPayments); checker.checkListCells( sourceSheet, 29, resultSheet, 43, (short)2, hrBonuses); checker.checkRows(sourceSheet, resultSheet, 31, 23, 1); props.put("${department.name}", "BA"); checker.checkRows(sourceSheet, resultSheet, 25, 48, 3); checker.checkListCells( sourceSheet, 29, resultSheet, 51, (short)0, baEmployeeNames); checker.checkListCells( sourceSheet, 29, resultSheet, 51, (short)1, baPayments); checker.checkListCells( sourceSheet, 29, resultSheet, 51, (short)2, baBonuses); checker.checkRows(sourceSheet, resultSheet, 31, 30, 1); sourceSheet = sourceWorkbook.getSheetAt( 1 ); resultSheet = resultWorkbook.getSheetAt( 1 ); assertEquals("Number of rows on Sheet 2 is not correct", 1, resultSheet.getLastRowNum() + 1); checker.setIgnoreFirstLastCellNums( true ); checker.checkRows( sourceSheet, resultSheet, 11, 0, 1); is.close(); saveWorkbook( resultWorkbook, forifTag3OutTagDestXLS); } public void testEmptyBeansExport() throws IOException, ParsePropertyException { Map beans = new HashMap(); BeanWithList listBean = new BeanWithList("Main bean", new Double(10.0)); beans.put("bean", simpleBean1); beans.put("listBean", listBean); InputStream is = new BufferedInputStream(getClass().getResourceAsStream(emptyBeansXLS)); XLSTransformer transformer = new XLSTransformer(); HSSFWorkbook resultWorkbook = transformer.transformXLS(is, beans); is.close(); is = new BufferedInputStream(getClass().getResourceAsStream(emptyBeansXLS)); POIFSFileSystem fs = new POIFSFileSystem(is); HSSFWorkbook sourceWorkbook = new HSSFWorkbook(fs); HSSFSheet sourceSheet = sourceWorkbook.getSheetAt(0); HSSFSheet resultSheet = resultWorkbook.getSheetAt(0); assertEquals("First Row Numbers differ in source and result sheets", sourceSheet.getFirstRowNum(), resultSheet.getFirstRowNum()); assertEquals("Last Row Number is incorrect", sourceSheet.getLastRowNum(), resultSheet.getLastRowNum()); Map props = new HashMap(); props.put("${listBean.name}", listBean.getName()); CellsChecker checker = new CellsChecker(props); checker.checkRows(sourceSheet, resultSheet, 0, 0, 3); is.close(); saveWorkbook( resultWorkbook, emptyBeansDestXLS ); } public void testListOfStringsExport() throws IOException, ParsePropertyException { Map beans = new HashMap(); beans.put("employee", itEmployees.get(0)); beans.put("employees", itEmployees); InputStream is = new BufferedInputStream(getClass().getResourceAsStream(employeeNotesXLS)); XLSTransformer transformer = new XLSTransformer(); HSSFWorkbook resultWorkbook = transformer.transformXLS(is, beans); is.close(); is = new BufferedInputStream(getClass().getResourceAsStream(employeeNotesXLS)); POIFSFileSystem fs = new POIFSFileSystem(is); HSSFWorkbook sourceWorkbook = new HSSFWorkbook(fs); HSSFSheet sourceSheet = sourceWorkbook.getSheetAt(0); HSSFSheet resultSheet = resultWorkbook.getSheetAt(0); Map props = new HashMap(); CellsChecker checker = new CellsChecker(props); checker.checkListCells( sourceSheet, 2, resultSheet, 2, (short)1, ((Employee)itEmployees.get(0)).getNotes().toArray() ); is.close(); saveWorkbook(resultWorkbook, employeeNotesDestXLS); } public void testVarStatusAttrInForEach() throws IOException, ParsePropertyException { Map beans = new HashMap(); beans.put("employees", itEmployees); InputStream is = new BufferedInputStream(getClass().getResourceAsStream( varStatusXLS )); XLSTransformer transformer = new XLSTransformer(); HSSFWorkbook resultWorkbook = transformer.transformXLS(is, beans); is.close(); is = new BufferedInputStream(getClass().getResourceAsStream(varStatusXLS)); POIFSFileSystem fs = new POIFSFileSystem(is); HSSFWorkbook sourceWorkbook = new HSSFWorkbook(fs); HSSFSheet sourceSheet = sourceWorkbook.getSheetAt(0); HSSFSheet resultSheet = resultWorkbook.getSheetAt(0); Map props = new HashMap(); CellsChecker checker = new CellsChecker(props); checker.checkListCells( sourceSheet, 3, resultSheet, 2, (short)0, new Object[]{ new Integer(0), new Integer(1), new Integer(2), new Integer(3), new Integer(4)} ); is.close(); saveWorkbook(resultWorkbook, varStatusDestXLS); } /* * This sample demonstrates a problem with formulas applied to jx:forEach tag * values nested in jx:outline tag. Basically jx:outline rows are removed during transformation * so as a result for the formula we have something like this: SUM(B3;B4;B5;B6;B7) * This restricts usage of formulas in this case becase the number of values passed to the formulas * in this way is restricted by Excel. So logically we need to transform formulas arguments * into a range like B3:B7. This is not currently possible with jXLS * TODO: fix this issue with formulas in the future */ public void atestOutlineInForEach() throws IOException, ParsePropertyException { Map beans = new HashMap(); beans.put("employees", itEmployees); InputStream is = new BufferedInputStream(getClass().getResourceAsStream( outlineXLS )); XLSTransformer transformer = new XLSTransformer(); HSSFWorkbook resultWorkbook = transformer.transformXLS(is, beans); is.close(); // is = new BufferedInputStream(getClass().getResourceAsStream(outlineXLS)); // POIFSFileSystem fs = new POIFSFileSystem(is); // HSSFWorkbook sourceWorkbook = new HSSFWorkbook(fs); // HSSFSheet sourceSheet = sourceWorkbook.getSheetAt(0); // HSSFSheet resultSheet = resultWorkbook.getSheetAt(0); // Map props = new HashMap(); // CellsChecker checker = new CellsChecker(props); // checker.checkListCells( sourceSheet, 3, resultSheet, 2, (short)0, new Object[]{ new Integer(0), new Integer(1), new Integer(2), new Integer(3), new Integer(4)} ); // is.close(); saveWorkbook(resultWorkbook, outlineDestXLS); } public void testExtendedEncodingExport() throws IOException, ParsePropertyException { Map beans = new HashMap(); Employee emp = (Employee) itEmployees.get(0); emp.setName("Леонид"); List notes = new ArrayList(); notes.add("Запи�?ь 1"); notes.add("Заметка 2"); notes.add("Строка 3"); emp.setNotes( notes ); beans.put("employee", emp); beans.put("employees", itEmployees); InputStream is = new BufferedInputStream(getClass().getResourceAsStream(employeeNotesXLS)); XLSTransformer transformer = new XLSTransformer(); HSSFWorkbook resultWorkbook = transformer.transformXLS(is, beans); is.close(); is = new BufferedInputStream(getClass().getResourceAsStream(employeeNotesXLS)); POIFSFileSystem fs = new POIFSFileSystem(is); HSSFWorkbook sourceWorkbook = new HSSFWorkbook(fs); HSSFSheet sourceSheet = sourceWorkbook.getSheetAt(0); HSSFSheet resultSheet = resultWorkbook.getSheetAt(0); Map props = new HashMap(); CellsChecker checker = new CellsChecker(props); checker.checkListCells( sourceSheet, 2, resultSheet, 2, (short)1, emp.getNotes().toArray() ); is.close(); saveWorkbook( resultWorkbook, employeeNotesRusDestXLS); } public void testForIfTagOneRowExport() throws IOException, ParsePropertyException { Map beans = new HashMap(); beans.put( "departments", departments ); InputStream is = new BufferedInputStream(getClass().getResourceAsStream(forifTagOneRowXLS)); XLSTransformer transformer = new XLSTransformer(); HSSFWorkbook resultWorkbook = transformer.transformXLS(is, beans); is.close(); is = new BufferedInputStream(getClass().getResourceAsStream(forifTagOneRowXLS)); POIFSFileSystem fs = new POIFSFileSystem(is); HSSFWorkbook sourceWorkbook = new HSSFWorkbook(fs); HSSFSheet sourceSheet = sourceWorkbook.getSheetAt(0); HSSFSheet resultSheet = resultWorkbook.getSheetAt(0); Map props = new HashMap(); props.put( "${department.name}", "IT"); CellsChecker checker = new CellsChecker(props); checker.checkRows(sourceSheet, resultSheet, 1, 0, 1); for(int i = 0; i < itEmployeeNames.length; i++){ props.put("${employee.name}", itEmployeeNames[i]); props.put("${employee.payment}", itPayments[i]); props.put("${employee.bonus}", itBonuses[i]); short srcCol = 7; if( itPayments[i].doubleValue() > 2000 ){ srcCol = 4; } checker.checkCells(sourceSheet, resultSheet, 2, (short)2, 1, (short)(i*2 + 1), false); checker.checkCells(sourceSheet, resultSheet, 2, srcCol, 1, (short)(i*2 + 2), false); checker.checkCells(sourceSheet, resultSheet, 3, (short)2, 2, (short)(i*2 + 1), false); checker.checkCells(sourceSheet, resultSheet, 3, srcCol, 2, (short)(i*2 + 2), false); } for(int i = 0; i < hrEmployeeNames.length; i++){ props.put("${employee.name}", hrEmployeeNames[i]); props.put("${employee.payment}", hrPayments[i]); props.put("${employee.bonus}", hrBonuses[i]); short srcCol = 7; if( hrPayments[i].doubleValue() > 2000 ){ srcCol = 4; } checker.checkCells(sourceSheet, resultSheet, 2, (short)2, 4, (short)(i*2 + 1), false); checker.checkCells(sourceSheet, resultSheet, 2, srcCol, 4, (short)(i*2 + 2), false); checker.checkCells(sourceSheet, resultSheet, 3, (short)2, 5, (short)(i*2 + 1), false); checker.checkCells(sourceSheet, resultSheet, 3, srcCol, 5, (short)(i*2 + 2), false); } for(int i = 0; i < baEmployeeNames.length; i++){ props.put("${employee.name}", baEmployeeNames[i]); props.put("${employee.payment}", baPayments[i]); props.put("${employee.bonus}", baBonuses[i]); short srcCol = 7; if( baPayments[i].doubleValue() > 2000 ){ srcCol = 4; } checker.checkCells(sourceSheet, resultSheet, 2, (short)2, 7, (short)(i*2 + 1), false); checker.checkCells(sourceSheet, resultSheet, 2, srcCol, 7, (short)(i*2 + 2), false); checker.checkCells(sourceSheet, resultSheet, 3, (short)2, 8, (short)(i*2 + 1), false); checker.checkCells(sourceSheet, resultSheet, 3, srcCol, 8, (short)(i*2 + 2), false); } is.close(); saveWorkbook( resultWorkbook, forifTagOneRowDestXLS); } public void testDynamicColumns() throws IOException, ParsePropertyException { Map beans = new HashMap(); List cols = new ArrayList(); String[] colNames = new String[]{"Column 1", "Column 2", "Column 3"}; for (int i = 0; i < colNames.length; i++) { String colName = colNames[i]; cols.add( new Column(colName) ); } beans.put( "cols", cols ); List list = new ArrayList(); list.add(new Item("A", new int[] { 1, 2, 3 })); list.add(new Item("B", new int[] { })); list.add(new Item("C", new int[] { 4, 5, 6 })); list.add(new Item("D", new int[] { })); beans.put("list", list); InputStream is = new BufferedInputStream(getClass().getResourceAsStream(dynamicColumnsXLS)); XLSTransformer transformer = new XLSTransformer(); HSSFWorkbook resultWorkbook = transformer.transformXLS(is, beans); is.close(); is = new BufferedInputStream(getClass().getResourceAsStream(dynamicColumnsXLS)); POIFSFileSystem fs = new POIFSFileSystem(is); HSSFWorkbook sourceWorkbook = new HSSFWorkbook(fs); HSSFSheet sourceSheet = sourceWorkbook.getSheetAt(0); HSSFSheet resultSheet = resultWorkbook.getSheetAt(0); Map props = new HashMap(); props.put( "${col.text}", colNames[0]); CellsChecker checker = new CellsChecker(props); checker.checkCells( sourceSheet, resultSheet, 0, (short)1, 0, (short)0, true); props.put( "${col.text}", colNames[1]); checker.checkCells( sourceSheet, resultSheet, 0, (short)1, 0, (short)1, true); props.put( "${col.text}", colNames[2]); checker.checkCells( sourceSheet, resultSheet, 0, (short)1, 0, (short)2, true); is.close(); saveWorkbook( resultWorkbook, dynamicColumnsDestXLS); } public void testForIfTagOneRowExport2() throws IOException, ParsePropertyException { Map beans = new HashMap(); List items = new ArrayList(); items.add(new Item("Item 1")); // items.add(new Item("Item 2")); beans.put("items", items); InputStream is = new BufferedInputStream(getClass().getResourceAsStream(forifTagOneRow2XLS)); XLSTransformer transformer = new XLSTransformer(); HSSFWorkbook resultWorkbook = transformer.transformXLS(is, beans); is.close(); //todo: complete test // is = new BufferedInputStream(getClass().getResourceAsStream(forifTagOneRow2XLS)); // POIFSFileSystem fs = new POIFSFileSystem(is); // HSSFWorkbook sourceWorkbook = new HSSFWorkbook(fs); // HSSFSheet sourceSheet = sourceWorkbook.getSheetAt(0); // HSSFSheet resultSheet = resultWorkbook.getSheetAt(0); // is.close(); saveWorkbook( resultWorkbook, forifTagOneRowDest2XLS); } public void testHiddenSheetsExport() throws IOException, ParsePropertyException { Map beans = new HashMap(); beans.put("bean", simpleBean1); InputStream is = new BufferedInputStream(getClass().getResourceAsStream(hideSheetsXLS)); XLSTransformer transformer = new XLSTransformer(); transformer.setSpreadsheetsToRemove(new String[]{"Sheet 2", "Sheet 3"}); HSSFWorkbook resultWorkbook = transformer.transformXLS(is, beans); assertEquals("Number of sheets in result workbook is incorrect", 1, resultWorkbook.getNumberOfSheets() ); is.close(); is = new BufferedInputStream(getClass().getResourceAsStream(hideSheetsXLS)); transformer.setSpreadsheetsToRemove(new String[]{"Sheet 2"}); resultWorkbook = transformer.transformXLS(is, beans); assertEquals("Number of sheets in result workbook is incorrect", 2, resultWorkbook.getNumberOfSheets() ); is.close(); saveWorkbook(resultWorkbook, hideSheetsDestXLS); } public void testMultipleSheetList() throws IOException, ParsePropertyException { InputStream is = new BufferedInputStream(getClass().getResourceAsStream(multipleSheetListXLS)); XLSTransformer transformer = new XLSTransformer(); List sheetNames = new ArrayList(); // sheetNames.add("New Sheet"); for(int i = 0; i < departments.size(); i++){ Department department = (Department) departments.get( i ); sheetNames.add( department.getName() ); } HSSFWorkbook resultWorkbook = transformer.transformMultipleSheetsList(is, departments, sheetNames, "department", new HashMap(), 0); is.close(); is = new BufferedInputStream(getClass().getResourceAsStream(multipleSheetListXLS)); POIFSFileSystem fs = new POIFSFileSystem(is); HSSFWorkbook sourceWorkbook = new HSSFWorkbook(fs); assertEquals( "Number of result worksheets is incorrect ", sourceWorkbook.getNumberOfSheets() + departments.size() - 1, resultWorkbook.getNumberOfSheets()); // for (int sheetNo = 0; sheetNo < resultWorkbook.getNumberOfSheets() && sheetNo < sheetNames.size(); sheetNo++) { // assertEquals( "Result worksheet name is incorrect", sheetNames.get(sheetNo), resultWorkbook.getSheetName(sheetNo)); // } // todo create all necessary checks // HSSFSheet sourceSheet = sourceWorkbook.getSheetAt(0); // HSSFSheet resultSheet = resultWorkbook.getSheetAt(0); // // Map props = new HashMap(); // props.put("${departments.name}//:4", "IT"); // props.put("Department//departments", "Department"); // CellsChecker checker = new CellsChecker(props); // checker.checkRows(sourceSheet, resultSheet, 0, 0, 3); // checker.checkListCells(sourceSheet, 3, resultSheet, 3, (short) 0, itEmployeeNames); // checker.checkListCells(sourceSheet, 3, resultSheet, 3, (short) 1, itPayments); // checker.checkListCells(sourceSheet, 3, resultSheet, 3, (short) 2, itBonuses); // checker.checkFormulaCell( sourceSheet, 3, resultSheet, 3, (short)3, "B4*(1+C4)"); // checker.checkFormulaCell( sourceSheet, 3, resultSheet, 4, (short)3, "B5*(1+C5)"); // checker.checkFormulaCell( sourceSheet, 3, resultSheet, 7, (short)3, "B8*(1+C8)"); is.close(); saveWorkbook(resultWorkbook, multipleSheetListDestXLS); } public void testMultiTab() throws IOException, ParsePropertyException { InputStream is = new BufferedInputStream(getClass().getResourceAsStream(multiTabXLS)); XLSTransformer transformer = new XLSTransformer(); List sheetNames = new ArrayList(); // sheetNames.add("New Sheet"); List maps = new ArrayList(); for(int i = 0; i < departments.size(); i++){ Map map = new HashMap(); Department department = (Department) departments.get( i ); map.put("department", department ); sheetNames.add( department.getName() ); map.put("name", "Number " + i); maps.add( map ); } HSSFWorkbook resultWorkbook = transformer.transformMultipleSheetsList(is, maps, sheetNames, "map", new HashMap(), 0); is.close(); saveWorkbook(resultWorkbook, multiTabDestXLS); } // todo complete this test public void atestMultipleSheetList2() throws IOException, ParsePropertyException { InputStream is = new BufferedInputStream(getClass().getResourceAsStream(multipleSheetList2XLS)); XLSTransformer transformer = new XLSTransformer(); List sheetNames = new ArrayList(); sheetNames.add("Sheet 1"); for(int i = 0; i < departments.size(); i++){ Department department = (Department) departments.get( i ); sheetNames.add( department.getName() ); } List templateSheetList = new ArrayList(); templateSheetList.add("Template Sheet 1"); templateSheetList.add("Template Sheet 2"); List sheetNameList = new ArrayList(); List beanParamList = new ArrayList(); HSSFWorkbook resultWorkbook = transformer.transformMultipleSheetsList(is, departments, sheetNames, "department", new HashMap(), 0); transformer.transformXLS(is, templateSheetList, sheetNameList, beanParamList ); is.close(); is = new BufferedInputStream(getClass().getResourceAsStream(multipleSheetList2XLS)); POIFSFileSystem fs = new POIFSFileSystem(is); HSSFWorkbook sourceWorkbook = new HSSFWorkbook(fs); assertEquals( "Number of result worksheets is incorrect ", sourceWorkbook.getNumberOfSheets() + departments.size() - 1, resultWorkbook.getNumberOfSheets()); for (int sheetNo = 0; sheetNo < resultWorkbook.getNumberOfSheets() && sheetNo < sheetNames.size(); sheetNo++) { } is.close(); saveWorkbook(resultWorkbook, multipleSheetList2DestXLS); } public void testGroupTag() throws IOException, ParsePropertyException { Map beans = new HashMap(); beans.put( "departments", departments ); InputStream is = new BufferedInputStream(getClass().getResourceAsStream(groupTagXLS)); XLSTransformer transformer = new XLSTransformer(); HSSFWorkbook resultWorkbook = transformer.transformXLS(is, beans); is.close(); // todo complete test checks // is = new BufferedInputStream(getClass().getResourceAsStream(groupTagXLS)); // POIFSFileSystem fs = new POIFSFileSystem(is); // HSSFWorkbook sourceWorkbook = new HSSFWorkbook(fs); // HSSFSheet sourceSheet = sourceWorkbook.getSheetAt(0); // HSSFSheet resultSheet = resultWorkbook.getSheetAt(0); saveWorkbook( resultWorkbook, groupTagDestXLS ); } public void testForIfTagMergeCellsExport() throws IOException, ParsePropertyException { Map beans = new HashMap(); beans.put( "departments", departments ); InputStream is = new BufferedInputStream(getClass().getResourceAsStream(forifTagMergeXLS)); XLSTransformer transformer = new XLSTransformer(); HSSFWorkbook resultWorkbook = transformer.transformXLS(is, beans); is.close(); saveWorkbook(resultWorkbook, forifTagMergeDestXLS); } public void testJEXLExpressions() throws IOException { Map beans = new HashMap(); SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy"); beans.put("dateFormat", dateFormat); Map map = new HashMap(); map.put("Name", "Leonid"); map.put("Surname", "Vysochyn"); map.put("employees", itDepartment.getStaff()); beans.put("map", map); MyBean obj = new MyBean(); Bean bean = new Bean(); beans.put( "bean", bean ); beans.put("emptyVar", ""); beans.put("nullVar", null); beans.put("obj", obj); beans.put("employees1", ((Department)departments.get(0)).getStaff()); beans.put("employees2", new ArrayList()); beans.put("employees3", ((Department)departments.get(1)).getStaff()); beans.put("employees4", new ArrayList()); beans.put("employees5", ((Department)departments.get(2)).getStaff()); InputStream is = new BufferedInputStream(getClass().getResourceAsStream(jexlXLS)); XLSTransformer transformer = new XLSTransformer(); transformer.setJexlInnerCollectionsAccess( true ); HSSFWorkbook resultWorkbook = transformer.transformXLS(is, beans); is.close(); is = new BufferedInputStream(getClass().getResourceAsStream(jexlXLS)); POIFSFileSystem fs = new POIFSFileSystem(is); HSSFWorkbook sourceWorkbook = new HSSFWorkbook(fs); HSSFSheet sourceSheet = sourceWorkbook.getSheetAt(0); HSSFSheet resultSheet = resultWorkbook.getSheetAt(0); Map props = new HashMap(); props.put("${obj.name}", obj.getName() ); props.put("${\"Hello, World\"}","Hello, World"); props.put("${obj.flag == true}", Boolean.valueOf(obj.getFlag())); props.put("${obj.name == null}", Boolean.valueOf(obj.getName() == null)); // props.put("${empty(obj.collection)}", Boolean.valueOf(obj.getCollection().isEmpty())); // props.put("${obj.collection.size()}", new Integer(((String)obj.getCollection().get(0)).length())); props.put("${obj.name.size()}", new Integer( obj.getName().length() ) ); props.put("${!empty(obj.collection) && obj.id > 0}", Boolean.valueOf(!obj.getCollection().isEmpty() && obj.getId() > 0)); props.put("${empty(obj.collection) || obj.id == 1}", Boolean.valueOf(obj.getCollection().isEmpty() && obj.getId() == 1)); props.put("${not empty(obj.collection)}", Boolean.valueOf(!obj.getCollection().isEmpty())); props.put("${obj.id > 1}", Boolean.valueOf(obj.getId() > 1)); props.put("${obj.id == 1}", Boolean.valueOf(obj.getId() == 1)); props.put("${obj.id != 1}", Boolean.valueOf(obj.getId() != 1)); props.put("${obj.id eq 1}", Boolean.valueOf(obj.getId() == 1)); props.put("${obj.id % 2}", new Integer(obj.getId() % 2)); props.put("${obj.myArray[0]} and ${obj.myArray[1]}", obj.getMyArray()[0] + " and " + obj.getMyArray()[1]); props.put("${dateFormat.format(obj.date)}", dateFormat.format( obj.getDate() )); props.put("${obj.printIt()}", obj.printIt() ); props.put("${obj.getName()}", obj.getName()); props.put("${obj.echo(\"Hello\")}", obj.echo("Hello")); CellsChecker checker = new CellsChecker(props); checker.checkSection( sourceSheet, resultSheet, 0, 0, (short)0, (short)1, 25, false, false); props.clear(); props.put("${bean.collection.innerCollection.get(0)}", "1"); checker.checkListCells( sourceSheet, 25, resultSheet, 25, (short)1, new String[]{((Bean.InnerBean)bean.getCollection().get(0)).getInnerCollection().get(0).toString(), ((Bean.InnerBean)bean.getCollection().get(1)).getInnerCollection().get(0).toString(), ((Bean.InnerBean)bean.getCollection().get(2)).getInnerCollection().get(0).toString()}); saveWorkbook( resultWorkbook, jexlDestXLS); } public void testForGroupBy() throws IOException, ParsePropertyException { Map beans = new HashMap(); List deps = new ArrayList( departments ); // adding department with null values to check grouping with null values deps.add(mgrDepartment); beans.put( "departments", deps ); InputStream is = new BufferedInputStream(getClass().getResourceAsStream(forGroupByXLS)); XLSTransformer transformer = new XLSTransformer(); HSSFWorkbook resultWorkbook = transformer.transformXLS(is, beans); is.close(); is = new BufferedInputStream(getClass().getResourceAsStream(forGroupByXLS)); is.close(); saveWorkbook(resultWorkbook, forGroupByDestXLS); // testing empty collection used with jx:forEach grouping // Collection emptyDepartments = new ArrayList(); ((Department)departments.get(0)).getStaff().clear(); // beanList.clear(); // beanList.put( "departments", emptyDepartments ); is = new BufferedInputStream(getClass().getResourceAsStream(forGroupByXLS)); resultWorkbook = transformer.transformXLS(is, beans); saveWorkbook( resultWorkbook, forGroupByDestXLS ); is.close(); } public void testPoiObjectsExpose() throws IOException, ParsePropertyException { Map beans = new HashMap(); beans.put( "departments", departments ); beans.put("itDepartment", itDepartment); List employees = itDepartment.getStaff(); ((Employee)employees.get(0)).setComment(""); for (int i = 1; i < employees.size(); i++) { Employee employee = (Employee) employees.get(i); String comment = ""; for( int j =0; j <= i; j++ ){ comment += "Employee Comment Line " + j + " ..\r\n"; } employee.setComment( comment ); } beans.put("employees", employees); beans.put("lineSize", new Integer(0)); beans.put("row", new Integer(3)); InputStream is = new BufferedInputStream(getClass().getResourceAsStream(poiobjectsXLS)); XLSTransformer transformer = new XLSTransformer(); HSSFWorkbook resultWorkbook = transformer.transformXLS(is, beans); is.close(); is = new BufferedInputStream(getClass().getResourceAsStream(poiobjectsXLS)); POIFSFileSystem fs = new POIFSFileSystem(is); HSSFWorkbook sourceWorkbook = new HSSFWorkbook(fs); HSSFSheet sourceSheet = sourceWorkbook.getSheetAt(0); HSSFSheet resultSheet = resultWorkbook.getSheetAt(0); assertEquals("First Row Numbers differ in source and result sheets", sourceSheet.getFirstRowNum(), resultSheet.getFirstRowNum()); assertEquals(resultSheet.getHeader().getLeft(), "Test Left Header"); assertEquals(resultSheet.getHeader().getCenter(), itDepartment.getName()); assertEquals(resultSheet.getHeader().getRight(), "Test Right Header"); assertEquals(resultSheet.getFooter().getRight(), "Test Right Footer"); assertEquals(resultSheet.getFooter().getCenter(), "Test Center Footer"); assertEquals( resultWorkbook.getSheetName(2), itDepartment.getName()); Map props = new HashMap(); props.put("${department.name}", "IT"); CellsChecker checker = new CellsChecker(props); checker.checkRows(sourceSheet, resultSheet, 1, 0, 3); checker.checkListCells(sourceSheet, 5, resultSheet, 3, (short) 0, itEmployeeNames); checker.checkListCells(sourceSheet, 5, resultSheet, 3, (short) 1, itPayments); checker.checkListCells(sourceSheet, 5, resultSheet, 3, (short) 2, itBonuses); props.clear(); props.put("${department.name}", "HR"); checker = new CellsChecker(props); checker.checkRows(sourceSheet, resultSheet, 1, 9, 3); props.clear(); checker.checkListCells(sourceSheet, 5, resultSheet, 12, (short) 0, hrEmployeeNames); checker.checkListCells(sourceSheet, 5, resultSheet, 12, (short) 1, hrPayments); checker.checkListCells(sourceSheet, 5, resultSheet, 12, (short) 2, hrBonuses); props.clear(); props.put("${department.name}", "BA"); checker = new CellsChecker(props); checker.checkRows(sourceSheet, resultSheet, 1, 17, 3); props.clear(); checker.checkListCells(sourceSheet, 5, resultSheet, 20, (short) 0, baEmployeeNames); checker.checkListCells(sourceSheet, 5, resultSheet, 20, (short) 1, baPayments); checker.checkListCells(sourceSheet, 5, resultSheet, 20, (short) 2, baBonuses); is.close(); saveWorkbook( resultWorkbook, poiobjectsDestXLS); } public void testForEachSelect() throws IOException { Map beans = new HashMap(); String[] selectedEmployees = new String[]{"Oleg", "Neil", "John"}; List employees = itDepartment.getStaff(); beans.put("employees", employees); InputStream is = new BufferedInputStream(getClass().getResourceAsStream(selectXLS)); XLSTransformer transformer = new XLSTransformer(); HSSFWorkbook resultWorkbook = transformer.transformXLS(is, beans); HSSFSheet sheet = resultWorkbook.getSheetAt(0); HSSFRow row = sheet.getRow(0); for(int i = 0; i < selectedEmployees.length; i++){ HSSFCell cell = row.getCell((short)i); String empName = cell.getRichStringCellValue().getString(); assertEquals("Selected employees are incorrect", selectedEmployees[i], empName); } is.close(); saveWorkbook(resultWorkbook, selectDestXLS); } - public void testOutTagInOneRow(){ + public void testOutTagInOneRow() throws IOException { Map beans = new HashMap(); List employees = itDepartment.getStaff(); beans.put("employees", employees); InputStream is = new BufferedInputStream(getClass().getResourceAsStream(outTagOneRowXLS)); XLSTransformer transformer = new XLSTransformer(); transformer.setJexlInnerCollectionsAccess(true); HSSFWorkbook resultWorkbook = transformer.transformXLS(is, beans); HSSFSheet sheet = resultWorkbook.getSheetAt(0); int index = 0; for (int i = 0; i < employees.size(); i++) { Employee employee = (Employee) employees.get(i); if( employee.getPayment().doubleValue() > 2000 ){ HSSFRow row = sheet.getRow(index); index++; assertNotNull("Row must not be null", row); assertEquals("Employee names are not equal", employee.getName(), row.getCell((short)0).getRichStringCellValue().getString()); assertEquals("Employee payments are not equal", employee.getPayment().doubleValue(), row.getCell((short)1).getNumericCellValue(), 1e-6); assertEquals("Employee bonuses are not equal", employee.getBonus().doubleValue(), row.getCell((short)2).getNumericCellValue(), 1e-6); } } + is.close(); + } + + public void testSyntaxError() throws IOException { + Map beans = new HashMap(); + beans.put("value", "A Test"); + beans.put("value2", "Second value"); + InputStream is = new BufferedInputStream(getClass().getResourceAsStream("/templates/syntaxerror.xls")); + XLSTransformer transformer = new XLSTransformer(); + HSSFWorkbook resultWorkbook = transformer.transformXLS(is, beans); + HSSFSheet sheet = resultWorkbook.getSheetAt(0); + HSSFRow row = sheet.getRow(0); + HSSFCell cell = row.getCell((short)0); + assertEquals("Incorrect cell value", "${value", cell.getRichStringCellValue().getString()); + row = sheet.getRow(1); + cell = row.getCell((short)0); + assertEquals("Incorrect cell value", "Second value", cell.getRichStringCellValue().getString()); + is.close(); } private void saveWorkbook(HSSFWorkbook resultWorkbook, String fileName) throws IOException { String saveResultsProp = System.getProperty("saveResults"); if( "true".equalsIgnoreCase(saveResultsProp) ){ if( log.isInfoEnabled() ){ log.info("Saving " + fileName); } OutputStream os = new BufferedOutputStream(new FileOutputStream(fileName)); resultWorkbook.write(os); os.flush(); os.close(); log.info("Output Excel saved to " + fileName); } } }
false
false
null
null
diff --git a/gerrit-sshd/src/main/java/com/google/gerrit/sshd/commands/DefaultCommandModule.java b/gerrit-sshd/src/main/java/com/google/gerrit/sshd/commands/DefaultCommandModule.java index e0ef9881f..a04ba159c 100644 --- a/gerrit-sshd/src/main/java/com/google/gerrit/sshd/commands/DefaultCommandModule.java +++ b/gerrit-sshd/src/main/java/com/google/gerrit/sshd/commands/DefaultCommandModule.java @@ -1,60 +1,60 @@ // Copyright (C) 2009 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.sshd.commands; import com.google.gerrit.sshd.CommandModule; import com.google.gerrit.sshd.CommandName; import com.google.gerrit.sshd.Commands; import com.google.gerrit.sshd.DispatchCommandProvider; import com.google.gerrit.sshd.SuExec; /** Register the basic commands any Gerrit server should support. */ public class DefaultCommandModule extends CommandModule { @Override protected void configure() { final CommandName git = Commands.named("git"); final CommandName gerrit = Commands.named("gerrit"); // The following commands can be ran on a server in either Master or Slave // mode. If a command should only be used on a server in one mode, but not // both, it should be bound in both MasterCommandModule and // SlaveCommandModule. command(gerrit).toProvider(new DispatchCommandProvider(gerrit)); command(gerrit, "flush-caches").to(AdminFlushCaches.class); command(gerrit, "ls-projects").to(ListProjects.class); command(gerrit, "show-caches").to(AdminShowCaches.class); command(gerrit, "show-connections").to(AdminShowConnections.class); command(gerrit, "show-queue").to(ShowQueue.class); command(gerrit, "stream-events").to(StreamEvents.class); command(git).toProvider(new DispatchCommandProvider(git)); command(git, "receive-pack").to(Commands.key(gerrit, "receive-pack")); command(git, "upload-pack").to(Upload.class); - command("ps").to(AdminShowCaches.class); + command("ps").to(ShowQueue.class); command("kill").to(AdminKill.class); command("scp").to(ScpCommand.class); // Honor the legacy hyphenated forms as aliases for the non-hyphenated forms // command("git-upload-pack").to(Commands.key(git, "upload-pack")); command("git-receive-pack").to(Commands.key(git, "receive-pack")); command("gerrit-receive-pack").to(Commands.key(git, "receive-pack")); command("suexec").to(SuExec.class); } }
true
true
protected void configure() { final CommandName git = Commands.named("git"); final CommandName gerrit = Commands.named("gerrit"); // The following commands can be ran on a server in either Master or Slave // mode. If a command should only be used on a server in one mode, but not // both, it should be bound in both MasterCommandModule and // SlaveCommandModule. command(gerrit).toProvider(new DispatchCommandProvider(gerrit)); command(gerrit, "flush-caches").to(AdminFlushCaches.class); command(gerrit, "ls-projects").to(ListProjects.class); command(gerrit, "show-caches").to(AdminShowCaches.class); command(gerrit, "show-connections").to(AdminShowConnections.class); command(gerrit, "show-queue").to(ShowQueue.class); command(gerrit, "stream-events").to(StreamEvents.class); command(git).toProvider(new DispatchCommandProvider(git)); command(git, "receive-pack").to(Commands.key(gerrit, "receive-pack")); command(git, "upload-pack").to(Upload.class); command("ps").to(AdminShowCaches.class); command("kill").to(AdminKill.class); command("scp").to(ScpCommand.class); // Honor the legacy hyphenated forms as aliases for the non-hyphenated forms // command("git-upload-pack").to(Commands.key(git, "upload-pack")); command("git-receive-pack").to(Commands.key(git, "receive-pack")); command("gerrit-receive-pack").to(Commands.key(git, "receive-pack")); command("suexec").to(SuExec.class); }
protected void configure() { final CommandName git = Commands.named("git"); final CommandName gerrit = Commands.named("gerrit"); // The following commands can be ran on a server in either Master or Slave // mode. If a command should only be used on a server in one mode, but not // both, it should be bound in both MasterCommandModule and // SlaveCommandModule. command(gerrit).toProvider(new DispatchCommandProvider(gerrit)); command(gerrit, "flush-caches").to(AdminFlushCaches.class); command(gerrit, "ls-projects").to(ListProjects.class); command(gerrit, "show-caches").to(AdminShowCaches.class); command(gerrit, "show-connections").to(AdminShowConnections.class); command(gerrit, "show-queue").to(ShowQueue.class); command(gerrit, "stream-events").to(StreamEvents.class); command(git).toProvider(new DispatchCommandProvider(git)); command(git, "receive-pack").to(Commands.key(gerrit, "receive-pack")); command(git, "upload-pack").to(Upload.class); command("ps").to(ShowQueue.class); command("kill").to(AdminKill.class); command("scp").to(ScpCommand.class); // Honor the legacy hyphenated forms as aliases for the non-hyphenated forms // command("git-upload-pack").to(Commands.key(git, "upload-pack")); command("git-receive-pack").to(Commands.key(git, "receive-pack")); command("gerrit-receive-pack").to(Commands.key(git, "receive-pack")); command("suexec").to(SuExec.class); }
diff --git a/tests/tests/content/src/android/content/cts/ContextWrapperTest.java b/tests/tests/content/src/android/content/cts/ContextWrapperTest.java index ac402ef1..65bdc477 100644 --- a/tests/tests/content/src/android/content/cts/ContextWrapperTest.java +++ b/tests/tests/content/src/android/content/cts/ContextWrapperTest.java @@ -1,1262 +1,1267 @@ /* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.content.cts; import com.android.cts.stub.R; -import dalvik.annotation.BrokenTest; import dalvik.annotation.TestLevel; import dalvik.annotation.TestTargetClass; import dalvik.annotation.TestTargetNew; import dalvik.annotation.TestTargets; import dalvik.annotation.ToBeFixed; import android.content.ActivityNotFoundException; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.ContextWrapper; import android.content.Intent; import android.content.IntentFilter; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.res.TypedArray; import android.content.res.Resources.Theme; import android.database.Cursor; import android.database.sqlite.SQLiteCursorDriver; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteQuery; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Binder; import android.os.Bundle; import android.os.IBinder; import android.preference.PreferenceManager; import android.test.AndroidTestCase; import android.view.animation.cts.DelayedCheck; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; /** * Test {@link ContextWrapper}. */ @TestTargetClass(ContextWrapper.class) public class ContextWrapperTest extends AndroidTestCase { private static final String PERMISSION_HARDWARE_TEST = "android.permission.HARDWARE_TEST"; private static final String ACTUAL_RESULT = "ResultSetByReceiver"; private static final String INTIAL_RESULT = "IntialResult"; private static final String VALUE_ADDED = "ValueAdded"; private static final String KEY_ADDED = "AddedByReceiver"; private static final String VALUE_REMOVED = "ValueWillBeRemove"; private static final String KEY_REMOVED = "ToBeRemoved"; private static final String VALUE_KEPT = "ValueKept"; private static final String KEY_KEPT = "ToBeKept"; private static final String MOCK_STICKY_ACTION = "android.content.cts.ContextWrapperTest." + "STICKY_BROADCAST_RESULT"; private static final String ACTION_BROADCAST_TESTORDER = "android.content.cts.ContextWrapperTest.BROADCAST_TESTORDER"; private final static String MOCK_ACTION1 = ACTION_BROADCAST_TESTORDER + "1"; private final static String MOCK_ACTION2 = ACTION_BROADCAST_TESTORDER + "2"; public static final String PERMISSION_GRANTED = "android.app.cts.permission.TEST_GRANTED"; public static final String PERMISSION_DENIED = "android.app.cts.permission.TEST_DENIED"; private static final int BROADCAST_TIMEOUT = 10000; private Context mContext; private ContextWrapper mContextWrapper; private Object mLockObj; private ArrayList<BroadcastReceiver> mRegisteredReceiverList; private boolean mWallpaperChanged; private BitmapDrawable mOriginalWallpaper; @Override protected void setUp() throws Exception { super.setUp(); mLockObj = new Object(); mContext = getContext(); mContextWrapper = new ContextWrapper(mContext); mRegisteredReceiverList = new ArrayList<BroadcastReceiver>(); mOriginalWallpaper = (BitmapDrawable) mContextWrapper.getWallpaper(); } @Override protected void tearDown() throws Exception { if (mWallpaperChanged) { mContextWrapper.setWallpaper(mOriginalWallpaper.getBitmap()); } for (BroadcastReceiver receiver : mRegisteredReceiverList) { mContextWrapper.unregisterReceiver(receiver); } super.tearDown(); } private void registerBroadcastReceiver(BroadcastReceiver receiver, IntentFilter filter) { mContextWrapper.registerReceiver(receiver, filter); mRegisteredReceiverList.add(receiver); } @TestTargetNew( level = TestLevel.COMPLETE, method = "ContextWrapper", args = {android.content.Context.class} ) public void testConstructor() { new ContextWrapper(mContext); // null param is allowed new ContextWrapper(null); } @TestTargetNew( level = TestLevel.COMPLETE, method = "enforceCallingPermission", args = {String.class, String.class} ) public void testEnforceCallingPermission() { try { mContextWrapper.enforceCallingPermission( PERMISSION_HARDWARE_TEST, "enforceCallingPermission is not working without possessing an IPC."); fail("enforceCallingPermission is not working without possessing an IPC."); } catch (SecurityException e) { // Currently no IPC is handled by this process, this exception is expected } } @TestTargetNew( level = TestLevel.COMPLETE, method = "sendOrderedBroadcast", args = {android.content.Intent.class, java.lang.String.class} ) public void testSendOrderedBroadcast1() throws InterruptedException { final HighPriorityBroadcastReceiver highPriorityReceiver = new HighPriorityBroadcastReceiver(); final LowPriorityBroadcastReceiver lowPriorityReceiver = new LowPriorityBroadcastReceiver(); final IntentFilter filter = new IntentFilter(ResultReceiver.MOCK_ACTION); registerBroadcastReceiver(highPriorityReceiver, filter); registerBroadcastReceiver(lowPriorityReceiver, filter); final Intent broadcastIntent = new Intent(ResultReceiver.MOCK_ACTION); mContextWrapper.sendOrderedBroadcast(broadcastIntent, null); new DelayedCheck(BROADCAST_TIMEOUT) { @Override protected boolean check() { return highPriorityReceiver.hasReceivedBroadCast() && !lowPriorityReceiver.hasReceivedBroadCast(); } }.run(); synchronized (highPriorityReceiver) { highPriorityReceiver.notify(); } new DelayedCheck(BROADCAST_TIMEOUT) { @Override protected boolean check() { return highPriorityReceiver.hasReceivedBroadCast() && lowPriorityReceiver.hasReceivedBroadCast(); } }.run(); } @TestTargetNew( level = TestLevel.COMPLETE, method = "sendOrderedBroadcast", args = {android.content.Intent.class, java.lang.String.class, android.content.BroadcastReceiver.class, android.os.Handler.class, int.class, java.lang.String.class, android.os.Bundle.class} ) public void testSendOrderedBroadcast2() throws InterruptedException { final TestBroadcastReceiver broadcastReceiver = new TestBroadcastReceiver(); broadcastReceiver.mIsOrderedBroadcasts = true; Bundle bundle = new Bundle(); bundle.putString(KEY_KEPT, VALUE_KEPT); bundle.putString(KEY_REMOVED, VALUE_REMOVED); mContextWrapper.sendOrderedBroadcast(new Intent(ResultReceiver.MOCK_ACTION), null, broadcastReceiver, null, 1, INTIAL_RESULT, bundle); synchronized (mLockObj) { try { mLockObj.wait(BROADCAST_TIMEOUT); } catch (InterruptedException e) { fail("unexpected InterruptedException."); } } assertTrue("Receiver didn't make any response.", broadcastReceiver.hadReceivedBroadCast()); assertEquals("Incorrect code: " + broadcastReceiver.getResultCode(), 3, broadcastReceiver.getResultCode()); assertEquals(ACTUAL_RESULT, broadcastReceiver.getResultData()); Bundle resultExtras = broadcastReceiver.getResultExtras(false); assertEquals(VALUE_ADDED, resultExtras.getString(KEY_ADDED)); assertEquals(VALUE_KEPT, resultExtras.getString(KEY_KEPT)); assertNull(resultExtras.getString(KEY_REMOVED)); } @TestTargets({ @TestTargetNew( level = TestLevel.COMPLETE, method = "getTheme", args = {} ), @TestTargetNew( level = TestLevel.COMPLETE, method = "setTheme", args = {int.class} ) }) - @BrokenTest("needs investigation") public void testAccessTheme() { mContextWrapper.setTheme(R.style.Test_Theme); final Theme testTheme = mContextWrapper.getTheme(); assertNotNull(testTheme); int[] attrs = { android.R.attr.windowNoTitle, android.R.attr.panelColorForeground, android.R.attr.panelColorBackground }; - TypedArray attrArray = testTheme.obtainStyledAttributes(attrs); - - assertTrue(attrArray.getBoolean(0, false)); - assertEquals(0xff000000, attrArray.getColor(1, 0)); - assertEquals(0xffffffff, attrArray.getColor(2, 0)); + TypedArray attrArray = null; + try { + attrArray = testTheme.obtainStyledAttributes(attrs); + assertTrue(attrArray.getBoolean(0, false)); + assertEquals(0xff000000, attrArray.getColor(1, 0)); + assertEquals(0xffffffff, attrArray.getColor(2, 0)); + } finally { + if (attrArray != null) { + attrArray.recycle(); + attrArray = null; + } + } // setTheme only works for the first time mContextWrapper.setTheme(android.R.style.Theme_Black); assertSame(testTheme, mContextWrapper.getTheme()); } @TestTargets({ @TestTargetNew( level = TestLevel.COMPLETE, method = "registerReceiver", args = {BroadcastReceiver.class, IntentFilter.class} ), @TestTargetNew( level = TestLevel.COMPLETE, method = "unregisterReceiver", args = {BroadcastReceiver.class} ) }) public void testRegisterReceiver1() throws InterruptedException { final FilteredReceiver broadcastReceiver = new FilteredReceiver(); final IntentFilter filter = new IntentFilter(MOCK_ACTION1); // Test registerReceiver mContextWrapper.registerReceiver(broadcastReceiver, filter); // Test unwanted intent(action = MOCK_ACTION2) broadcastReceiver.reset(); waitForFilteredIntent(mContextWrapper, broadcastReceiver, MOCK_ACTION2); assertFalse(broadcastReceiver.hadReceivedBroadCast1()); assertFalse(broadcastReceiver.hadReceivedBroadCast2()); // Send wanted intent(action = MOCK_ACTION1) broadcastReceiver.reset(); waitForFilteredIntent(mContextWrapper, broadcastReceiver, MOCK_ACTION1); assertTrue(broadcastReceiver.hadReceivedBroadCast1()); assertFalse(broadcastReceiver.hadReceivedBroadCast2()); mContextWrapper.unregisterReceiver(broadcastReceiver); // Test unregisterReceiver FilteredReceiver broadcastReceiver2 = new FilteredReceiver(); mContextWrapper.registerReceiver(broadcastReceiver2, filter); mContextWrapper.unregisterReceiver(broadcastReceiver2); // Test unwanted intent(action = MOCK_ACTION2) broadcastReceiver2.reset(); waitForFilteredIntent(mContextWrapper, broadcastReceiver2, MOCK_ACTION2); assertFalse(broadcastReceiver2.hadReceivedBroadCast1()); assertFalse(broadcastReceiver2.hadReceivedBroadCast2()); // Send wanted intent(action = MOCK_ACTION1), but the receiver is unregistered. broadcastReceiver2.reset(); waitForFilteredIntent(mContextWrapper, broadcastReceiver2, MOCK_ACTION1); assertFalse(broadcastReceiver2.hadReceivedBroadCast1()); assertFalse(broadcastReceiver2.hadReceivedBroadCast2()); } @TestTargetNew( level = TestLevel.COMPLETE, method = "registerReceiver", args = {android.content.BroadcastReceiver.class, android.content.IntentFilter.class, java.lang.String.class, android.os.Handler.class} ) public void testRegisterReceiver2() throws InterruptedException { FilteredReceiver broadcastReceiver = new FilteredReceiver(); IntentFilter filter = new IntentFilter(); filter.addAction(MOCK_ACTION1); // Test registerReceiver mContextWrapper.registerReceiver(broadcastReceiver, filter, null, null); // Test unwanted intent(action = MOCK_ACTION2) broadcastReceiver.reset(); waitForFilteredIntent(mContextWrapper, broadcastReceiver, MOCK_ACTION2); assertFalse(broadcastReceiver.hadReceivedBroadCast1()); assertFalse(broadcastReceiver.hadReceivedBroadCast2()); // Send wanted intent(action = MOCK_ACTION1) broadcastReceiver.reset(); waitForFilteredIntent(mContextWrapper, broadcastReceiver, MOCK_ACTION1); assertTrue(broadcastReceiver.hadReceivedBroadCast1()); assertFalse(broadcastReceiver.hadReceivedBroadCast2()); mContextWrapper.unregisterReceiver(broadcastReceiver); } @TestTargetNew( level = TestLevel.COMPLETE, method = "enforceCallingOrSelfPermission", args = {String.class, String.class} ) public void testEnforceCallingOrSelfPermission() { try { mContextWrapper.enforceCallingOrSelfPermission(PERMISSION_HARDWARE_TEST, "enforceCallingOrSelfPermission is not working without possessing an IPC."); fail("enforceCallingOrSelfPermission is not working without possessing an IPC."); } catch (SecurityException e) { // If the function is OK, it should throw a SecurityException here because currently no // IPC is handled by this process. } } @TestTargets({ @TestTargetNew( level = TestLevel.COMPLETE, method = "setWallpaper", args = {Bitmap.class} ), @TestTargetNew( level = TestLevel.COMPLETE, method = "setWallpaper", args = {InputStream.class} ), @TestTargetNew( level = TestLevel.COMPLETE, method = "clearWallpaper", args = {} ), @TestTargetNew( level = TestLevel.COMPLETE, method = "getWallpaper", args = {} ), @TestTargetNew( level = TestLevel.COMPLETE, method = "peekWallpaper", args = {} ) }) public void testAccessWallpaper() throws IOException, InterruptedException { // set Wallpaper by contextWrapper#setWallpaper(Bitmap) Bitmap bitmap = Bitmap.createBitmap(20, 30, Bitmap.Config.RGB_565); // Test getWallpaper Drawable testDrawable = mContextWrapper.getWallpaper(); // Test peekWallpaper Drawable testDrawable2 = mContextWrapper.peekWallpaper(); mContextWrapper.setWallpaper(bitmap); mWallpaperChanged = true; synchronized(this) { wait(500); } assertNotSame(testDrawable, mContextWrapper.peekWallpaper()); assertNotNull(mContextWrapper.getWallpaper()); assertNotSame(testDrawable2, mContextWrapper.peekWallpaper()); assertNotNull(mContextWrapper.peekWallpaper()); // set Wallpaper by contextWrapper#setWallpaper(InputStream) mContextWrapper.clearWallpaper(); testDrawable = mContextWrapper.getWallpaper(); InputStream stream = mContextWrapper.getResources().openRawResource(R.drawable.scenery); mContextWrapper.setWallpaper(stream); synchronized (this) { wait(1000); } assertNotSame(testDrawable, mContextWrapper.peekWallpaper()); } @TestTargets({ @TestTargetNew( level = TestLevel.COMPLETE, method = "openOrCreateDatabase", args = {java.lang.String.class, int.class, android.database.sqlite.SQLiteDatabase.CursorFactory.class} ), @TestTargetNew( level = TestLevel.COMPLETE, method = "getDatabasePath", args = {String.class} ), @TestTargetNew( level = TestLevel.COMPLETE, method = "openOrCreateDatabase", args = {String.class, int.class, android.database.sqlite.SQLiteDatabase.CursorFactory.class} ), @TestTargetNew( level = TestLevel.COMPLETE, method = "databaseList", args = {} ), @TestTargetNew( level = TestLevel.COMPLETE, method = "deleteDatabase", args = {String.class} ) }) public void testAccessDatabase() { String DATABASE_NAME = "databasetest"; String DATABASE_NAME1 = DATABASE_NAME + "1"; String DATABASE_NAME2 = DATABASE_NAME + "2"; SQLiteDatabase mDatabase; File mDatabaseFile; SQLiteDatabase.CursorFactory factory = new SQLiteDatabase.CursorFactory() { public Cursor newCursor(SQLiteDatabase db, SQLiteCursorDriver masterQuery, String editTable, SQLiteQuery query) { return new android.database.sqlite.SQLiteCursor(db, masterQuery, editTable, query) { @Override public boolean requery() { setSelectionArguments(new String[] { "2" }); return super.requery(); } }; } }; // FIXME: Move cleanup into tearDown() for (String db : mContextWrapper.databaseList()) { File f = mContextWrapper.getDatabasePath(db); if (f.exists()) { mContextWrapper.deleteDatabase(db); } } // Test openOrCreateDatabase with null and actual factory mDatabase = mContextWrapper.openOrCreateDatabase(DATABASE_NAME1, ContextWrapper.MODE_WORLD_READABLE | ContextWrapper.MODE_WORLD_WRITEABLE, factory); assertNotNull(mDatabase); mDatabase.close(); mDatabase = mContextWrapper.openOrCreateDatabase(DATABASE_NAME2, ContextWrapper.MODE_WORLD_READABLE | ContextWrapper.MODE_WORLD_WRITEABLE, factory); assertNotNull(mDatabase); mDatabase.close(); // Test getDatabasePath File actualDBPath = mContextWrapper.getDatabasePath(DATABASE_NAME1); // Test databaseList() assertEquals(2, mContextWrapper.databaseList().length); ArrayList<String> list = new ArrayList<String>(); // Don't know the items storing order list.add(mContextWrapper.databaseList()[0]); list.add(mContextWrapper.databaseList()[1]); assertTrue(list.contains(DATABASE_NAME1) && list.contains(DATABASE_NAME2)); // Test deleteDatabase() for (int i = 1; i < 3; i++) { mDatabaseFile = mContextWrapper.getDatabasePath(DATABASE_NAME + i); assertTrue(mDatabaseFile.exists()); mContextWrapper.deleteDatabase(DATABASE_NAME + i); mDatabaseFile = new File(actualDBPath, DATABASE_NAME + i); assertFalse(mDatabaseFile.exists()); } } @TestTargetNew( level = TestLevel.COMPLETE, method = "enforceUriPermission", args = {Uri.class, int.class, int.class, int.class, String.class} ) public void testEnforceUriPermission1() { try { Uri uri = Uri.parse("content://ctstest"); mContextWrapper.enforceUriPermission(uri, Binder.getCallingPid(), Binder.getCallingUid(), Intent.FLAG_GRANT_WRITE_URI_PERMISSION, "enforceUriPermission is not working without possessing an IPC."); fail("enforceUriPermission is not working without possessing an IPC."); } catch (SecurityException e) { // If the function is OK, it should throw a SecurityException here because currently no // IPC is handled by this process. } } @TestTargetNew( level = TestLevel.COMPLETE, method = "enforceUriPermission", args = {android.net.Uri.class, java.lang.String.class, java.lang.String.class, int.class, int.class, int.class, java.lang.String.class} ) public void testEnforceUriPermission2() { Uri uri = Uri.parse("content://ctstest"); try { mContextWrapper.enforceUriPermission(uri, PERMISSION_HARDWARE_TEST, PERMISSION_HARDWARE_TEST, Binder.getCallingPid(), Binder.getCallingUid(), Intent.FLAG_GRANT_WRITE_URI_PERMISSION, "enforceUriPermission is not working without possessing an IPC."); fail("enforceUriPermission is not working without possessing an IPC."); } catch (SecurityException e) { // If the function is ok, it should throw a SecurityException here because currently no // IPC is handled by this process. } } @TestTargetNew( level = TestLevel.COMPLETE, method = "getPackageResourcePath", args = {} ) public void testGetPackageResourcePath() { assertNotNull(mContextWrapper.getPackageResourcePath()); } @TestTargetNew( level = TestLevel.COMPLETE, method = "startActivity", args = {Intent.class} ) public void testStartActivity() { Intent intent = new Intent(mContext, ContextWrapperStubActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try { mContextWrapper.startActivity(intent); fail("Test startActivity should thow a ActivityNotFoundException here."); } catch (ActivityNotFoundException e) { // Because ContextWrapper is a wrapper class, so no need to test // the details of the function's performance. Getting a result // from the wrapped class is enough for testing. } } @TestTargetNew( level = TestLevel.COMPLETE, method = "createPackageContext", args = {String.class, int.class} ) public void testCreatePackageContext() throws PackageManager.NameNotFoundException { Context actualContext = mContextWrapper.createPackageContext(getValidPackageName(), Context.CONTEXT_IGNORE_SECURITY); assertNotNull(actualContext); } /** * Helper method to retrieve a valid application package name to use for tests. */ private String getValidPackageName() { List<PackageInfo> packages = mContextWrapper.getPackageManager().getInstalledPackages( PackageManager.GET_ACTIVITIES); assertTrue(packages.size() >= 1); return packages.get(0).packageName; } @TestTargetNew( level = TestLevel.COMPLETE, method = "getMainLooper", args = {} ) public void testGetMainLooper() { assertNotNull(mContextWrapper.getMainLooper()); } @TestTargetNew( level = TestLevel.COMPLETE, method = "getApplicationContext", args = {} ) public void testGetApplicationContext() { assertSame(mContext.getApplicationContext(), mContextWrapper.getApplicationContext()); } @TestTargetNew( level = TestLevel.COMPLETE, method = "getSharedPreferences", args = {String.class, int.class} ) public void testGetSharedPreferences() { SharedPreferences sp; SharedPreferences localSP; sp = PreferenceManager.getDefaultSharedPreferences(mContext); String packageName = mContextWrapper.getPackageName(); localSP = mContextWrapper.getSharedPreferences(packageName + "_preferences", Context.MODE_PRIVATE); assertSame(sp, localSP); } @TestTargetNew( level = TestLevel.COMPLETE, method = "revokeUriPermission", args = {Uri.class, int.class} ) @ToBeFixed(bug = "1400249", explanation = "Can't test the effect of this function, should be" + "tested by functional test.") public void testRevokeUriPermission() { Uri uri = Uri.parse("contents://ctstest"); mContextWrapper.revokeUriPermission(uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION); } @TestTargets({ @TestTargetNew( level = TestLevel.COMPLETE, method = "startService", args = {Intent.class} ), @TestTargetNew( level = TestLevel.COMPLETE, method = "bindService", args = {android.content.Intent.class, android.content.ServiceConnection.class, int.class} ), @TestTargetNew( level = TestLevel.COMPLETE, method = "stopService", args = {Intent.class} ), @TestTargetNew( level = TestLevel.COMPLETE, method = "unbindService", args = {ServiceConnection.class} ) }) public void testAccessService() throws InterruptedException { MockContextWrapperService.reset(); bindExpectResult(mContextWrapper, new Intent(mContext, MockContextWrapperService.class)); // Check startService assertTrue(MockContextWrapperService.hadCalledOnStart()); // Check bindService assertTrue(MockContextWrapperService.hadCalledOnBind()); assertTrue(MockContextWrapperService.hadCalledOnDestory()); // Check unbinService assertTrue(MockContextWrapperService.hadCalledOnUnbind()); } @TestTargetNew( level = TestLevel.COMPLETE, method = "getPackageCodePath", args = {} ) public void testGetPackageCodePath() { assertNotNull(mContextWrapper.getPackageCodePath()); } @TestTargetNew( level = TestLevel.COMPLETE, method = "getPackageName", args = {} ) public void testGetPackageName() { assertEquals("com.android.cts.stub", mContextWrapper.getPackageName()); } @TestTargetNew( level = TestLevel.COMPLETE, method = "getCacheDir", args = {} ) public void testGetCacheDir() { assertNotNull(mContextWrapper.getCacheDir()); } @TestTargetNew( level = TestLevel.COMPLETE, method = "getContentResolver", args = {} ) public void testGetContentResolver() { assertSame(mContext.getContentResolver(), mContextWrapper.getContentResolver()); } @TestTargets({ @TestTargetNew( level = TestLevel.COMPLETE, method = "attachBaseContext", args = {Context.class} ), @TestTargetNew( level = TestLevel.COMPLETE, method = "getBaseContext", args = {} ) }) public void testAccessBaseContext() throws PackageManager.NameNotFoundException { MockContextWrapper testContextWrapper = new MockContextWrapper(mContext); // Test getBaseContext() assertSame(mContext, testContextWrapper.getBaseContext()); Context secondContext = testContextWrapper.createPackageContext(getValidPackageName(), Context.CONTEXT_IGNORE_SECURITY); assertNotNull(secondContext); // Test attachBaseContext try { testContextWrapper.attachBaseContext(secondContext); fail("If base context has already been set, it should throw a IllegalStateException."); } catch (IllegalStateException e) { } } @TestTargetNew( level = TestLevel.COMPLETE, method = "getFileStreamPath", args = {String.class} ) public void testGetFileStreamPath() { String TEST_FILENAME = "TestGetFileStreamPath"; // Test the path including the input filename String fileStreamPath = mContextWrapper.getFileStreamPath(TEST_FILENAME).toString(); assertTrue(fileStreamPath.indexOf(TEST_FILENAME) >= 0); } @TestTargetNew( level = TestLevel.COMPLETE, method = "getClassLoader", args = {} ) public void testGetClassLoader() { assertSame(mContext.getClassLoader(), mContextWrapper.getClassLoader()); } @TestTargets({ @TestTargetNew( level = TestLevel.COMPLETE, method = "getWallpaperDesiredMinimumHeight", args = {} ), @TestTargetNew( level = TestLevel.COMPLETE, method = "getWallpaperDesiredMinimumWidth", args = {} ) }) public void testGetWallpaperDesiredMinimumHeightAndWidth() { int height = mContextWrapper.getWallpaperDesiredMinimumHeight(); int width = mContextWrapper.getWallpaperDesiredMinimumWidth(); // returned value is <= 0, the caller should use the height of the // default display instead. // That is to say, the return values of desired minimumHeight and // minimunWidth are at the same side of 0-dividing line. assertTrue((height > 0 && width > 0) || (height <= 0 && width <= 0)); } @TestTargets({ @TestTargetNew( level = TestLevel.COMPLETE, method = "sendStickyBroadcast", args = {Intent.class} ), @TestTargetNew( level = TestLevel.COMPLETE, method = "removeStickyBroadcast", args = {Intent.class} ) }) public void testAccessStickyBroadcast() throws InterruptedException { ResultReceiver resultReceiver = new ResultReceiver(); Intent intent = new Intent(MOCK_STICKY_ACTION); TestBroadcastReceiver stickyReceiver = new TestBroadcastReceiver(); mContextWrapper.sendStickyBroadcast(intent); waitForReceiveBroadCast(resultReceiver); assertEquals(intent.getAction(), mContextWrapper.registerReceiver(stickyReceiver, new IntentFilter(MOCK_STICKY_ACTION)).getAction()); synchronized (mLockObj) { mLockObj.wait(BROADCAST_TIMEOUT); } assertTrue("Receiver didn't make any response.", stickyReceiver.hadReceivedBroadCast()); mContextWrapper.unregisterReceiver(stickyReceiver); mContextWrapper.removeStickyBroadcast(intent); assertNull(mContextWrapper.registerReceiver(stickyReceiver, new IntentFilter(MOCK_STICKY_ACTION))); mContextWrapper.unregisterReceiver(stickyReceiver); } @TestTargetNew( level = TestLevel.COMPLETE, method = "checkCallingOrSelfUriPermission", args = {Uri.class, int.class} ) public void testCheckCallingOrSelfUriPermission() { Uri uri = Uri.parse("content://ctstest"); int retValue = mContextWrapper.checkCallingOrSelfUriPermission(uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION); assertEquals(PackageManager.PERMISSION_DENIED, retValue); } @TestTargetNew( level = TestLevel.COMPLETE, method = "grantUriPermission", args = {String.class, Uri.class, int.class} ) @ToBeFixed(bug = "1400249", explanation = "Can't test the effect of this function," + " should be tested by functional test.") public void testGrantUriPermission() { mContextWrapper.grantUriPermission("com.android.mms", Uri.parse("contents://ctstest"), Intent.FLAG_GRANT_WRITE_URI_PERMISSION); } @TestTargetNew( level = TestLevel.COMPLETE, method = "enforcePermission", args = {String.class, int.class, int.class, String.class} ) public void testEnforcePermission() { try { mContextWrapper.enforcePermission( PERMISSION_HARDWARE_TEST, Binder.getCallingPid(), Binder.getCallingUid(), "enforcePermission is not working without possessing an IPC."); fail("enforcePermission is not working without possessing an IPC."); } catch (SecurityException e) { // If the function is ok, it should throw a SecurityException here // because currently no IPC is handled by this process. } } @TestTargetNew( level = TestLevel.COMPLETE, method = "checkUriPermission", args = {Uri.class, int.class, int.class, int.class} ) public void testCheckUriPermission1() { Uri uri = Uri.parse("content://ctstest"); int retValue = mContextWrapper.checkUriPermission(uri, Binder.getCallingPid(), 0, Intent.FLAG_GRANT_WRITE_URI_PERMISSION); assertEquals(PackageManager.PERMISSION_GRANTED, retValue); retValue = mContextWrapper.checkUriPermission(uri, Binder.getCallingPid(), Binder.getCallingUid(), Intent.FLAG_GRANT_WRITE_URI_PERMISSION); assertEquals(PackageManager.PERMISSION_DENIED, retValue); } @TestTargetNew( level = TestLevel.COMPLETE, method = "checkUriPermission", args = {Uri.class, String.class, String.class, int.class, int.class, int.class} ) public void testCheckUriPermission2() { Uri uri = Uri.parse("content://ctstest"); int retValue = mContextWrapper.checkUriPermission(uri, PERMISSION_HARDWARE_TEST, PERMISSION_HARDWARE_TEST, Binder.getCallingPid(), 0, Intent.FLAG_GRANT_WRITE_URI_PERMISSION); assertEquals(PackageManager.PERMISSION_GRANTED, retValue); retValue = mContextWrapper.checkUriPermission(uri, PERMISSION_HARDWARE_TEST, PERMISSION_HARDWARE_TEST, Binder.getCallingPid(), Binder.getCallingUid(), Intent.FLAG_GRANT_WRITE_URI_PERMISSION); assertEquals(PackageManager.PERMISSION_DENIED, retValue); } @TestTargetNew( level = TestLevel.COMPLETE, method = "checkCallingPermission", args = {java.lang.String.class} ) public void testCheckCallingPermission() { int retValue = mContextWrapper.checkCallingPermission(PERMISSION_HARDWARE_TEST); assertEquals(PackageManager.PERMISSION_DENIED, retValue); } @TestTargetNew( level = TestLevel.COMPLETE, method = "checkCallingUriPermission", args = {Uri.class, int.class} ) public void testCheckCallingUriPermission() { Uri uri = Uri.parse("content://ctstest"); int retValue = mContextWrapper.checkCallingUriPermission(uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION); assertEquals(PackageManager.PERMISSION_DENIED, retValue); } @TestTargetNew( level = TestLevel.COMPLETE, method = "enforceCallingUriPermission", args = {Uri.class, int.class, String.class} ) public void testEnforceCallingUriPermission() { try { Uri uri = Uri.parse("content://ctstest"); mContextWrapper.enforceCallingUriPermission(uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION, "enforceCallingUriPermission is not working without possessing an IPC."); fail("enforceCallingUriPermission is not working without possessing an IPC."); } catch (SecurityException e) { // If the function is OK, it should throw a SecurityException here because currently no // IPC is handled by this process. } } @TestTargetNew( level = TestLevel.COMPLETE, method = "getDir", args = {String.class, int.class} ) public void testGetDir() { File dir = mContextWrapper.getDir("testpath", Context.MODE_WORLD_WRITEABLE); assertNotNull(dir); dir.delete(); } @TestTargetNew( level = TestLevel.COMPLETE, method = "getPackageManager", args = {} ) public void testGetPackageManager() { assertSame(mContext.getPackageManager(), mContextWrapper.getPackageManager()); } @TestTargetNew( level = TestLevel.COMPLETE, method = "checkCallingOrSelfPermission", args = {String.class} ) public void testCheckCallingOrSelfPermission() { int retValue = mContextWrapper.checkCallingOrSelfPermission("android.permission.GET_TASKS"); assertEquals(PackageManager.PERMISSION_GRANTED, retValue); } @TestTargetNew( level = TestLevel.COMPLETE, method = "sendBroadcast", args = {Intent.class} ) public void testSendBroadcast1() throws InterruptedException { final ResultReceiver receiver = new ResultReceiver(); registerBroadcastReceiver(receiver, new IntentFilter(ResultReceiver.MOCK_ACTION)); mContextWrapper.sendBroadcast(new Intent(ResultReceiver.MOCK_ACTION)); new DelayedCheck(BROADCAST_TIMEOUT){ @Override protected boolean check() { return receiver.hasReceivedBroadCast(); } }.run(); } @TestTargetNew( level = TestLevel.COMPLETE, method = "sendBroadcast", args = {Intent.class, String.class} ) public void testSendBroadcast2() throws InterruptedException { final ResultReceiver receiver = new ResultReceiver(); registerBroadcastReceiver(receiver, new IntentFilter(ResultReceiver.MOCK_ACTION)); mContextWrapper.sendBroadcast(new Intent(ResultReceiver.MOCK_ACTION), null); new DelayedCheck(BROADCAST_TIMEOUT){ @Override protected boolean check() { return receiver.hasReceivedBroadCast(); } }.run(); } @TestTargetNew( level = TestLevel.COMPLETE, method = "enforceCallingOrSelfUriPermission", args = {Uri.class, int.class, String.class} ) public void testEnforceCallingOrSelfUriPermission() { try { Uri uri = Uri.parse("content://ctstest"); mContextWrapper.enforceCallingOrSelfUriPermission(uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION, "enforceCallingOrSelfUriPermission is not working without possessing an IPC."); fail("enforceCallingOrSelfUriPermission is not working without possessing an IPC."); } catch (SecurityException e) { // If the function is OK, it should throw a SecurityException here because currently no // IPC is handled by this process. } } @TestTargetNew( level = TestLevel.COMPLETE, method = "checkPermission", args = {String.class, int.class, int.class} ) public void testCheckPermission() { // Test with root user, everything will be granted. int returnValue = mContextWrapper.checkPermission(PERMISSION_HARDWARE_TEST, 1, 0); assertEquals(PackageManager.PERMISSION_GRANTED, returnValue); // Test with non-root user, only included granted permission. returnValue = mContextWrapper.checkPermission(PERMISSION_HARDWARE_TEST, 1, 1); assertEquals(PackageManager.PERMISSION_DENIED, returnValue); // Test with null permission. try { returnValue = mContextWrapper.checkPermission(null, 0, 0); fail("checkPermission should not accept null permission"); } catch (IllegalArgumentException e) { } // Test with invalid uid and included granted permission. returnValue = mContextWrapper.checkPermission("android.permission.GET_TASKS", 1, -11); assertEquals(PackageManager.PERMISSION_DENIED, returnValue); } @TestTargetNew( level = TestLevel.COMPLETE, method = "getSystemService", args = {String.class} ) public void testGetSystemService() { // Test invalid service name assertNull(mContextWrapper.getSystemService("invalid")); // Test valid service name assertNotNull(mContextWrapper.getSystemService(Context.WINDOW_SERVICE)); } @TestTargetNew( level = TestLevel.COMPLETE, method = "getAssets", args = {} ) public void testGetAssets() { assertSame(mContext.getAssets(), mContextWrapper.getAssets()); } @TestTargetNew( level = TestLevel.COMPLETE, method = "getResources", args = {} ) public void testGetResources() { assertSame(mContext.getResources(), mContextWrapper.getResources()); } @TestTargetNew( level = TestLevel.COMPLETE, method = "startInstrumentation", args = {android.content.ComponentName.class, java.lang.String.class, android.os.Bundle.class} ) public void testStartInstrumentation() { // Use wrong name ComponentName cn = new ComponentName("com.android", "com.android.content.FalseLocalSampleInstrumentation"); assertNotNull(cn); assertNotNull(mContextWrapper); // If the target instrumentation is wrong, the function should return false. assertFalse(mContextWrapper.startInstrumentation(cn, null, null)); } private void bindExpectResult(Context contextWrapper, Intent service) throws InterruptedException { if (service == null) { fail("No service created!"); } TestConnection conn = new TestConnection(true, false); contextWrapper.bindService(service, conn, Context.BIND_AUTO_CREATE); contextWrapper.startService(service); // Wait for a short time, so the service related operations could be // working. synchronized (this) { wait(2500); } // Test stop Service assertTrue(contextWrapper.stopService(service)); contextWrapper.unbindService(conn); synchronized (this) { wait(1000); } } private interface Condition { public boolean onCondition(); } private synchronized void waitForCondition(Condition con) throws InterruptedException { // check the condition every 1 second until the condition is fulfilled // and wait for 3 seconds at most for (int i = 0; !con.onCondition() && i <= 3; i++) { wait(1000); } } private void waitForReceiveBroadCast(final ResultReceiver receiver) throws InterruptedException { Condition con = new Condition() { public boolean onCondition() { return receiver.hasReceivedBroadCast(); } }; waitForCondition(con); } private void waitForFilteredIntent(ContextWrapper contextWrapper, final FilteredReceiver receiver, final String action) throws InterruptedException { contextWrapper.sendOrderedBroadcast(new Intent(action), null); synchronized (mLockObj) { mLockObj.wait(BROADCAST_TIMEOUT); } } private static final class MockContextWrapper extends ContextWrapper { public MockContextWrapper(Context base) { super(base); } @Override public void attachBaseContext(Context base) { super.attachBaseContext(base); } } private final class TestBroadcastReceiver extends BroadcastReceiver { boolean mHadReceivedBroadCast; boolean mIsOrderedBroadcasts; @Override public void onReceive(Context context, Intent intent) { synchronized (this) { if (mIsOrderedBroadcasts) { setResultCode(3); setResultData(ACTUAL_RESULT); } Bundle map = getResultExtras(false); if (map != null) { map.remove(KEY_REMOVED); map.putString(KEY_ADDED, VALUE_ADDED); } mHadReceivedBroadCast = true; this.notifyAll(); } synchronized (mLockObj) { mLockObj.notify(); } } boolean hadReceivedBroadCast() { return mHadReceivedBroadCast; } void reset(){ mHadReceivedBroadCast = false; } } private class FilteredReceiver extends BroadcastReceiver { private boolean mHadReceivedBroadCast1 = false; private boolean mHadReceivedBroadCast2 = false; public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (MOCK_ACTION1.equals(action)) { mHadReceivedBroadCast1 = true; } else if (MOCK_ACTION2.equals(action)) { mHadReceivedBroadCast2 = true; } synchronized (mLockObj) { mLockObj.notify(); } } public boolean hadReceivedBroadCast1() { return mHadReceivedBroadCast1; } public boolean hadReceivedBroadCast2() { return mHadReceivedBroadCast2; } public void reset(){ mHadReceivedBroadCast1 = false; mHadReceivedBroadCast2 = false; } } private class TestConnection implements ServiceConnection { public TestConnection(boolean expectDisconnect, boolean setReporter) { } void setMonitor(boolean v) { } public void onServiceConnected(ComponentName name, IBinder service) { } public void onServiceDisconnected(ComponentName name) { } } }
false
false
null
null
diff --git a/src/freemail/utils/PropsFile.java b/src/freemail/utils/PropsFile.java index 0e756ad..240875e 100644 --- a/src/freemail/utils/PropsFile.java +++ b/src/freemail/utils/PropsFile.java @@ -1,227 +1,228 @@ /* * PropsFile.java * This file is part of Freemail * Copyright (C) 2006,2008 Dave Baker * Copyright (C) 2008 Alexander Lehmann * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package freemail.utils; import java.io.File; import java.io.FileReader; import java.io.FileOutputStream; import java.io.PrintWriter; import java.io.BufferedReader; import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.Hashtable; public class PropsFile { // substitute static methods for constructor private static final Hashtable<String, PropsFile> propsList=new Hashtable<String, PropsFile>(); private static int reapCounter = 0; /// We go through the list and remove stale entries once in this many times a PropsFile is created private static final int reapEvery = 20; public static synchronized PropsFile createPropsFile(File f, boolean stopAtBlank) { if (reapCounter == reapEvery) { reapOld(); reapCounter = 0; } else { ++reapCounter; } String fn=f.getPath(); PropsFile pf=propsList.get(fn); if(pf!=null) { return pf; } else { pf=new PropsFile(f, stopAtBlank); propsList.put(fn, pf); return pf; } } public static PropsFile createPropsFile(File f) { return createPropsFile(f, false); } public static void reapOld() { Logger.debug(PropsFile.class, "Cleaning up stale PropsFiles"); Iterator<Map.Entry<String, PropsFile>> i = propsList.entrySet().iterator(); while (i.hasNext()) { Map.Entry<String, PropsFile> entry = i.next(); File f = new File(entry.getKey()); if (!f.exists()) { Logger.debug(PropsFile.class, "Removing "+f.getPath()); i.remove(); } } } private final File file; private HashMap<String, String> data; private BufferedReader bufrdr; private String commentPrefix; private String header; /** Pass true into stopAtBlank to cause the reader to stop upon encountering * a blank line. It's the the caller's responsibility to get * (using the getReader() method) the stream and close it properly. */ private PropsFile(File f, boolean stopAtBlank) { this.file = f; this.data = null; if (f.exists()) { try { this.bufrdr = this.read(stopAtBlank); } catch (IOException ioe) { } } this.commentPrefix = null; this.header = null; } public void setCommentPrefix(String cp) { this.commentPrefix = cp; } public void setHeader(String hdr) { this.header = hdr; } private synchronized BufferedReader read(boolean stopAtBlank) throws IOException { this.data = new HashMap<String, String>(); BufferedReader br = new BufferedReader(new FileReader(this.file)); String line = null; while ( (line = br.readLine()) != null) { if (this.commentPrefix != null && line.startsWith(this.commentPrefix)) { continue; } if (stopAtBlank && line.length() == 0) { return br; } String[] parts = line.split("=", 2); if (parts.length < 2) continue; this.data.put(parts[0], parts[1]); } br.close(); return null; } public BufferedReader getReader() { return this.bufrdr; } public void closeReader() { if (this.bufrdr == null) return; try { this.bufrdr.close(); } catch (IOException ioe) { } } private synchronized void write() throws IOException { - if(!file.getParentFile().exists()) { - if(!file.getParentFile().mkdirs()) { + File parentDir = file.getParentFile(); + if(parentDir != null && !parentDir.exists()) { + if(!parentDir.mkdirs()) { Logger.error(this, "Couldn't create parent directory of " + file); throw new IOException("Couldn't create parent directory of " + file); } } PrintWriter pw = new PrintWriter(new FileOutputStream(this.file)); if (this.header != null) pw.println(this.header); Iterator<Map.Entry<String, String>> i = this.data.entrySet().iterator(); while (i.hasNext()) { Map.Entry<String, String> e = i.next(); String key = e.getKey(); String val = e.getValue(); pw.println(key+"="+val); } pw.close(); } public String get(String key) { if (this.data == null) return null; return this.data.get(key); } public boolean put(String key, String val) { if (this.data == null) { this.data = new HashMap<String, String>(); } Object o = this.data.put(key, val); if (o == null || !o.equals(val)) { try { this.write(); } catch (IOException ioe) { ioe.printStackTrace(); return false; } } return true; } public boolean put(String key, long val) { return this.put(key, Long.toString(val)); } public boolean exists() { return this.file.exists(); } public Set<String> listProps() { return this.data.keySet(); } public boolean remove(String key) { if (this.data.containsKey(key)) { this.data.remove(key); try { this.write(); } catch (IOException ioe) { ioe.printStackTrace(); return false; } } return true; } @Override public String toString() { return file.getPath(); } }
true
true
private synchronized void write() throws IOException { if(!file.getParentFile().exists()) { if(!file.getParentFile().mkdirs()) { Logger.error(this, "Couldn't create parent directory of " + file); throw new IOException("Couldn't create parent directory of " + file); } } PrintWriter pw = new PrintWriter(new FileOutputStream(this.file)); if (this.header != null) pw.println(this.header); Iterator<Map.Entry<String, String>> i = this.data.entrySet().iterator(); while (i.hasNext()) { Map.Entry<String, String> e = i.next(); String key = e.getKey(); String val = e.getValue(); pw.println(key+"="+val); } pw.close(); }
private synchronized void write() throws IOException { File parentDir = file.getParentFile(); if(parentDir != null && !parentDir.exists()) { if(!parentDir.mkdirs()) { Logger.error(this, "Couldn't create parent directory of " + file); throw new IOException("Couldn't create parent directory of " + file); } } PrintWriter pw = new PrintWriter(new FileOutputStream(this.file)); if (this.header != null) pw.println(this.header); Iterator<Map.Entry<String, String>> i = this.data.entrySet().iterator(); while (i.hasNext()) { Map.Entry<String, String> e = i.next(); String key = e.getKey(); String val = e.getValue(); pw.println(key+"="+val); } pw.close(); }
diff --git a/src/gui/inventory/InventoryController.java b/src/gui/inventory/InventoryController.java index e2d2a3e..34439fb 100644 --- a/src/gui/inventory/InventoryController.java +++ b/src/gui/inventory/InventoryController.java @@ -1,631 +1,631 @@ package gui.inventory; import static ch.lambdaj.Lambda.*; import gui.common.*; import gui.item.*; import gui.product.*; import java.util.*; import org.joda.time.DateTime; -import common.TestEnvironment; +import model.tempmain.TestEnvironment; import model.common.Barcode; import model.common.ModelFacade; import model.common.Size; import model.common.VaultPickler; import model.item.Item; import model.item.ItemVault; import model.product.Product; import model.product.ProductVault; import model.productcontainer.*; /** * Controller class for inventory view. */ public class InventoryController extends Controller implements IInventoryController, Observer { ModelFacade _mf = new ModelFacade(); VaultPickler _pickler; /** * Constructor. * * @param view Reference to the inventory view */ public InventoryController(IInventoryView view) { super(view); _pickler = new VaultPickler(); _pickler.DeSerializeMe(); - this.addSampleItems(); +// this.addSampleItems(); construct(); StorageUnitVault.getInstance().addObserver(this); ProductGroupVault.getInstance().addObserver(this); ProductVault.getInstance().addObserver(this); ItemVault.getInstance().addObserver(this); } /** * Returns a reference to the view for this controller. */ @Override protected IInventoryView getView() { return (IInventoryView)super.getView(); } private ProductContainerData currentlySelectedPC; private ProductData currentlySelectedP; private int currentlySelectedPId = -1; private int currentlySelectedPCId = -1; public void setCurrentlySelectedProduct(int i){ this.currentlySelectedPId = i; } public void setCurrentlySelectedProductContainer(int i){ this.currentlySelectedPCId = i; } /** * Loads data into the controller's view. * * {@pre None} * * {@post The controller has loaded data into its view} */ @Override protected void loadValues() { ProductContainerData root = new ProductContainerData(); if (this.currentlySelectedPCId == -2) this.currentlySelectedPC = root; //currentlySelectedPC = getView().getSelectedProductContainer(); //if(currentlySelectedPC != null) // currentlySelectedPCId = ((Number) currentlySelectedPC.getTag()).intValue(); //Get all available storage units List<StorageUnit> storageUnits = new ArrayList<StorageUnit>(); storageUnits = (List)_mf.storageUnitVault.findAll("Deleted = %o", false); storageUnits = sort(storageUnits, (on(ProductContainer.class).getLowerCaseName())); //For each storage unit add all it's children productGroups for(StorageUnit su : storageUnits){ ProductContainerData tempSU = new ProductContainerData(su.getName()); if(su.getId() == this.currentlySelectedPCId) this.currentlySelectedPC = tempSU; //tempSU.setTag(su.getId()); root.addChild(addChildrenProductContainers(su,tempSU)); } getView().setProductContainers(root); if(currentlySelectedPC != null) getView().selectProductContainer(currentlySelectedPC); if(getView().getSelectedProductContainer() != null) this.productContainerSelectionChanged(); } private void addSampleItems(){ TestEnvironment env = new TestEnvironment(12, 350); env.newEnvironment(); } /* * Add all children to pc, recursive call */ private ProductContainerData addChildrenProductContainers(ProductContainer pc, ProductContainerData pcData){ //Get list of all productGroups in PC List<ProductGroup> productGroups = new ArrayList<ProductGroup>(); productGroups = (List)_mf.productGroupVault.findAll("ParentId = %o", pc.getId()); productGroups = sort(productGroups, (on(ProductContainer.class).getLowerCaseName())); //Loop through each product group and add it to PC for(ProductGroup pg : productGroups){ //Create a new data object from the product group ProductContainerData tempPC = new ProductContainerData(pg.getName()); pcData.addChild(addChildrenProductContainers(pg,tempPC)); if(pg.getId() == this.currentlySelectedPCId) this.currentlySelectedPC = tempPC; } pcData.setTag(pc.getId()); return pcData; } /** * Sets the enable/disable state of all components in the controller's view. * A component should be enabled only if the user is currently * allowed to interact with that component. * * {@pre None} * * {@post The enable/disable state of all components in the controller's view * have been set appropriately.} */ @Override protected void enableComponents() { return; } // // IInventoryController overrides // /** * Returns true if and only if the "Add Storage Unit" menu item should be enabled. * * This is always enabled */ @Override public boolean canAddStorageUnit() { return true; } /** * Returns true if and only if the "Add Items" menu item should be enabled. * * This is always enabled */ @Override public boolean canAddItems() { return true; } /** * Returns true if and only if the "Transfer Items" menu item should be enabled. * * This is always enabled */ @Override public boolean canTransferItems() { return true; } /** * Returns true if and only if the "Remove Items" menu item should be enabled. * * This is always enabled */ @Override public boolean canRemoveItems() { return true; } /** * Returns true if and only if the "Delete Storage Unit" menu item should be enabled. * * *Can only be deleted if there are no items */ @Override public boolean canDeleteStorageUnit() { ProductContainerData selectedContainerData = getView().getSelectedProductContainer(); if (selectedContainerData != null) { int id = -1; if(selectedContainerData.getTag() != null) id = ((Number) selectedContainerData.getTag()).intValue(); ProductGroup selectedProductGroup = _mf.productGroupVault.get(id); StorageUnit selectedStorageUnit = _mf.storageUnitVault.get(id); if(selectedProductGroup!=null){ return selectedProductGroup.isDeleteable().getStatus(); } else { return selectedStorageUnit.isDeleteable().getStatus(); } } return false; } /** * This method is called when the user selects the "Delete Storage Unit" menu item. * * Must delete it's self as well as all sum children */ @Override public void deleteStorageUnit() { ProductContainerData selectedContainerData = getView().getSelectedProductContainer(); int id = -1; if(selectedContainerData.getTag() != null) id = ((Number) selectedContainerData.getTag()).intValue(); StorageUnit selectedStorageUnit = _mf.storageUnitVault.get(id); selectedStorageUnit.delete(); selectedStorageUnit.save(); } /** * Returns true if and only if the "Edit Storage Unit" menu item should be enabled. * * This is always enabled */ @Override public boolean canEditStorageUnit() { return true; } /** * Returns true if and only if the "Add Product Group" menu item should be enabled. * * This is always enabled */ @Override public boolean canAddProductGroup() { return true; } /** * Returns true if and only if the "Delete Product Group" menu item should be enabled. * * * Same as storage unit */ @Override public boolean canDeleteProductGroup() { return this.canDeleteStorageUnit(); } /** * Returns true if and only if the "Edit Product Group" menu item should be enabled. * * This is always enabled */ @Override public boolean canEditProductGroup() { return true; } /** * This method is called when the user selects the "Delete Product Group" menu item. */ @Override public void deleteProductGroup() { ProductContainerData selectedContainerData = getView().getSelectedProductContainer(); int id = -1; if(selectedContainerData.getTag() != null) id = ((Number) selectedContainerData.getTag()).intValue(); ProductGroup selectedProductGroup = _mf.productGroupVault.get(id); selectedProductGroup.delete(); selectedProductGroup.save(); } private Random rand = new Random(); private String getRandomBarcode() { Random rand = new Random(); StringBuilder barcode = new StringBuilder(); for (int i = 0; i < 12; ++i) { barcode.append(((Integer)rand.nextInt(10)).toString()); } return barcode.toString(); } /** * This method is called when the selected item container changes. */ @Override public void productContainerSelectionChanged() { List<ProductData> productDataList = new ArrayList<ProductData>(); ProductContainerData selectedContainerData = getView().getSelectedProductContainer(); if (selectedContainerData != null) { //Get list of all productGroups in PC List<Product> products = new ArrayList<Product>(); int id = -1; if(selectedContainerData.getTag() != null) id = ((Number) selectedContainerData.getTag()).intValue(); ProductGroup selectedProductGroup = _mf.productGroupVault.get(id); StorageUnit selectedStorageUnit = _mf.storageUnitVault.get(id); this.currentlySelectedPCId = id; //Is a storage unit or a product group selected if(selectedStorageUnit != null){ products = (List)_mf.productVault.findAll("ContainerId = %o", selectedStorageUnit.getId()); getView().setContextUnit(selectedStorageUnit.getName()); getView().setContextGroup(""); getView().setContextSupply(""); } else if(selectedProductGroup != null){ products = (List)_mf.productVault.findAll("ContainerId = %o", selectedProductGroup.getId()); getView().setContextUnit(selectedProductGroup.getStorageUnit().getName()); getView().setContextGroup(selectedProductGroup.getName()); //getView().setContextSupply(selectedProductGroup.get3MonthSupply().toString()); } else { products = (List)_mf.productVault.findAll("Deleted = %o", false); // This means that the root is selected. this.currentlySelectedPCId = -2; getView().setContextUnit("All"); getView().setContextGroup(""); getView().setContextSupply(""); } products = sort(products, (on(Product.class).getDescriptionSort())); productDataList = GuiModelConverter.wrapProducts(products); ProductData selP = findSelectedP(productDataList); currentlySelectedP = (selP != null) ? selP : currentlySelectedP; } getView().setItems(new ItemData[0]); getView().setProducts(productDataList.toArray(new ProductData[0])); if(currentlySelectedP != null){ getView().selectProduct(this.currentlySelectedP); if(getView().getSelectedProduct() != null) this.productSelectionChanged(); } } /** * This just looks through the list to find the currently selected product. * Returns null if none is found. */ private ProductData findSelectedP(List<ProductData> plist){ for (ProductData p : plist){ if (((Number)p.getTag()).intValue() == this.currentlySelectedPId){ return p; } } return null; } /** * This method is called when the selected item changes. */ @Override public void productSelectionChanged() { ProductData selectedProductData = getView().getSelectedProduct(); int id = -1; if(selectedProductData.getTag() != null) id = ((Number) selectedProductData.getTag()).intValue(); Product selectedProduct = _mf.productVault.get(id); this.currentlySelectedPId = id; /* The purpose of declaring this outside of the conditional statement is that we want the item list to be empty if no product is selected. */ List<ItemData> itemDataList = new ArrayList<ItemData>(); if (selectedProduct != null) { List<Item> items = new ArrayList<Item>(); items = (List)_mf.itemVault.findAll("ProductId = %o", id); items = sort(items, (on(Item.class).getEntryDate())); itemDataList = GuiModelConverter.wrapItems(items); } getView().setItems(itemDataList.toArray(new ItemData[0])); } /** * This method is called when the selected item changes. */ @Override public void itemSelectionChanged() { return; } /** * Returns true if and only if the "Delete Product" menu item should be enabled. */ @Override public boolean canDeleteProduct() { if(this.getView().getSelectedProduct() == null) return false; ProductData selectedProductData = getView().getSelectedProduct(); int id = -1; if(selectedProductData.getTag() != null) id = ((Number) selectedProductData.getTag()).intValue(); Product selectedProduct = _mf.productVault.get(id); return selectedProduct.isDeleteable().getStatus(); } /** * This method is called when the user selects the "Delete Product" menu item. */ @Override public void deleteProduct() { ProductData selectedProductData = getView().getSelectedProduct(); int id = -1; if(selectedProductData.getTag() != null) id = ((Number) selectedProductData.getTag()).intValue(); Product selectedProduct = _mf.productVault.get(id); selectedProduct.delete(); selectedProduct.save(); } /** * Returns true if and only if the "Edit Item" menu item should be enabled. * * */ @Override public boolean canEditItem() { if(this.getView().getSelectedItem() == null) return false; return true; } /** * This method is called when the user selects the "Edit Item" menu item. */ @Override public void editItem() { getView().displayEditItemView(); } /** * Returns true if and only if the "Remove Item" menu item should be enabled. */ @Override public boolean canRemoveItem() { if(this.getView().getSelectedItem() == null) return false; return true; } /** * This method is called when the user selects the "Remove Item" menu item. */ @Override public void removeItem() { ItemData selectedItemData = getView().getSelectedItem(); int id = -1; if(selectedItemData.getTag() != null) id = ((Number) selectedItemData.getTag()).intValue(); Item selectedItem = _mf.itemVault.get(id); selectedItem.delete(); selectedItem.save(); } /** * Returns true if and only if the "Edit Product" menu item should be enabled. */ @Override public boolean canEditProduct() { if(this.getView().getSelectedProduct() == null) return false; return true; } /** * This method is called when the user selects the "Add Product Group" menu item. */ @Override public void addProductGroup() { this.currentlySelectedPCId = _mf.productGroupVault.getLastIndex()+1; getView().displayAddProductGroupView(); } /** * This method is called when the user selects the "Add Items" menu item. */ @Override public void addItems() { getView().displayAddItemBatchView(); } /** * This method is called when the user selects the "Transfer Items" menu item. */ @Override public void transferItems() { getView().displayTransferItemBatchView(); } /** * This method is called when the user selects the "Remove Items" menu item. */ @Override public void removeItems() { getView().displayRemoveItemBatchView(); } /** * This method is called when the user selects the "Add Storage Unit" menu item. */ @Override public void addStorageUnit() { this.currentlySelectedPCId = _mf.storageUnitVault.getLastIndex()+1; getView().displayAddStorageUnitView(); } /** * This method is called when the user selects the "Edit Product Group" menu item. */ @Override public void editProductGroup() { getView().displayEditProductGroupView(); } /** * This method is called when the user selects the "Edit Storage Unit" menu item. */ @Override public void editStorageUnit() { getView().displayEditStorageUnitView(); } /** * This method is called when the user selects the "Edit Product" menu item. */ @Override public void editProduct() { getView().displayEditProductView(); } /** * This method is called when the user drags a product into a * product container. * * @param productData Product dragged into the target product container * @param containerData Target product container */ @Override public void addProductToContainer(ProductData productData, ProductContainerData containerData) { int id = -1; if(productData.getTag() != null) id = ((Number) productData.getTag()).intValue(); Product selectedProduct = _mf.productVault.get(id); id = -1; if(containerData.getTag() != null) id = ((Number) containerData.getTag()).intValue(); ProductGroup selectedProductGroup = _mf.productGroupVault.get(id); StorageUnit selectedStorageUnit = _mf.storageUnitVault.get(id); this.currentlySelectedPC = null; this.currentlySelectedPCId = id; if(selectedProductGroup!=null){ _mf.dragProduct(selectedProductGroup.getStorageUnit(), selectedProductGroup, selectedProduct); } else { _mf.dragProduct(selectedStorageUnit, selectedStorageUnit, selectedProduct); } } /** * This method is called when the user drags an item into * a product container. * * @param itemData Item dragged into the target product container * @param containerData Target product container */ @Override public void moveItemToContainer(ItemData itemData, ProductContainerData containerData) { int id = -1; if(itemData.getTag() != null) id = ((Number) itemData.getTag()).intValue(); Item selectedItem = _mf.itemVault.get(id); id = -1; if(containerData.getTag() != null) id = ((Number) containerData.getTag()).intValue(); ProductGroup selectedProductGroup = _mf.productGroupVault.get(id); StorageUnit selectedStorageUnit = _mf.storageUnitVault.get(id); this.currentlySelectedPC = null; this.currentlySelectedPCId = id; if(selectedProductGroup!=null){ _mf.dragItem(selectedProductGroup, selectedItem); } else { _mf.dragItem(selectedStorageUnit, selectedItem); } } /** * This method is called when the observed vaults are changes * * @param o Vault that is observed * @param arg Hint */ @Override public void update(Observable o, Object arg) { this.loadValues(); } } diff --git a/src/gui/reports/supply/SupplyReportController.java b/src/gui/reports/supply/SupplyReportController.java index b39e568..701e680 100644 --- a/src/gui/reports/supply/SupplyReportController.java +++ b/src/gui/reports/supply/SupplyReportController.java @@ -1,112 +1,111 @@ package gui.reports.supply; import java.awt.Desktop; import java.io.File; import java.io.IOException; import model.reports.*; import gui.common.*; /** * Controller class for the N-month supply report view. */ public class SupplyReportController extends Controller implements ISupplyReportController { /*--- STUDENT-INCLUDE-BEGIN /** * Constructor. * * @param view Reference to the N-month supply report view */ public SupplyReportController(IView view) { super(view); getView().setMonths("3"); construct(); } // // Controller overrides // /** * Returns a reference to the view for this controller. * * {@pre None} * * {@post Returns a reference to the view for this controller.} */ @Override protected ISupplyReportView getView() { return (ISupplyReportView)super.getView(); } /** * Sets the enable/disable state of all components in the controller's view. * A component should be enabled only if the user is currently * allowed to interact with that component. * * {@pre None} * * {@post The enable/disable state of all components in the controller's view * have been set appropriately.} */ @Override protected void enableComponents() { int months; try { months = Integer.parseInt(getView().getMonths()); } catch (NumberFormatException e) { - e.printStackTrace(); months = -1; } boolean valid = (months > 0 && months <= 100) ? true : false; getView().enableOK(valid); } /** * Loads data into the controller's view. * * {@pre None} * * {@post The controller has loaded data into its view} */ @Override protected void loadValues() { } // // IExpiredReportController overrides // /** * This method is called when any of the fields in the * N-month supply report view is changed by the user. */ @Override public void valuesChanged() { enableComponents(); } /** * This method is called when the user clicks the "OK" * button in the N-month supply report view. */ @Override public void display() { ReportBuilder builder = (getView().getFormat() == FileFormat.HTML) ? new HTMLReportBuilder() : new PDFReportBuilder(); IReportDirector director = new NSupplyReport(Integer.parseInt(this.getView().getMonths())); director.setBuilder(builder); director.constructReport(); if (Desktop.isDesktopSupported()) { try { File myFile = new File(builder.returnReport()); Desktop.getDesktop().open(myFile); } catch (IOException ex) { // no application registered for PDFs } } } }
false
false
null
null
diff --git a/src/main/java/org/acaro/graffiti/processing/GraffitiVertex.java b/src/main/java/org/acaro/graffiti/processing/GraffitiVertex.java index 155dee0..484247a 100644 --- a/src/main/java/org/acaro/graffiti/processing/GraffitiVertex.java +++ b/src/main/java/org/acaro/graffiti/processing/GraffitiVertex.java @@ -1,391 +1,395 @@ /* Copyright 2011 Claudio Martella * * 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.acaro.graffiti.processing; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeSet; import org.acaro.graffiti.query.Condition; import org.acaro.graffiti.query.LocationStep; import org.acaro.graffiti.query.Query; import org.acaro.graffiti.query.QueryParser; import org.apache.giraph.graph.BspUtils; import org.apache.giraph.graph.GiraphJob; import org.apache.giraph.graph.MutableVertex; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.util.Tool; import org.apache.log4j.Logger; public class GraffitiVertex extends MutableVertex<Text, Query, Text, GraffitiMessage> implements Tool { public static final String SOURCE_VX = "source_vertex"; public static final String QUERY = "query"; private static final Logger LOG = Logger.getLogger(GraffitiVertex.class); /* * It contains all the outgoing edges. Each entry in the hashmap represents an outgoing label. * Each element of the contained TreeSet are vertices on the other end of an edge with * that label. */ private final Map<Text, Set<Text>> labelledOutEdgeMap = new HashMap<Text, Set<Text>>(); private final List<GraffitiMessage> msgList = new ArrayList<GraffitiMessage>(); private Configuration conf; private GraffitiEmitter emitter; private Text vertexId = null; private Query query; private boolean halt = false; private int numOutEdges; @Override public void compute(Iterator<GraffitiMessage> messages) throws IOException { if (getSuperstep() == 0 && isSource()) { processMessage(new GraffitiMessage(this.query, new ResultSet())); } else { while (messages.hasNext()) { processMessage(messages.next()); } } voteToHalt(); } - private void processMessage(GraffitiMessage message) { + private void processMessage(GraffitiMessage message) throws IOException { Query query = message.getQuery(); LocationStep l = query.getLocationSteps().firstElement(); if (checkConditions(l) == false) { return; } Query newQuery = prepareNewQuery(query); String label = l.getEdge(); ResultSet r = message.getResults(); if (newQuery.isFinished()) { emitResults(label, new ResultSet(r)); } else { forwardMsg(label, new GraffitiMessage(newQuery, new ResultSet(r))); } } private boolean checkConditions(LocationStep l) { for (Condition c: l.getConditions()) { if (c.evaluate(this) == false) { return false; } } return true; } private Query prepareNewQuery(Query old) { Query newQuery = new Query(old); LocationStep l = newQuery.getLocationSteps().pop(); int rp = l.getRepeat(); if (rp > 0) { LocationStep newL = new LocationStep(l); newL.setRepeat(--rp); newQuery.getLocationSteps().push(newL); } return newQuery; } - private void emitResults(String label, ResultSet r) { + private void emitResults(String label, ResultSet r) throws IOException { r.add(getVertexId()); if (label.equals(LocationStep.EMPTY_EDGE)) { emit(r); } else { if (label.equals("*")) { for (Text tLabel: getEdgesLabels()) { emitWithLabel(tLabel, new ResultSet(r)); } } else { emitWithLabel(new Text(label), r); } } } - private void emitWithLabel(Text label, ResultSet r) { + private void emitWithLabel(Text label, ResultSet r) throws IOException { r.add(label); Set<Text> edges = labelledOutEdgeMap.get(label); if (edges != null) { for (Text v: edges) { ResultSet rslv = new ResultSet(r); rslv.add(v); emit(rslv); } } } - private void emit(ResultSet r) { + private void emit(ResultSet r) throws IOException { emitter.emit(r); } private void forwardMsg(String label, GraffitiMessage message) { if (label.equals("*")) { for (Text tLabel: getEdgesLabels()) { // "clone" it because they go through paths with different labels forwardMsgThroughLabel(tLabel, new GraffitiMessage(message)); } } else { forwardMsgThroughLabel(new Text(label), message); } } private void forwardMsgThroughLabel(Text label, GraffitiMessage message) { message.getResults().add(getVertexId()); message.getResults().add(label); Set<Text> edges = labelledOutEdgeMap.get(label); if (edges != null) { for (Text v: edges) { sendMsg(v, message); } } } private boolean isSource() { String source = getContext().getConfiguration().get(SOURCE_VX); return source.equals("*") || source.equals(getVertexId()); } public Set<Text> getEdgesByLabel(Text label) { return labelledOutEdgeMap.get(label); } public Set<Text> getEdgesLabels() { return labelledOutEdgeMap.keySet(); } @Override public void readFields(DataInput in) throws IOException { vertexId = BspUtils.<Text>createVertexIndex(getContext().getConfiguration()); vertexId.readFields(in); int edgeMapSize = in.readInt(); for (int i = 0; i < edgeMapSize; i++) { Text label = new Text(); label.readFields(in); int verticesSize = in.readInt(); for (int j = 0; j < verticesSize; j++) { Text vID = new Text(); vID.readFields(in); addEdge(vID, label); } } int msgListSize = in.readInt(); for (int i = 0; i < msgListSize; i++) { GraffitiMessage msg = BspUtils.<GraffitiMessage>createMessageValue( getContext().getConfiguration()); msg.readFields(in); msgList.add(msg); } halt = in.readBoolean(); } @Override public void write(DataOutput out) throws IOException { vertexId.write(out); out.writeInt(labelledOutEdgeMap.size()); for (Entry<Text, Set<Text>> label: labelledOutEdgeMap.entrySet()) { label.getKey().write(out); out.writeInt(label.getValue().size()); for (Text dest: label.getValue()) { dest.write(out); } } out.writeInt(msgList.size()); for (GraffitiMessage msg : msgList) { msg.write(out); } out.writeBoolean(halt); } @Override public boolean addEdge(Text vID, Text label) { Set<Text> set = labelledOutEdgeMap.get(label); if (set == null) { set = new TreeSet<Text>(); labelledOutEdgeMap.put(label, set); } boolean ret = set.add(vID); if (ret == true) { numOutEdges++; } return ret; } @Override public Text removeEdge(Text vID) { throw new UnsupportedOperationException("removeEdge should not be called"); } @Override public void setVertexId(Text vID) { this.vertexId = vID; } @Override public Text getEdgeValue(Text vID) { throw new UnsupportedOperationException("getEdgeValue should not be called"); } @Override public List<GraffitiMessage> getMsgList() { return this.msgList; } @Override public int getNumOutEdges() { return this.numOutEdges; } @Override public Text getVertexId() { return this.vertexId; } @Override public Query getVertexValue() { return this.query; } @Override public boolean hasEdge(Text vID) { throw new UnsupportedOperationException("hasEdge should not be called"); } @Override public boolean isHalted() { return this.halt; } @Override public Iterator<Text> iterator() { throw new UnsupportedOperationException("iterator should not be called"); } @Override public void postApplication() { - this.emitter.close(); + try { + this.emitter.close(); + } catch (IOException e) { + e.printStackTrace(); + } } @Override public void postSuperstep() { // Don't need this } @Override public void preApplication() throws InstantiationException, IllegalAccessException { this.emitter = GraffitiEmitter.getInstance(); } @Override public void preSuperstep() { // Don't need this } @Override public void sendMsgToAllEdges(GraffitiMessage m) { for (Set<Text> labelSet: labelledOutEdgeMap.values()) { for (Text v: labelSet) { sendMsg(v, m); } } } @Override public void setVertexValue(Query value) { this.query = value; } @Override public void voteToHalt() { this.halt = true; } /* * This is all Tool stuff */ @Override public Configuration getConf() { return this.conf; } @Override public void setConf(Configuration conf) { this.conf = conf; } @Override public int run(String[] args) throws Exception { if (args.length != 2) { throw new IllegalArgumentException( "run: Must have 2 arguments <input path> <query>"); } Query q = new QueryParser(args[1]).parse(); GiraphJob job = new GiraphJob(getConf(), getClass().getName()); job.setVertexClass(getClass()); job.setVertexInputFormatClass(GraffitiVertexInputFormat.class); FileInputFormat.addInputPath(job, new Path(args[0])); job.getConfiguration().set(GraffitiVertex.SOURCE_VX, q.getStartNode()); job.getConfiguration().set(GraffitiVertex.QUERY, args[1]); //job.setWorkerConfiguration(Integer.parseInt(argArray[3]), Integer.parseInt(argArray[3]), 100.0f); if (job.run(true) == true) { return 0; } else { return -1; } } }
false
false
null
null
diff --git a/ide/eclipse/esb/org.wso2.developerstudio.eclipse.artifact.endpoint/src/org/wso2/developerstudio/eclipse/artifact/endpoint/model/EndpointModel.java b/ide/eclipse/esb/org.wso2.developerstudio.eclipse.artifact.endpoint/src/org/wso2/developerstudio/eclipse/artifact/endpoint/model/EndpointModel.java index 84703a5e1..813bd9303 100644 --- a/ide/eclipse/esb/org.wso2.developerstudio.eclipse.artifact.endpoint/src/org/wso2/developerstudio/eclipse/artifact/endpoint/model/EndpointModel.java +++ b/ide/eclipse/esb/org.wso2.developerstudio.eclipse.artifact.endpoint/src/org/wso2/developerstudio/eclipse/artifact/endpoint/model/EndpointModel.java @@ -1,357 +1,360 @@ /* * Copyright (c) 2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * 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.wso2.developerstudio.eclipse.artifact.endpoint.model; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.OMException; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.Path; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.PlatformUI; import org.wso2.developerstudio.eclipse.artifact.endpoint.Activator; import org.wso2.developerstudio.eclipse.artifact.endpoint.utils.EpArtifactConstants; import org.wso2.developerstudio.eclipse.artifact.endpoint.validators.EndPointTemplateList; import org.wso2.developerstudio.eclipse.artifact.endpoint.validators.ProjectFilter; import org.wso2.developerstudio.eclipse.esb.core.utils.SynapseEntryType; import org.wso2.developerstudio.eclipse.esb.core.utils.SynapseFileUtils; import org.wso2.developerstudio.eclipse.esb.project.utils.ESBProjectUtils; import org.wso2.developerstudio.eclipse.general.project.utils.GeneralProjectUtils; import org.wso2.developerstudio.eclipse.logging.core.IDeveloperStudioLog; import org.wso2.developerstudio.eclipse.logging.core.Logger; import org.wso2.developerstudio.eclipse.platform.core.exception.ObserverFailedException; import org.wso2.developerstudio.eclipse.platform.core.project.model.ProjectDataModel; import org.wso2.developerstudio.eclipse.platform.core.templates.ArtifactTemplate; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.xml.stream.XMLStreamException; public class EndpointModel extends ProjectDataModel { private static IDeveloperStudioLog log=Logger.getLog(Activator.PLUGIN_ID); + + public static final String CONF_REG_ID = "2"; + public static final String GOV_REG_ID = "3"; private ArtifactTemplate selectedTemplate; private boolean saveAsDynamic = false; - private String registryPathID = "2"; + private String registryPathID = GOV_REG_ID; private String dynamicEpRegistryPath= new String(); private List<OMElement> availableEPList; private IContainer endpointSaveLocation; private String epName; private String addressEPURI; private String wsdlEPURI; private String wsdlEPService; private String wsdlEPPort; private String templateEPURI; private String templateEPTargetTemp = ""; private List<OMElement> selectedEPList=new ArrayList<OMElement>(); public Object getModelPropertyValue(String key) { Object modelPropertyValue = super.getModelPropertyValue(key); if (modelPropertyValue == null) { if (key.equals(EpArtifactConstants.WIZARD_OPTION_EP_TYPE)) { modelPropertyValue = getSelectedTemplate(); } else if (key.equals(EpArtifactConstants.WIZARD_OPTION_DYNAMIC_EP)) { modelPropertyValue = isSaveAsDynamic(); } else if (key.equals(EpArtifactConstants.WIZARD_OPTION_REGISTRY_TYPE)) { modelPropertyValue = getRegistryPathID(); } else if (key.equals(EpArtifactConstants.WIZARD_OPTION_SAVE_LOCATION)) { modelPropertyValue = getEndpointSaveLocation(); } else if(key.equals(EpArtifactConstants.WIZARD_OPTION_AVAILABLE_EPS)){ modelPropertyValue = selectedEPList.toArray(); } else if (key.equals(EpArtifactConstants.WIZARD_OPTION_REGISTRY_PATH)){ modelPropertyValue = getDynamicEpRegistryPath(); } } return modelPropertyValue; } public boolean setModelPropertyValue(String key, Object data) throws ObserverFailedException { boolean returnResult = super.setModelPropertyValue(key, data); if (key.equals(EpArtifactConstants.WIZARD_OPTION_IMPORT_FILE)) { if (getImportFile() != null && !getImportFile().toString().equals("")) { try { List<OMElement> availableEPs = new ArrayList<OMElement>(); if (SynapseFileUtils.isSynapseConfGiven(getImportFile(), SynapseEntryType.END_POINT)) { availableEPs = SynapseFileUtils.synapseFileProcessing(getImportFile().getPath(), SynapseEntryType.END_POINT); setAvailableEPList(availableEPs); getSelectedEPList().clear(); getSelectedEPList().addAll(availableEPs); } else { setAvailableEPList(new ArrayList<OMElement>()); } returnResult = false; } catch (OMException e) { log.error("Error reading object model", e); } catch (XMLStreamException e) { log.error("XML stream error", e); } catch (IOException e) { log.error("I/O error has occurred", e); } catch (Exception e) { log.error("An unexpected error has occurred", e); } } } else if (key.equals(EpArtifactConstants.WIZARD_OPTION_EP_TYPE)) { ArtifactTemplate template = (ArtifactTemplate) data; setSelectedTemplate(template); } else if (key.equals(EpArtifactConstants.WIZARD_OPTION_DYNAMIC_EP)) { setSaveAsDynamic((Boolean) data); ProjectFilter.setShowGeneralProjects((Boolean) data); setEndpointSaveLocation(""); } else if (key.equals(EpArtifactConstants.WIZARD_OPTION_REGISTRY_TYPE)) { setDynamicEpRegistryPath(""); setRegistryPathID(data.toString()); } else if (key.equals(EpArtifactConstants.WIZARD_OPTION_SAVE_LOCATION)) { setEndpointSaveLocation((IContainer) data); } else if (key.equals(EpArtifactConstants.WIZARD_OPTION_CREATE_ESB_PROJECT)) { if(isSaveAsDynamic()){ Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(); IProject generalProject = GeneralProjectUtils.createGeneralProject(shell); if(generalProject!=null){ setEndpointSaveLocation(generalProject); } } else{ Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(); IProject esbProject = ESBProjectUtils.createESBProject(shell); if(esbProject!=null){ setEndpointSaveLocation(esbProject); } } // TODO show wizard to create a esb project // get endpoint location of the esb project & set // endpointSaveLocation as it is }else if(key.equals(EpArtifactConstants.WIZARD_OPTION_EP_NAME)){ setEpName(data.toString()); }else if(key.equals(EpArtifactConstants.WIZARD_OPTION_TEMPLATE_ADDRESS_EP_URL)){ setAddressEPURI(data.toString()); }else if(key.equals(EpArtifactConstants.WIZARD_OPTION_TEMPLATE_WSDL_EP_URL)){ setWsdlEPURI(data.toString()); }else if(key.equals(EpArtifactConstants.WIZARD_OPTION_TEMPLATE_WSDL_EP_SERVICE)){ setWsdlEPService(data.toString()); }else if(key.equals(EpArtifactConstants.WIZARD_OPTION_TEMPLATE_WSDL_EP_SERVICE_PORT)){ setWsdlEPPort(data.toString()); }else if(key.equals(EpArtifactConstants.WIZARD_OPTION_TEMPLATE_TEMP_EP_URL)){ setTemplateEPURI(data.toString()); }else if(key.equals(EpArtifactConstants.WIZARD_OPTION_TEMPLATE_TEMP_TARGET)){ setTemplateEPTargetTemp(data.toString()); }else if(key.equals(EpArtifactConstants.WIZARD_OPTION_AVAILABLE_EPS)){ Object[] selectedEPs = (Object[])data; selectedEPList.clear(); for (Object object : selectedEPs) { if(object instanceof OMElement){ selectedEPList.add((OMElement)object); } } setSelectedEPList(selectedEPList); } else if (key.equals(EpArtifactConstants.WIZARD_OPTION_REGISTRY_PATH)){ if(null!=data){ setDynamicEpRegistryPath(data.toString()); } } return returnResult; } public void setSelectedTemplate(ArtifactTemplate selectedTemplate) { this.selectedTemplate = selectedTemplate; } public ArtifactTemplate getSelectedTemplate() { if(selectedTemplate == null){ ArtifactTemplate[] artifactTemplates = EndPointTemplateList.getArtifactTemplates(); if (artifactTemplates.length > 0) { selectedTemplate = artifactTemplates[0];// new // ArtifactTemplate("org.wso2.developerstudio.eclipse.esb.template.ep0", // "Default Endpoint"); } else { return null; } } return selectedTemplate; } public void setSaveAsDynamic(boolean saveAsDynamic) { this.saveAsDynamic = saveAsDynamic; } public boolean isSaveAsDynamic() { return saveAsDynamic; } public void setDynamicEpRegistryPath(String dynamicEpRegistryPath) { this.dynamicEpRegistryPath = dynamicEpRegistryPath; } public String getDynamicEpRegistryPath() { return dynamicEpRegistryPath; } public void setAvailableEPList(List<OMElement> availableEPList) { this.availableEPList = availableEPList; } public List<OMElement> getAvailableEPList() { return availableEPList; } public void setEndpointSaveLocation(IContainer endpointSaveLocation) { this.endpointSaveLocation = endpointSaveLocation; } public void setEndpointSaveLocation(String endpointSaveLocation) { this.endpointSaveLocation = ResourcesPlugin.getWorkspace().getRoot() .getContainerForLocation(new Path(endpointSaveLocation)); } public IContainer getEndpointSaveLocation() { return endpointSaveLocation; } public void setLocation(File location) { super.setLocation(location); File absolutionPath = getLocation(); if (getEndpointSaveLocation() == null && absolutionPath != null) { IContainer newEndpointSaveLocation = getContainer(absolutionPath, EpArtifactConstants.ESB_PROJECT_NATURE); setEndpointSaveLocation(newEndpointSaveLocation); } } public static IContainer getContainer(File absolutionPath, String projectNature) { IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects(); int length = 0; IProject currentSelection = null; for (IProject project : projects) { try { if (project.isOpen() && project.hasNature(projectNature)) { File projectLocation = project.getLocation().toFile(); int projectLocationLength = projectLocation.toString().length(); if (projectLocationLength > length && projectLocationLength <= absolutionPath.toString().length()) { if (absolutionPath.toString().startsWith(projectLocation.toString())) { length = projectLocationLength; currentSelection = project; } } } } catch (CoreException e) { log.error("An unexpected error has occurred", e); } } IContainer newEndpointSaveLocation = null; if (currentSelection != null) { String path = absolutionPath.toString().substring( currentSelection.getLocation().toFile() .toString().length()); if (path.equals("")) { newEndpointSaveLocation = currentSelection; } else { newEndpointSaveLocation = currentSelection.getFolder(path); } } return newEndpointSaveLocation; } public void setEpName(String epName) { this.epName = epName; } public String getEpName() { return epName; } public String getAddressEPURI() { return addressEPURI; } public void setAddressEPURI(String addressEPURI) { this.addressEPURI = addressEPURI; } public String getWsdlEPURI() { return wsdlEPURI; } public void setWsdlEPURI(String wsdlEPURI) { this.wsdlEPURI = wsdlEPURI; } public String getWsdlEPService() { return wsdlEPService; } public void setWsdlEPService(String wsdlEPService) { this.wsdlEPService = wsdlEPService; } public String getWsdlEPPort() { return wsdlEPPort; } public void setWsdlEPPort(String wsdlEPPort) { this.wsdlEPPort = wsdlEPPort; } public String getTemplateEPURI() { return templateEPURI; } public void setTemplateEPURI(String templateEPURI) { this.templateEPURI = templateEPURI; } public String getTemplateEPTargetTemp() { return templateEPTargetTemp; } public void setTemplateEPTargetTemp(String templateEPTargetTemp) { this.templateEPTargetTemp = templateEPTargetTemp; } public void setSelectedEPList(List<OMElement> selectedEPList) { this.selectedEPList = selectedEPList; } public List<OMElement> getSelectedEPList() { return selectedEPList; } public void setRegistryPathID(String registryPathID) { this.registryPathID = registryPathID; } public String getRegistryPathID() { return registryPathID; } } diff --git a/ide/eclipse/esb/org.wso2.developerstudio.eclipse.artifact.endpoint/src/org/wso2/developerstudio/eclipse/artifact/endpoint/ui/wizard/EndpointProjectCreationWizard.java b/ide/eclipse/esb/org.wso2.developerstudio.eclipse.artifact.endpoint/src/org/wso2/developerstudio/eclipse/artifact/endpoint/ui/wizard/EndpointProjectCreationWizard.java index 5a6f6b8f9..c921d9546 100644 --- a/ide/eclipse/esb/org.wso2.developerstudio.eclipse.artifact.endpoint/src/org/wso2/developerstudio/eclipse/artifact/endpoint/ui/wizard/EndpointProjectCreationWizard.java +++ b/ide/eclipse/esb/org.wso2.developerstudio.eclipse.artifact.endpoint/src/org/wso2/developerstudio/eclipse/artifact/endpoint/ui/wizard/EndpointProjectCreationWizard.java @@ -1,490 +1,502 @@ /* * Copyright (c) 2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * 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.wso2.developerstudio.eclipse.artifact.endpoint.ui.wizard; import static org.wso2.developerstudio.eclipse.platform.core.registry.util.Constants.REGISTRY_RESOURCE; +import static org.wso2.developerstudio.eclipse.artifact.endpoint.model.EndpointModel.*; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import javax.xml.namespace.QName; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.impl.builder.StAXOMBuilder; import org.apache.commons.lang.StringUtils; import org.apache.maven.model.Plugin; import org.apache.maven.model.PluginExecution; import org.apache.maven.model.Repository; import org.apache.maven.model.RepositoryPolicy; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.util.xml.Xpp3Dom; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.wizard.IWizardPage; import org.wso2.developerstudio.eclipse.artifact.endpoint.Activator; import org.wso2.developerstudio.eclipse.artifact.endpoint.model.EndpointModel; import org.wso2.developerstudio.eclipse.artifact.endpoint.utils.EndPointImageUtils; import org.wso2.developerstudio.eclipse.artifact.endpoint.utils.EpArtifactConstants; import org.wso2.developerstudio.eclipse.artifact.endpoint.validators.ProjectFilter; import org.wso2.developerstudio.eclipse.capp.maven.utils.MavenConstants; import org.wso2.developerstudio.eclipse.esb.project.artifact.ESBArtifact; import org.wso2.developerstudio.eclipse.esb.project.artifact.ESBProjectArtifact; import org.wso2.developerstudio.eclipse.general.project.artifact.GeneralProjectArtifact; import org.wso2.developerstudio.eclipse.general.project.artifact.RegistryArtifact; import org.wso2.developerstudio.eclipse.general.project.artifact.bean.RegistryElement; import org.wso2.developerstudio.eclipse.general.project.artifact.bean.RegistryItem; import org.wso2.developerstudio.eclipse.logging.core.IDeveloperStudioLog; import org.wso2.developerstudio.eclipse.logging.core.Logger; import org.wso2.developerstudio.eclipse.maven.util.MavenUtils; import org.wso2.developerstudio.eclipse.platform.core.registry.util.RegistryResourceInfo; import org.wso2.developerstudio.eclipse.platform.core.registry.util.RegistryResourceInfoDoc; import org.wso2.developerstudio.eclipse.platform.core.registry.util.RegistryResourceUtils; import org.wso2.developerstudio.eclipse.platform.core.templates.ArtifactTemplate; import org.wso2.developerstudio.eclipse.platform.ui.editor.Openable; import org.wso2.developerstudio.eclipse.platform.ui.startup.ESBGraphicalEditor; import org.wso2.developerstudio.eclipse.platform.ui.wizard.AbstractWSO2ProjectCreationWizard; import org.wso2.developerstudio.eclipse.utils.file.FileUtils; public class EndpointProjectCreationWizard extends AbstractWSO2ProjectCreationWizard { private static IDeveloperStudioLog log=Logger.getLog(Activator.PLUGIN_ID); private EndpointModel epModel; private IFile endpointFile; private ESBProjectArtifact esbProjectArtifact; private List<File> fileLst = new ArrayList<File>(); private IProject project; public EndpointProjectCreationWizard() { this.epModel = new EndpointModel(); setModel(this.epModel); setWindowTitle(EpArtifactConstants.EP_WIZARD_WINDOW_TITLE); setDefaultPageImageDescriptor(EndPointImageUtils.getInstance().getImageDescriptor("endpoint-wizard.png")); } protected boolean isRequireProjectLocationSection() { return false; } protected boolean isRequiredWorkingSet() { return false; } public boolean performFinish() { try { epModel = (EndpointModel) getModel(); project = epModel.getEndpointSaveLocation().getProject(); if(epModel.isSaveAsDynamic()){ createDynamicEndpointArtifact(project,epModel); } else{ if(!createEndpointArtifact(project,epModel)){ return false; } } project.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor()); if(fileLst.size()>0){ openEditor(fileLst.get(0)); } } catch (CoreException e) { log.error("CoreException has occurred", e); } catch (Exception e) { log.error("An unexpected error has occurred", e); } ProjectFilter.setShowGeneralProjects(false); return true; } @Override public boolean performCancel() { ProjectFilter.setShowGeneralProjects(false); return super.performCancel(); } @Override public IWizardPage getPreviousPage(IWizardPage page) { return super.getPreviousPage(page); } private boolean createEndpointArtifact(IProject prj, EndpointModel model) throws Exception { boolean isNewArtifact=true; String templateContent = ""; String template = ""; IContainer location = project.getFolder("src" + File.separator + "main" + File.separator + "synapse-config" + File.separator + "endpoints"); File pomfile = project.getFile("pom.xml").getLocation().toFile(); getModel().getMavenInfo().setPackageName("synapse/endpoint"); if (!pomfile.exists()) { createPOM(pomfile); } updatePom(); project.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor()); String groupId = getMavenGroupId(pomfile); groupId += ".endpoint"; // Adding the metadat+a about the endpoint to the metadata store. esbProjectArtifact = new ESBProjectArtifact(); esbProjectArtifact.fromFile(project.getFile("artifact.xml") .getLocation().toFile()); if (getModel().getSelectedOption().equals( EpArtifactConstants.WIZARD_OPTION_IMPORT_OPTION)) { endpointFile = location.getFile(new Path(getModel().getImportFile().getName())); if(endpointFile.exists()){ if(!MessageDialog.openQuestion(getShell(), "WARNING", "Do you like to override exsiting project in the workspace")){ return false; } isNewArtifact = false; } copyImportFile(location,isNewArtifact,groupId); } else { ArtifactTemplate selectedTemplate = epModel.getSelectedTemplate(); templateContent = FileUtils.getContentAsString(selectedTemplate .getTemplateDataStream()); if (selectedTemplate.getName().equals( EpArtifactConstants.ADDRESS_EP)) { template = createEPTemplate(templateContent, EpArtifactConstants.ADDRESS_EP); } else if (selectedTemplate.getName().equals( EpArtifactConstants.WSDL_EP)) { template = createEPTemplate(templateContent, EpArtifactConstants.WSDL_EP); } else if (selectedTemplate.getName().equals( EpArtifactConstants.TEMPLATE_EP)) { template = createEPTemplate(templateContent, EpArtifactConstants.TEMPLATE_EP); } else { template = createEPTemplate(templateContent, ""); } endpointFile = location.getFile(new Path(epModel.getEpName() + ".xml")); File destFile = endpointFile.getLocation().toFile(); FileUtils.createFile(destFile, template); fileLst.add(destFile); ESBArtifact artifact = new ESBArtifact(); artifact.setName(epModel.getEpName()); artifact.setVersion("1.0.0"); artifact.setType("synapse/endpoint"); artifact.setServerRole("EnterpriseServiceBus"); artifact.setGroupId(groupId); artifact.setFile(FileUtils.getRelativePath(project.getLocation() .toFile(), new File(location.getLocation().toFile(), epModel.getEpName() + ".xml")).replaceAll(Pattern.quote(File.separator), "/")); esbProjectArtifact.addESBArtifact(artifact); } project.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor()); esbProjectArtifact.toFile(); return true; } private void createDynamicEndpointArtifact(IContainer location,EndpointModel model) throws Exception{ addGeneralProjectPlugin(project); File pomLocation = project.getFile("pom.xml").getLocation().toFile(); String groupId = getMavenGroupId(pomLocation) + ".resource"; String registryPath = model.getDynamicEpRegistryPath() .replaceAll("^conf:", "/_system/config") .replaceAll("^gov:", "/_system/governance") .replaceAll("^local:", "/_system/local"); + + if(model.getRegistryPathID().equals(CONF_REG_ID)){ + if(!registryPath.startsWith("/_system/config")){ + registryPath = "/_system/config/".concat(registryPath); + } + } else if (model.getRegistryPathID().equals(GOV_REG_ID)){ + if(!registryPath.startsWith("/_system/governance")){ + registryPath = "/_system/governance/".concat(registryPath); + } + } + String templateContent = ""; String template = ""; RegistryResourceInfoDoc regResInfoDoc = new RegistryResourceInfoDoc(); ArtifactTemplate selectedTemplate = epModel.getSelectedTemplate(); templateContent = FileUtils.getContentAsString(selectedTemplate .getTemplateDataStream()); if (selectedTemplate.getName().equals( EpArtifactConstants.ADDRESS_EP)) { template = createEPTemplate(templateContent, EpArtifactConstants.ADDRESS_EP); } else if (selectedTemplate.getName().equals( EpArtifactConstants.WSDL_EP)) { template = createEPTemplate(templateContent, EpArtifactConstants.WSDL_EP); } else if (selectedTemplate.getName().equals( EpArtifactConstants.TEMPLATE_EP)) { template = createEPTemplate(templateContent, EpArtifactConstants.TEMPLATE_EP); } else { template = createEPTemplate(templateContent, ""); } endpointFile = location.getFile(new Path(epModel.getEpName() + ".xml")); File destFile = endpointFile.getLocation().toFile(); FileUtils.createFile(destFile, template); fileLst.add(destFile); RegistryResourceUtils.createMetaDataForFolder(registryPath, location .getLocation().toFile()); RegistryResourceUtils.addRegistryResourceInfo(destFile, regResInfoDoc, project.getLocation().toFile(), registryPath); GeneralProjectArtifact generalProjectArtifact = new GeneralProjectArtifact(); generalProjectArtifact.fromFile(project.getFile("artifact.xml") .getLocation().toFile()); RegistryArtifact artifact = new RegistryArtifact(); artifact.setName(epModel.getEpName()); artifact.setVersion("1.0.0"); artifact.setType("registry/resource"); artifact.setServerRole("EnterpriseServiceBus"); artifact.setGroupId(groupId); List<RegistryResourceInfo> registryResources = regResInfoDoc .getRegistryResources(); for (RegistryResourceInfo registryResourceInfo : registryResources) { RegistryElement item = null; if (registryResourceInfo.getType() == REGISTRY_RESOURCE) { item = new RegistryItem(); ((RegistryItem) item).setFile(registryResourceInfo .getResourceBaseRelativePath()); ((RegistryItem) item).setMediaType(registryResourceInfo.getMediaType()); } item.setPath(registryResourceInfo.getDeployPath().replaceAll("/$", "")); artifact.addRegistryElement(item); } generalProjectArtifact.addArtifact(artifact); generalProjectArtifact.toFile(); } private void addGeneralProjectPlugin(IProject project) throws Exception{ MavenProject mavenProject; File mavenProjectPomLocation = project.getFile("pom.xml").getLocation().toFile(); if(!mavenProjectPomLocation.exists()){ mavenProject = MavenUtils.createMavenProject("org.wso2.carbon." + project.getName(), project.getName(), "1.0.0","pom"); } else { mavenProject = MavenUtils.getMavenProject(mavenProjectPomLocation); } boolean pluginExists = MavenUtils.checkOldPluginEntry(mavenProject, "org.wso2.maven", "wso2-general-project-plugin", MavenConstants.WSO2_GENERAL_PROJECT_VERSION); if(pluginExists){ return ; } Plugin plugin = MavenUtils.createPluginEntry(mavenProject, "org.wso2.maven", "wso2-general-project-plugin", MavenConstants.WSO2_GENERAL_PROJECT_VERSION, true); PluginExecution pluginExecution; pluginExecution = new PluginExecution(); pluginExecution.addGoal("pom-gen"); pluginExecution.setPhase("process-resources"); pluginExecution.setId("registry"); plugin.addExecution(pluginExecution); Xpp3Dom configurationNode = MavenUtils.createMainConfigurationNode(); Xpp3Dom artifactLocationNode = MavenUtils.createXpp3Node(configurationNode, "artifactLocation"); artifactLocationNode.setValue("."); Xpp3Dom typeListNode = MavenUtils.createXpp3Node(configurationNode, "typeList"); typeListNode.setValue("${artifact.types}"); pluginExecution.setConfiguration(configurationNode); Repository repo = new Repository(); repo.setUrl("http://dist.wso2.org/maven2"); repo.setId("wso2-maven2-repository-1"); Repository repo1 = new Repository(); repo1.setUrl("http://maven.wso2.org/nexus/content/groups/wso2-public/"); repo1.setId("wso2-nexus-maven2-repository-1"); if (!mavenProject.getRepositories().contains(repo)) { mavenProject.getModel().addRepository(repo); mavenProject.getModel().addPluginRepository(repo); } if (!mavenProject.getRepositories().contains(repo1)) { mavenProject.getModel().addRepository(repo1); mavenProject.getModel().addPluginRepository(repo1); } MavenUtils.saveMavenProject(mavenProject, mavenProjectPomLocation); } public void updatePom() throws Exception{ File mavenProjectPomLocation = project.getFile("pom.xml").getLocation().toFile(); MavenProject mavenProject = MavenUtils.getMavenProject(mavenProjectPomLocation); boolean pluginExists = MavenUtils.checkOldPluginEntry(mavenProject, "org.wso2.maven", "wso2-esb-endpoint-plugin", MavenConstants.WSO2_ESB_ENDPOINT_VERSION); if(pluginExists){ return ; } Plugin plugin = MavenUtils.createPluginEntry(mavenProject, "org.wso2.maven", "wso2-esb-endpoint-plugin", MavenConstants.WSO2_ESB_ENDPOINT_VERSION, true); PluginExecution pluginExecution = new PluginExecution(); pluginExecution.addGoal("pom-gen"); pluginExecution.setPhase("process-resources"); pluginExecution.setId("endpoint"); Xpp3Dom configurationNode = MavenUtils.createMainConfigurationNode(); Xpp3Dom artifactLocationNode = MavenUtils.createXpp3Node(configurationNode, "artifactLocation"); artifactLocationNode.setValue("."); Xpp3Dom typeListNode = MavenUtils.createXpp3Node(configurationNode, "typeList"); typeListNode.setValue("${artifact.types}"); pluginExecution.setConfiguration(configurationNode); plugin.addExecution(pluginExecution); Repository repo = new Repository(); repo.setUrl("http://maven.wso2.org/nexus/content/groups/wso2-public/"); repo.setId("wso2-nexus"); RepositoryPolicy releasePolicy=new RepositoryPolicy(); releasePolicy.setEnabled(true); releasePolicy.setUpdatePolicy("daily"); releasePolicy.setChecksumPolicy("ignore"); repo.setReleases(releasePolicy); if (!mavenProject.getRepositories().contains(repo)) { mavenProject.getModel().addRepository(repo); mavenProject.getModel().addPluginRepository(repo); } MavenUtils.saveMavenProject(mavenProject, mavenProjectPomLocation); } public void copyImportFile(IContainer importLocation, boolean isNewArtifact, String groupId) throws IOException { File importFile = getModel().getImportFile(); EndpointModel endpointModel = (EndpointModel) getModel(); List<OMElement> selectedEPList = endpointModel.getSelectedEPList(); File destFile = null; if(selectedEPList != null && selectedEPList.size() >0 ){ for (OMElement element : selectedEPList) { String name = element.getAttributeValue(new QName("name")); destFile = new File(importLocation.getLocation().toFile(), name + ".xml"); FileUtils.createFile(destFile, element.toString()); fileLst.add(destFile); if(isNewArtifact){ String fileLocation = FileUtils.getRelativePath(importLocation.getProject().getLocation().toFile(), new File(importLocation.getLocation().toFile(),name+".xml")); esbProjectArtifact.addESBArtifact(createArtifactxml(fileLocation, name,groupId)); } } }else{ destFile = new File(importLocation.getLocation().toFile(), importFile.getName()); FileUtils.copy(importFile, destFile); fileLst.add(destFile); String name = importFile.getName().replaceAll(".xml$", ""); if(isNewArtifact){ String fileLocation = FileUtils.getRelativePath(importLocation.getProject().getLocation().toFile(), new File(importLocation.getLocation().toFile(),name+".xml")); esbProjectArtifact.addESBArtifact(createArtifactxml(fileLocation, name,groupId)); } } } private ESBArtifact createArtifactxml(String location, String artifactName,String groupId) { ESBArtifact artifact=new ESBArtifact(); artifact.setName(artifactName); artifact.setVersion("1.0.0"); artifact.setType("synapse/endpoint"); artifact.setServerRole("EnterpriseServiceBus"); artifact.setGroupId(groupId); artifact.setFile(location); return artifact; } public IResource getCreatedResource() { return endpointFile; } public String createEPTemplate(String templateContent, String type) throws IOException{ // String defaultNS = ESBPreferenceData.getDefaultNamesapce(); // if(defaultNS.equals("") || defaultNS == null){ // defaultNS = SynapseConstants.NS_1_4; // } templateContent = templateContent.replaceAll("\\{", "<"); templateContent = templateContent.replaceAll("\\}", ">"); String newContent = StringUtils.replace(templateContent,"<ep.name>", epModel.getEpName()); if(type.equals(EpArtifactConstants.ADDRESS_EP)){ newContent = StringUtils.replace(newContent,"<address.uri>", epModel.getAddressEPURI()); }else if(type.equals(EpArtifactConstants.WSDL_EP)){ newContent = StringUtils.replace(newContent,"<wsdl.uri>", epModel.getWsdlEPURI()); newContent = StringUtils.replace(newContent,"<service.name>", epModel.getWsdlEPService()); newContent = StringUtils.replace(newContent,"<service.port>", epModel.getWsdlEPPort()); }else if(type.equals(EpArtifactConstants.TEMPLATE_EP)){ newContent = StringUtils.replace(newContent,"<ep.uri>", epModel.getTemplateEPURI()); newContent = StringUtils.replace(newContent,"<ep.template>", epModel.getTemplateEPTargetTemp()); } return newContent; } public void openEditor(File file){ try { refreshDistProjects(); OMElement documentElement = new StAXOMBuilder(new FileInputStream(file)).getDocumentElement(); String localName =documentElement.getFirstElement().getLocalName(); String type="endpoint"; if ("address".equals(localName)) { type=type+"-1"; } else if ("wsdl".equals(localName)) { type=type+"-2"; } else if ("loadbalance".equals(localName)) { type=type+"-3"; } else if ("failover".equals(localName)) { type=type+"-4"; } else if ("recipientlist".equals(localName)) { type=type+"-5"; } else { type=type+"-0"; } String location = endpointFile.getParent().getFullPath()+"/"; String source = FileUtils.getContentAsString(file); Openable openable = ESBGraphicalEditor.getOpenable(); openable.editorOpen(file.getName(),type,location+"endpoint_", source); } catch (Exception e) { log.error("Cannot open the editor", e); } } }
false
false
null
null
diff --git a/src/com/noughmad/slashdotcomments/StoryListFragment.java b/src/com/noughmad/slashdotcomments/StoryListFragment.java index c862b5d..d8f69f2 100644 --- a/src/com/noughmad/slashdotcomments/StoryListFragment.java +++ b/src/com/noughmad/slashdotcomments/StoryListFragment.java @@ -1,249 +1,249 @@ package com.noughmad.slashdotcomments; import android.app.Activity; import android.app.ListFragment; import android.app.LoaderManager; import android.content.Context; import android.content.CursorLoader; import android.content.Loader; import android.database.Cursor; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.text.Html; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CursorAdapter; import android.widget.ListView; import android.widget.TextView; /** * A list fragment representing a list of Stories. This fragment also supports * tablet devices by allowing list items to be given an 'activated' state upon * selection. This helps indicate which item is currently being viewed in a * {@link StoryDetailFragment}. * <p> * Activities containing this fragment MUST implement the {@link Callbacks} * interface. */ public class StoryListFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor> { /** * The serialization (saved instance state) Bundle key representing the * activated item position. Only used on tablets. */ private static final String STATE_ACTIVATED_POSITION = "activated_position"; /** * The fragment's current callback object, which is notified of list item * clicks. */ private Callbacks mCallbacks = sDummyCallbacks; /** * The current activated item position. Only used on tablets. */ private int mActivatedPosition = ListView.INVALID_POSITION; /** * A callback interface that all activities containing this fragment must * implement. This mechanism allows activities to be notified of item * selections. */ public interface Callbacks { /** * Callback for when an item has been selected. */ public void onItemSelected(long l); public boolean isTwoPane(); public void onRefreshStateChanged(boolean refreshing); } /** * A dummy implementation of the {@link Callbacks} interface that does * nothing. Used only when this fragment is not attached to an activity. */ private static Callbacks sDummyCallbacks = new Callbacks() { @Override public void onItemSelected(long id) { } public boolean isTwoPane() { return false; } public void onRefreshStateChanged(boolean refreshing) { } }; private static final String[] STORIES_COLUMNS = new String[] { SlashdotProvider.ID, SlashdotProvider.STORY_TITLE, SlashdotProvider.STORY_COMMENT_COUNT }; private class StoriesAdapter extends CursorAdapter { public StoriesAdapter(Context context, Cursor c) { super(context, c, false); } @Override public void bindView(View view, Context context, Cursor cursor) { TextView title = (TextView)view.findViewById(R.id.story_title); - title.setText(Html.fromHtml(cursor.getString(0))); + title.setText(Html.fromHtml(cursor.getString(1))); TextView comments = (TextView)view.findViewById(R.id.story_comments); - comments.setText(String.format("Comments: %d", cursor.getInt(1))); + comments.setText(String.format("Comments: %d", cursor.getInt(2))); } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); return inflater.inflate(R.layout.item_story, parent, false); } }; private class GetStoriesTask extends AsyncTask<String, Void, Void> { @Override protected Void doInBackground(String... params) { SlashdotContent.refreshStories(getActivity(), params[0]); return null; } @Override protected void onPostExecute(Void v) { mCallbacks.onRefreshStateChanged(false); } }; /** * Mandatory empty constructor for the fragment manager to instantiate the * fragment (e.g. upon screen orientation changes). */ public StoryListFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setListAdapter(new StoriesAdapter(getActivity(), null)); refreshStories(); getLoaderManager().initLoader(0, null, this); setListShown(false); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); // Restore the previously serialized activated item position. if (savedInstanceState != null && savedInstanceState.containsKey(STATE_ACTIVATED_POSITION)) { setActivatedPosition(savedInstanceState .getInt(STATE_ACTIVATED_POSITION)); } } @Override public void onAttach(Activity activity) { super.onAttach(activity); // Activities containing this fragment must implement its callbacks. if (!(activity instanceof Callbacks)) { throw new IllegalStateException( "Activity must implement fragment's callbacks."); } mCallbacks = (Callbacks) activity; } @Override public void onDetach() { super.onDetach(); // Reset the active callbacks interface to the dummy implementation. mCallbacks = sDummyCallbacks; } @Override public void onListItemClick(ListView listView, View view, int position, long id) { super.onListItemClick(listView, view, position, id); // Notify the active callbacks interface (the activity, if the // fragment is attached to one) that an item has been selected. mCallbacks.onItemSelected(listView.getItemIdAtPosition(position)); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mActivatedPosition != ListView.INVALID_POSITION) { // Serialize and persist the activated item position. outState.putInt(STATE_ACTIVATED_POSITION, mActivatedPosition); } } /** * Turns on activate-on-click mode. When this mode is on, list items will be * given the 'activated' state when touched. */ public void setActivateOnItemClick(boolean activateOnItemClick) { // When setting CHOICE_MODE_SINGLE, ListView will automatically // give items the 'activated' state when touched. getListView().setChoiceMode( activateOnItemClick ? ListView.CHOICE_MODE_SINGLE : ListView.CHOICE_MODE_NONE); } private void setActivatedPosition(int position) { if (position == ListView.INVALID_POSITION) { getListView().setItemChecked(mActivatedPosition, false); } else { getListView().setItemChecked(position, true); } mActivatedPosition = position; } public void refreshStories() { (new GetStoriesTask()).execute("http://slashdot.org"); mCallbacks.onRefreshStateChanged(true); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { Uri uri = Uri.withAppendedPath(SlashdotProvider.BASE_URI, SlashdotProvider.STORIES_TABLE_NAME); return new CursorLoader(getActivity(), uri, STORIES_COLUMNS, null, null, null); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { Log.i("StoryListFragment", "Load finished: " + cursor.getCount()); ((CursorAdapter)getListAdapter()).swapCursor(cursor); if (cursor.getCount() > 0) { setListShown(true); } } @Override public void onLoaderReset(Loader<Cursor> loader) { } }
false
false
null
null
diff --git a/src/org/jitsi/android/gui/chat/ChatFragment.java b/src/org/jitsi/android/gui/chat/ChatFragment.java index 89a76b8..baf3e68 100644 --- a/src/org/jitsi/android/gui/chat/ChatFragment.java +++ b/src/org/jitsi/android/gui/chat/ChatFragment.java @@ -1,1205 +1,1203 @@ /* * Jitsi, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package org.jitsi.android.gui.chat; import java.text.*; import java.util.*; import android.app.*; import android.content.*; import android.graphics.drawable.*; import android.os.*; import android.text.*; import android.text.ClipboardManager; import android.text.method.*; import android.view.*; import android.widget.*; import android.widget.LinearLayout.*; import net.java.sip.communicator.service.contactlist.*; import net.java.sip.communicator.service.globaldisplaydetails.*; import net.java.sip.communicator.service.protocol.*; import net.java.sip.communicator.service.protocol.event.*; import net.java.sip.communicator.service.protocol.globalstatus.*; import net.java.sip.communicator.util.*; import net.java.sip.communicator.util.Logger; import org.jitsi.*; import org.jitsi.android.*; import org.jitsi.android.gui.*; import org.jitsi.android.gui.account.*; import org.jitsi.android.gui.contactlist.*; import org.jitsi.android.gui.util.*; import org.jitsi.android.gui.util.event.EventListener; import org.jitsi.service.osgi.*; /** * The <tt>ChatFragment</tt> is responsible for chat interface. * * @author Yana Stamcheva * @author Pawel Domas */ public class ChatFragment extends OSGiFragment { /** * The logger */ private static final Logger logger = Logger.getLogger(ChatFragment.class); /** * The session adapter for the contained <tt>ChatSession</tt>. */ private ChatListAdapter chatListAdapter; /** * The corresponding <tt>ChatSession</tt>. */ private ChatSession chatSession; /** * The chat list view representing the chat. */ private ListView chatListView; /** * List header used to display progress bar when history is being loaded. */ private View header; /** * Remembers first visible view to scroll the list after new portion of * history messages is added. */ public int scrollFirstVisible; /** * Remembers top position to add to the scrolling offset after new portion * of history messages is added. */ public int scrollTopOffset; /** * The chat typing view. */ private LinearLayout typingView; /** * The task that loads history. */ private LoadHistoryTask loadHistoryTask; /** * Indicates that this fragment is visible to the user. * This is important, because of PagerAdapter being used on phone layouts, * which doesn't properly call onResume() when switched page fragment is * displayed. */ private boolean visibleToUser = false; /** * The chat controller used to handle operations like editing and sending * messages used by this fragment. */ private ChatController chatController; /** * Refresh avatar and globals status display on change. */ private EventListener<PresenceStatus> globalStatusListener = new EventListener<PresenceStatus>() { @Override public void onChangeEvent(PresenceStatus eventObject) { if(chatListAdapter != null) chatListAdapter.localAvatarOrStatusChanged(); } }; /** * Returns the corresponding <tt>ChatSession</tt>. * * @return the corresponding <tt>ChatSession</tt> */ public ChatSession getChatSession() { return chatSession; } /** * Returns the underlying chat list view. * * @return the underlying chat list view */ public ListView getChatListView() { return chatListView; } /** * Returns the underlying chat list view. * * @return the underlying chat list view */ public ChatListAdapter getChatListAdapter() { return chatListAdapter; } /** * {@inheritDoc} */ @Override public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View content = inflater.inflate( R.layout.chat_conversation, container, false); chatListAdapter = new ChatListAdapter(); chatListView = (ListView) content.findViewById(R.id.chatListView); // Inflates and adds the header, hidden by default this.header = inflater.inflate(R.layout.progressbar, chatListView, false); header.setVisibility(View.GONE); chatListView.addHeaderView(header); // Registers for chat message context menu registerForContextMenu(chatListView); typingView = (LinearLayout) content.findViewById(R.id.typingView); chatListView.setAdapter(chatListAdapter); chatListView.setSelector(R.drawable.contact_list_selector); chatListView.setOnScrollListener(new AbsListView.OnScrollListener() { @Override public void onScrollStateChanged(AbsListView view, int scrollState) { // Detects event when user scrolls to the top of the list if(scrollState == 0) { if(chatListView.getChildAt(0).getTop()==0) { // Loads some more history // if there's no loading task in progress if(loadHistoryTask == null) { loadHistoryTask = new LoadHistoryTask(); loadHistoryTask.execute(); } } } } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { // Remembers scrolling position to restore after new history // messages are loaded scrollFirstVisible = firstVisibleItem; View firstVisible = view.getChildAt(0); scrollTopOffset = firstVisible != null ? firstVisible.getTop() : 0; } }); // Chat intent handling Bundle arguments = getArguments(); String chatId = arguments.getString(ChatSessionManager.CHAT_IDENTIFIER); if(chatId == null) throw new IllegalArgumentException(); chatSession = ChatSessionManager.getActiveChat(chatId); return content; } /** * {@inheritDoc} */ @Override public void onAttach(Activity activity) { super.onAttach(activity); this.chatController = new ChatController(activity, this); } /** * This method must be called by parent <tt>Activity</tt> or * <tt>Fragment</tt> in order to register the chat controller. * * @param isVisible <tt>true</tt> if the fragment is now visible to * the user. * @see ChatController */ public void setVisibleToUser(boolean isVisible) { logger.debug("View visible to user: " + hashCode()+" "+isVisible); this.visibleToUser = isVisible; checkInitController(); } /** * Checks for <tt>ChatController</tt> initialization. To init the controller * fragment must be visible and it's View must be created. * * If fragment is no longer visible the controller will be uninitialized. */ private void checkInitController() { if(visibleToUser && chatListView != null) { logger.debug("Init controller: " + hashCode()); chatController.onShow(); // Also register global status listener AndroidGUIActivator.getLoginRenderer() .addGlobalStatusListener(globalStatusListener); } else if(!visibleToUser) { chatController.onHide(); // Also remove global status listener AndroidGUIActivator.getLoginRenderer() .removeGlobalStatusListener(globalStatusListener); } else { logger.debug("Skipping controller init... " + hashCode()); } } /** * Initializes the chat list adapter. */ private void initAdapter() { loadHistoryTask = new LoadHistoryTask(); loadHistoryTask.execute(); } @Override public void onResume() { super.onResume(); initAdapter(); // If added to the pager adapter for the first time it is required // to check again, because it's marked visible when the Views // are not created yet checkInitController(); chatSession.addMessageListener(chatListAdapter); chatSession.addContactStatusListener(chatListAdapter); chatSession.addTypingListener(chatListAdapter); } @Override public void onPause() { chatSession.removeMessageListener(chatListAdapter); chatSession.removeContactStatusListener(chatListAdapter); chatSession.removeTypingListener(chatListAdapter); /* * Indicates that this fragment is no longer visible, * because of this call parent <tt>Activities don't have to call it * in onPause(). */ setVisibleToUser(false); super.onPause(); } /** * {@inheritDoc} */ @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v,menuInfo); // Creates chat message context menu getActivity().getMenuInflater().inflate(R.menu.chat_msg_ctx_menu, menu); } /** * {@inheritDoc} */ @Override public boolean onContextItemSelected(MenuItem item) { if(item.getItemId() == R.id.copy_to_clipboard) { AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); // Clicked position must be aligned to list headers count int position = info.position - chatListView.getHeaderViewsCount(); // Gets clicked message ChatMessage clickedMsg = chatListAdapter.getMessage(position); // Copy message content to clipboard ClipboardManager clipboardManager = (ClipboardManager) getActivity() .getSystemService(Context.CLIPBOARD_SERVICE); clipboardManager.setText(clickedMsg.getContentForClipboard()); return true; } return super.onContextItemSelected(item); } /** * Creates new parametrized instance of <tt>CallContactFragment</tt>. * * @param chatId optional phone number that will be filled. * @return new parametrized instance of <tt>CallContactFragment</tt>. */ public static ChatFragment newInstance(String chatId) { if (logger.isDebugEnabled()) logger.debug("CHAT FRAGMENT NEW INSTANCE: " + chatId); ChatFragment chatFragment = new ChatFragment(); Bundle args = new Bundle(); args.putString(ChatSessionManager.CHAT_IDENTIFIER, chatId); chatFragment.setArguments(args); return chatFragment; } /** * */ public void onDetach() { if (logger.isDebugEnabled()) logger.debug("DETACH CHAT FRAGMENT: " + this); super.onDetach(); chatListAdapter = null; if (loadHistoryTask != null) { loadHistoryTask.cancel(true); loadHistoryTask = null; } } class ChatListAdapter extends BaseAdapter implements ChatSession.ChatSessionListener, ContactPresenceStatusListener, TypingNotificationsListener { /** * The list of chat message displays. */ private final List<MessageDisplay> messages = new ArrayList<MessageDisplay>(); /** * The type of the incoming message view. */ final int INCOMING_MESSAGE_VIEW = 0; /** * The type of the outgoing message view. */ final int OUTGOING_MESSAGE_VIEW = 1; /** * The type of the system message view. */ final int SYSTEM_MESSAGE_VIEW = 2; /** * The type of the error message view. */ final int ERROR_MESSAGE_VIEW = 3; /** * Counter used to generate row ids. */ private long idGenerator=0; /** * HTML image getter. */ private final Html.ImageGetter imageGetter = new HtmlImageGetter(); /** * Passes the message to the contained <code>ChatConversationPanel</code> * for processing and appends it at the end of the conversationPanel * document. * */ public void addMessage( ChatMessage newMessage, boolean update) { synchronized (messages) { int lastMsgIdx = getLastMessageIdx(newMessage); ChatMessage lastMsg = lastMsgIdx != -1 ? chatListAdapter.getMessage(lastMsgIdx) : null; if(lastMsg == null || !lastMsg.isConsecutiveMessage(newMessage)) { messages.add(new MessageDisplay(newMessage)); } else { // Merge the message and update the object in the list messages.get(lastMsgIdx) .update(lastMsg.mergeMessage(newMessage)); } } if(update) { runOnUiThread(new Runnable() { @Override public void run() { chatListAdapter.notifyDataSetChanged(); // List must be scrolled manually, when // android:transcriptMode="normal" is set chatListView.setSelection(chatListAdapter.getCount()); } }); } } /** * Inserts given <tt>Collection</tt> of <tt>ChatMessage</tt> at * the beginning of the list. * * @param collection the collection of <tt>ChatMessage</tt> to prepend. */ public void prependMessages(Collection<ChatMessage> collection) { List<MessageDisplay> newMsgs = new ArrayList<MessageDisplay>(); Iterator<ChatMessage> iterator = collection.iterator(); MessageDisplay previous = null; while(iterator.hasNext()) { ChatMessage next = iterator.next(); if(previous == null || !previous.msg.isConsecutiveMessage(next)) { previous = new MessageDisplay(next); newMsgs.add(previous); } else { // Merge the message and update the object in the list previous.update(previous.msg.mergeMessage(next)); } } messages.addAll(0, newMsgs); } /** * Finds index of the message that will handle <tt>newMessage</tt> * merging process(usually just the last one). If the * <tt>newMessage</tt> is a correction message, then the last message * of the same type will be returned. * * @param newMessage the next message to be merged into the adapter. * * @return index of the message that will handle <tt>newMessage</tt> * merging process. If <tt>newMessage</tt> is a correction message, * then the last message of the same type will be returned. */ private int getLastMessageIdx(ChatMessage newMessage) { // If it's not a correction message then jus return the last one if(newMessage.getCorrectedMessageUID() == null) return chatListAdapter.getCount()-1; // Search for the same type int msgType = newMessage.getMessageType(); for(int i=getCount()-1; i>= 0; i--) { ChatMessage candidate = getMessage(i); if(candidate.getMessageType() == msgType) { return i; } } return -1; } /** * {@inheritDoc} */ public int getCount() { synchronized (messages) { return messages.size(); } } /** * {@inheritDoc} */ public Object getItem(int position) { synchronized (messages) { if (logger.isDebugEnabled()) logger.debug("OBTAIN CHAT ITEM ON POSITION: " + position); return messages.get(position); } } ChatMessage getMessage(int pos) { return ((MessageDisplay) getItem(pos)).msg; } MessageDisplay getMessageDisplay(int pos) { return (MessageDisplay) getItem(pos); } /** * {@inheritDoc} */ public long getItemId(int pos) { return messages.get(pos).id; } public int getViewTypeCount() { return 4; } public int getItemViewType(int position) { ChatMessage message = getMessage(position); int messageType = message.getMessageType(); if (messageType == ChatMessage.INCOMING_MESSAGE) return INCOMING_MESSAGE_VIEW; else if (messageType == ChatMessage.OUTGOING_MESSAGE) return OUTGOING_MESSAGE_VIEW; else if (messageType == ChatMessage.SYSTEM_MESSAGE) return SYSTEM_MESSAGE_VIEW; else if(messageType == ChatMessage.ERROR_MESSAGE) return ERROR_MESSAGE_VIEW; return 0; } /** * {@inheritDoc} */ public View getView(int position, View convertView, ViewGroup parent) { // Keeps reference to avoid future findViewById() MessageViewHolder messageViewHolder; if (convertView == null) { LayoutInflater inflater = getActivity().getLayoutInflater(); messageViewHolder = new MessageViewHolder(); int viewType = getItemViewType(position); messageViewHolder.viewType = viewType; if (viewType == INCOMING_MESSAGE_VIEW) { convertView = inflater.inflate( R.layout.chat_incoming_row, parent, false); messageViewHolder.avatarView = (ImageView) convertView.findViewById( R.id.incomingAvatarIcon); messageViewHolder.statusView = (ImageView) convertView.findViewById( R.id.incomingStatusIcon); messageViewHolder.messageView = (TextView) convertView.findViewById( R.id.incomingMessageView); messageViewHolder.timeView = (TextView) convertView.findViewById( R.id.incomingTimeView); messageViewHolder.typingView = (ImageView) convertView.findViewById( R.id.typingImageView); } else if(viewType == OUTGOING_MESSAGE_VIEW) { convertView = inflater.inflate( R.layout.chat_outgoing_row, parent, false); messageViewHolder.avatarView = (ImageView) convertView.findViewById( R.id.outgoingAvatarIcon); messageViewHolder.statusView = (ImageView) convertView.findViewById( R.id.outgoingStatusIcon); messageViewHolder.messageView = (TextView) convertView.findViewById( R.id.outgoingMessageView); messageViewHolder.timeView = (TextView) convertView.findViewById( R.id.outgoingTimeView); } else { // System or error view convertView = inflater.inflate( viewType == SYSTEM_MESSAGE_VIEW ? R.layout.chat_system_row : R.layout.chat_error_row, parent, false); messageViewHolder.messageView = (TextView) convertView.findViewById( R.id.messageView); } convertView.setTag(messageViewHolder); } else { messageViewHolder = (MessageViewHolder) convertView.getTag(); } MessageDisplay message = getMessageDisplay(position); if (message != null) { if(messageViewHolder.viewType == INCOMING_MESSAGE_VIEW || messageViewHolder.viewType == OUTGOING_MESSAGE_VIEW) { updateStatusAndAvatarView(messageViewHolder); messageViewHolder.timeView.setText(message.getDateStr()); } messageViewHolder.messageView.setText(message.getBody()); // Html links are handled only for system messages, which is // currently used for displaying OTR authentication dialog. // Otherwise settings movement method prevent form firing // on item clicked events. int currentMsgType = message.msg.getMessageType(); if(messageViewHolder.msgType != currentMsgType) { MovementMethod movementMethod = null; if(currentMsgType == ChatMessage.SYSTEM_MESSAGE) { movementMethod = LinkMovementMethod.getInstance(); } messageViewHolder .messageView .setMovementMethod(movementMethod); } } return convertView; } /** * Updates status and avatar views on given <tt>MessageViewHolder</tt>. * @param viewHolder the <tt>MessageViewHolder</tt> to update. */ private void updateStatusAndAvatarView(MessageViewHolder viewHolder) { Drawable avatar = null; Drawable status = null; if (viewHolder.viewType == INCOMING_MESSAGE_VIEW) { avatar = ContactListAdapter.getAvatarDrawable( chatSession.getMetaContact()); status = ContactListAdapter.getStatusDrawable( chatSession.getMetaContact()); } else if (viewHolder.viewType == OUTGOING_MESSAGE_VIEW) { AndroidLoginRenderer loginRenderer = AndroidGUIActivator.getLoginRenderer(); avatar = loginRenderer.getLocalAvatarDrawable(); status = loginRenderer.getLocalStatusDrawable(); } setAvatar(viewHolder.avatarView, avatar); setStatus(viewHolder.statusView, status); } @Override public void messageDelivered(final MessageDeliveredEvent evt) { final Contact contact = evt.getDestinationContact(); final MetaContact metaContact = AndroidGUIActivator.getContactListService() .findMetaContactByContact(contact); if (logger.isTraceEnabled()) logger.trace("MESSAGE DELIVERED to contact: " + contact.getAddress()); if (metaContact != null && chatSession.getMetaContact().equals(metaContact)) { final ChatMessageImpl msg = ChatMessageImpl.getMsgForEvent(evt); if (logger.isTraceEnabled()) logger.trace( "MESSAGE DELIVERED: process message to chat for contact: " + contact.getAddress() + " MESSAGE: " + msg.getMessage()); addMessage(msg, true); } } @Override public void messageDeliveryFailed(MessageDeliveryFailedEvent arg0) { // Do nothing, handled in ChatSession } @Override public void messageReceived(final MessageReceivedEvent evt) { if (logger.isTraceEnabled()) logger.trace("MESSAGE RECEIVED from contact: " + evt.getSourceContact().getAddress()); final Contact protocolContact = evt.getSourceContact(); final MetaContact metaContact = AndroidGUIActivator.getContactListService() .findMetaContactByContact(protocolContact); if(metaContact != null && chatSession.getMetaContact().equals(metaContact)) { final ChatMessageImpl msg = ChatMessageImpl.getMsgForEvent(evt); addMessage(msg, true); } else { if (logger.isTraceEnabled()) logger.trace("MetaContact not found for protocol contact: " + protocolContact + "."); } } @Override public void messageAdded(ChatMessage msg) { addMessage(msg, true); } /** * Indicates a contact has changed its status. */ @Override public void contactPresenceStatusChanged( ContactPresenceStatusChangeEvent evt) { Contact sourceContact = evt.getSourceContact(); if (logger.isDebugEnabled()) logger.debug("Contact presence status changed: " + sourceContact.getAddress()); if (!chatSession.getMetaContact().containsContact(sourceContact)) return; new UpdateStatusTask().execute(); } @Override public void typingNotificationDeliveryFailed( TypingNotificationEvent evt) { } @Override public void typingNotificationReceived(TypingNotificationEvent evt) { if (logger.isDebugEnabled()) logger.debug("Typing notification received: " + evt.getSourceContact().getAddress()); TypingNotificationHandler .handleTypingNotificationReceived(evt, ChatFragment.this); } /** * Removes all messages from the adapter */ public void removeAllMessages() { messages.clear(); } /** * Updates all avatar and status on outgoing messages rows. */ public void localAvatarOrStatusChanged() { runOnUiThread(new Runnable() { @Override public void run() { for(int i=0; i<chatListView.getChildCount(); i++) { View row = chatListView.getChildAt(i); updateStatusAndAvatarView( (MessageViewHolder) row.getTag()); } } }); } /** * Class used to cache processed message contents. Prevents from * re-processing on each View display. */ class MessageDisplay { /** * Row identifier. */ private final long id; /** * Displayed <tt>ChatMessage</tt> */ private ChatMessage msg; /** * Date string cache */ private String dateStr; /** * Message body cache */ private Spanned body; /** * Creates new instance of <tt>MessageDisplay</tt> that will be used * for displaying given <tt>ChatMessage</tt>. * * @param msg the <tt>ChatMessage</tt> that will be displayed by * this instance. */ MessageDisplay(ChatMessage msg) { this.msg = msg; this.id = idGenerator++; } /** * Returns formatted date string for the <tt>ChatMessage</tt>. * @return formatted date string for the <tt>ChatMessage</tt>. */ public String getDateStr() { if(dateStr == null) { Date date = msg.getDate(); dateStr = GuiUtils.formatDate(date) + " " + GuiUtils.formatTime(date); } return dateStr; } /** * Returns <tt>Spanned</tt> message body processed for HTML tags. * @return <tt>Spanned</tt> message body. */ public Spanned getBody() { if(body == null) { body = Html.fromHtml(msg.getMessage(), imageGetter, null); } return body; } /** * Updates this display instance with new message causing display * contents to be invalidated. * @param chatMessage new message content */ public void update(ChatMessage chatMessage) { dateStr = null; body = null; msg = chatMessage; } } } static class MessageViewHolder { ImageView avatarView; ImageView statusView; ImageView typeIndicator; TextView messageView; TextView timeView; ImageView typingView; int viewType; int position; int msgType; } /** * Loads the history in an asynchronous thread and then adds the history * messages to the user interface. */ private class LoadHistoryTask extends AsyncTask<Void, Void, Collection<ChatMessage>> { /** * Remembers adapter size before new messages were added. */ private int preSize; @Override protected void onPreExecute() { super.onPreExecute(); header.setVisibility(View.VISIBLE); this.preSize = chatListAdapter.getCount(); } @Override protected Collection<ChatMessage> doInBackground(Void... params) { return chatSession.getHistory(preSize == 0); } @Override protected void onPostExecute(Collection<ChatMessage> result) { super.onPostExecute(result); chatListAdapter.prependMessages(result); header.setVisibility(View.GONE); chatListAdapter.notifyDataSetChanged(); int loaded = chatListAdapter.getCount() - preSize; int scrollTo = loaded + scrollFirstVisible; chatListView.setSelectionFromTop(scrollTo, scrollTopOffset); loadHistoryTask = null; } } /** * Updates the status user interface. */ private class UpdateStatusTask extends AsyncTask<Void, Void, Void> { protected Void doInBackground(Void... params) { return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); - for (int i = 0; - i <= chatListView.getLastVisiblePosition(); i++) + for (int i = 0; i < chatListView.getChildCount(); i++) { - RelativeLayout chatRowView - = (RelativeLayout) chatListView.getChildAt( - i - chatListView.getFirstVisiblePosition()); + View chatRowView = chatListView.getChildAt(i); - if (chatRowView != null - && chatListAdapter.getItemViewType(i) + MessageViewHolder viewHolder + = (MessageViewHolder) chatRowView.getTag(); + + if (viewHolder != null + && viewHolder.viewType == chatListAdapter.INCOMING_MESSAGE_VIEW) { Drawable status = ContactListAdapter .getStatusDrawable( chatSession.getMetaContact()); - ImageView statusView - = (ImageView) chatRowView - .findViewById(R.id.incomingStatusIcon); + ImageView statusView = viewHolder.statusView; setStatus(statusView, status); } } } } /** * Returns the local user avatar drawable. * * @return the local user avatar drawable */ private static Drawable getLocalAvatarDrawable() { GlobalDisplayDetailsService displayDetailsService = AndroidGUIActivator.getGlobalDisplayDetailsService(); byte[] avatarImage = displayDetailsService.getGlobalDisplayAvatar(); if (avatarImage != null) return AndroidImageUtil.drawableFromBytes(avatarImage); return null; } /** * Returns the local user status drawable. * * @return the local user status drawable */ private static Drawable getLocalStatusDrawable() { GlobalStatusService globalStatusService = AndroidGUIActivator.getGlobalStatusService(); byte[] statusImage = StatusUtil.getContactStatusIcon( globalStatusService.getGlobalPresenceStatus()); return AndroidImageUtil.drawableFromBytes(statusImage); } /** * Sets the avatar icon for the given avatar view. * * @param avatarView the avatar image view * @param avatarDrawable the avatar drawable to set */ public void setAvatar( ImageView avatarView, Drawable avatarDrawable) { if (avatarDrawable == null) { avatarDrawable = JitsiApplication.getAppResources() .getDrawable(R.drawable.avatar); } avatarView.setImageDrawable(avatarDrawable); } /** * Sets the status of the given view. * * @param statusView the status icon view * @param statusDrawable the status drawable */ public void setStatus( ImageView statusView, Drawable statusDrawable) { statusView.setImageDrawable(statusDrawable); } /** * Sets the appropriate typing notification interface. * * @param typingState the typing state that should be represented in the * view */ public void setTypingState(int typingState) { if (typingView == null) return; TextView typingTextView = (TextView) typingView.findViewById(R.id.typingTextView); ImageView typingImgView = (ImageView) typingView.findViewById(R.id.typingImageView); boolean setVisible = false; if (typingState == OperationSetTypingNotifications.STATE_TYPING) { Drawable typingDrawable = typingImgView.getDrawable(); if (!(typingDrawable instanceof AnimationDrawable)) { typingImgView.setImageResource(R.drawable.typing_drawable); typingDrawable = typingImgView.getDrawable(); } if(!((AnimationDrawable) typingDrawable).isRunning()) { AnimationDrawable animatedDrawable = (AnimationDrawable) typingDrawable; animatedDrawable.setOneShot(false); animatedDrawable.start(); } typingTextView.setText(chatSession.getShortDisplayName() + " " + getResources() .getString(R.string.service_gui_CONTACT_TYPING)); setVisible = true; } else if (typingState == OperationSetTypingNotifications.STATE_PAUSED) { typingImgView.setImageResource(R.drawable.typing1); typingTextView.setText( chatSession.getShortDisplayName() + " " + getResources() .getString(R.string.service_gui_CONTACT_PAUSED_TYPING)); setVisible = true; } if (setVisible) { typingImgView.getLayoutParams().height = LayoutParams.WRAP_CONTENT; typingImgView.setPadding(7, 0, 7, 7); typingView.setVisibility(View.VISIBLE); } else typingView.setVisibility(View.INVISIBLE); } }
false
false
null
null
diff --git a/RealisticChat.java b/RealisticChat.java index 8409b2d..cb04899 100644 --- a/RealisticChat.java +++ b/RealisticChat.java @@ -1,1004 +1,1008 @@ package me.exphc.RealisticChat; import java.util.logging.Logger; import java.util.Set; import java.util.HashSet; import java.util.ArrayList; import java.util.List; import java.util.Iterator; import java.util.Random; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentSkipListSet; import java.util.Date; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.*; import org.bukkit.entity.*; import org.bukkit.event.*; import org.bukkit.event.player.*; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ShapedRecipe; import org.bukkit.enchantments.*; import org.bukkit.block.*; import org.bukkit.*; class SmartphoneCall { public static RealisticChat plugin; public static ConcurrentHashMap<Player, SmartphoneCall> calls = new ConcurrentHashMap<Player, SmartphoneCall>(); public static ConcurrentHashMap<Player, SmartphoneCall> ringingCall = new ConcurrentHashMap<Player, SmartphoneCall>(); //ConcurrentSkipListSet<Player> members; // not Comparable public HashSet<Player> members; public Date whenStarted, whenEnded; // set of all ringtones for each member, when call()ing someone new public HashSet<SmartphoneRinger> ringers; /** Create a new call, with only one player. */ public SmartphoneCall(Player caller) { //members = new ConcurrentSkipListSet<Player>(); members = new HashSet<Player>(); members.add(caller); // unfortunately, this is the time started calling not answered.. // will be reset in answer() whenStarted = new Date(); // for lookup calls.put(caller, this); ringers = new HashSet<SmartphoneRinger>(); } /** Try to establish a call with a new callee. */ public void call(Player callee) { stopRinging(); // If they're already holding the phone, they answer immediately! if (plugin.listener.holdingSmartphone(callee)) { answer(callee); return; } // Otherwise, we need to ring them until they answer // Ringing tone for everyone already online for (Player member: members) { ringers.add(new SmartphoneRinger(plugin, member)); } SmartphoneRinger calleeRinger = new SmartphoneRinger(plugin, callee); // Track everyone hearing the ringing for this callee, including callee itself ringers.add(calleeRinger); callee.sendMessage("Incoming call from "+getNames()+", pickup a smartphone to answer"); // Call which will be established if they answer! ringingCall.put(callee, this); } /** Answer (pickup) a ringing call. */ public void answer(Player callee) { // TODO: what timestamp to record for 3-way (or greater) calling? whenStarted = new Date(); ringingCall.remove(callee); stopRinging(); members.add(callee); // for lookup calls.put(callee, this); // Tell everyone about the new call String names = getNames(); for (Player member: members) { member.sendMessage("Call established: " + names); } } /** Get string of a list of names in the call. */ public String getNames() { ArrayList<String> names = new ArrayList<String>(); for (Player member: members) { names.add(member.getDisplayName()); } return RealisticChatListener.joinList(names, ", "); } private void stopRinging() { for (SmartphoneRinger ringer: ringers) { ringer.stop(); } ringers.clear(); } /** Get the call ringing to a player, or null if no one is calling. */ public static SmartphoneCall getRingingCall(Player callee) { return ringingCall.get(callee); } /** Find the call a player is participating in. */ public static SmartphoneCall lookup(Player member) { return calls.get(member); } /** Send a message to all members on a call. */ public void say(Player speaker, String message) { ArrayList<String> recvInfo = new ArrayList<String>(); recvInfo.add("smartphone"); for (Player member: members) { if (speaker != member) { RealisticChatListener.deliverMessage(member, speaker, "cell" + RealisticChatListener.getDeviceTag() + message, recvInfo); } } } /** Destroy a call. */ public void hangup() { whenEnded = new Date(); long durationMsec = whenEnded.getTime() - whenStarted.getTime(); long durationSeconds = (durationMsec / 1000) % 60; long durationMinutes = (durationMsec / 1000) / 60; // TODO: better duration formatting? String duration = durationMinutes + " m " + durationSeconds + " s"; for (Player member: members) { member.sendMessage("Hung up call, lasted " + duration); calls.remove(member); } // TODO: log calls } } /** Play a sequence of tones representing a telephone ringing. */ class SmartphoneRinger implements Runnable { private final Location noteblockLocation; private final Iterator<Note> notesIterator; private final int taskId; private final Player player; private final RealisticChat plugin; public SmartphoneRinger(RealisticChat plugin, Player player) { this.plugin = plugin; this.player = player; // Place a temporary noteblock above the player's head, required by the client to play a note // For why we do this see http://forums.bukkit.org/threads/player-playnote-is-it-broken.65404/#post-1023374 // TODO: what if player is at build limit? noteblockLocation = player.getLocation().add(0, 2, 0); - player.sendBlockChange(noteblockLocation, Material.NOTE_BLOCK, (byte)0); + Block oldBlock = noteblockLocation.getBlock(); + if (oldBlock == null || oldBlock.getType() == Material.AIR) { + // only send note block if not another in its place, to prevent bypassing world protections + player.sendBlockChange(noteblockLocation, Material.NOTE_BLOCK, (byte)0); + } List<Note> notes = new ArrayList<Note>(); // TODO: more phone-like ringing! for (int i = 0; i < plugin.getConfig().getInt("smartphoneRings", 4); i += 1) { notes.add(new Note(1, Note.Tone.A, false)); notes.add(new Note(1, Note.Tone.A, true)); notes.add(new Note(1, Note.Tone.A, false)); notes.add(new Note(1, Note.Tone.A, false)); notes.add(null); } notesIterator = notes.iterator(); long delay = 0; long period = 20/2; taskId = Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin, this, delay, period); } public void run() { if (notesIterator.hasNext()) { Note note = notesIterator.next(); if (note != null) { player.playNote(noteblockLocation, Instrument.PIANO, note); } } else { stop(); } } /** Stop ringing, either because call was established or did not answer. */ public void stop() { Bukkit.getScheduler().cancelTask(taskId); // Revert temporary noteblock Block lastBlock = noteblockLocation.getBlock(); player.sendBlockChange(noteblockLocation, lastBlock.getType(), lastBlock.getData()); // No longer eligible to answer SmartphoneCall.ringingCall.remove(player); } } class RealisticChatListener implements Listener { static RealisticChat plugin; Random random; public RealisticChatListener(RealisticChat plugin) { this.random = new Random(); this.plugin = plugin; Bukkit.getServer().getPluginManager().registerEvents(this, plugin); } @EventHandler(priority = EventPriority.NORMAL) public void onPlayerChat(PlayerChatEvent event) { Player sender = event.getPlayer(); String message = event.getMessage(); if (message.startsWith(getDeviceTag())) { // we made this event.. don't recurse! let it pass through to other plugins return; } ArrayList<String> sendInfo = new ArrayList<String>(); // First, global prefix overrides all if (message.startsWith(getGlobalPrefix())) { globallyDeliverMessage(sender, message.substring(getGlobalPrefix().length())); event.setCancelled(true); return; } // TODO: change to sound pressure level instead of distance based // see http://en.wikipedia.org/wiki/Sound_pressure#Examples_of_sound_pressure_and_sound_pressure_levels // for added realism, also to allow 130 dB = threshold of pain (player damage), nausea, http://en.wikipedia.org/wiki/Sound_cannon double speakingRange = plugin.getConfig().getDouble("speakingRangeMeters", 50.0); double garbleRangeDivisor = plugin.getConfig().getDouble("garbleRangeDivisor", 2.0); // so last 1/2.0 (half) of distance, speech is unclear // Yelling costs hunger and increases range int yell = countExclamationMarks(message); yell = Math.min(yell, plugin.getConfig().getInt("yellMax", 4)); if (yell > 0 && sender.hasPermission("realisticchat.yell")) { sendInfo.add("yell="+yell); final int defaultHunger[] = { 1, 2, 4, 20 }; final double defaultRangeIncrease[] = { 10.0, 50.0, 100.0, 500.0 }; int hunger = plugin.getConfig().getInt("yell."+yell+".hunger", defaultHunger[yell - 1]); // TODO: check food level first, and clamp yell if insufficient (or take away health hearts too?) sender.setFoodLevel(sender.getFoodLevel() - hunger); speakingRange += plugin.getConfig().getDouble("yell."+yell+".rangeIncrease", defaultRangeIncrease[yell - 1]); } // Whispering decreases range int whisper = countParenthesizeNests(message); if (whisper > 0 && sender.hasPermission("realisticchat.whisper")) { sendInfo.add("whisper="+whisper); speakingRange -= plugin.getConfig().getDouble("whisperRangeDecrease", 40.0) * whisper; if (speakingRange < 1) { speakingRange = 1; } } // Speaking into certain devices if (holdingBullhorn(sender)) { sendInfo.add("send-mega"); // calculated in recipient } else if (holdingSmartphone(sender)) { sendInfo.add("send-phone"); SmartphoneCall call = SmartphoneCall.lookup(sender); if (call != null) { // We're on a call! call.say(sender, message); if (!plugin.getConfig().getBoolean("smartphoneHearLocally", true)) { return; } // fall through and say locally too } else if (!sender.hasPermission("realisticchat.smartphone.call")) { //sender.sendMessage("You do not have permission to make calls"); } else { // Talking to voice-activated phone // TODO: natural language processing // TODO: detect commands, like voice-activated proximity-activated state-of-the-art smartphone String calleeName = message.replaceAll("[()!]", ""); // strip punctuation to try to understand better // Call player name if exists Player caller = sender; Player callee = Bukkit.getPlayer(calleeName); // interestingly, this does prefix matching.. // TODO: also check for offline player, to leave offline voicemail if (callee == null) { // TODO: ring but have no one pick up? Your call cannot be completed as dialed. sender.sendMessage("Sorry, I don't understand '"+calleeName+"'"); sender.sendMessage("Say a player name to place a call."); } else if (callee.equals(caller)) { // Tried to call self.. sender.sendMessage("Busy signal"); } else if (!callee.hasPermission("realisticchat.smartphone.answer")) { // TODO: move to call()? sender.sendMessage(callee.getDisplayName() + " does not have permission to answer calls"); } else { sender.sendMessage("Ringing "+callee.getDisplayName()+"..."); // TODO: ring until player picks up! Keep ringing, then the callee should have to // switch their held item to the smartphone in order to pickup. If they don't pick up // in time, or deny the call (shift-switch?) switch to their voicemail. call = new SmartphoneCall(caller); call.call(callee); // will be picked up on item change, if any /* if (isSmartphone(callee.getItemInHand())) { new SmartphoneCall(caller, callee); } else { sender.sendMessage(callee.getDisplayName() + " did not answer"); } */ } } if (!plugin.getConfig().getBoolean("smartphoneWaterproof", false)) { // Trying to use a phone underwater? Not the best idea // TODO: can we feasibly detect once player enters water? rather not listen to player move event though Block in = sender.getLocation().getBlock().getRelative(BlockFace.DOWN); if (in != null && (in.getType() == Material.WATER || in.getType() == Material.STATIONARY_WATER)) { if (call != null) { call.hangup(); } Item item = sender.getWorld().dropItemNaturally(sender.getLocation(), sender.getItemInHand()); item.setPickupDelay(plugin.getConfig().getInt("smartphoneWaterPickupDelay", 10000)); // can't pickup, will despawn before sender.setItemInHand(null); sender.sendMessage("Your smartphone was destroyed by water damage"); } } } // Log that the player tried to talk sendInfo.add("r="+speakingRange); plugin.log.info("<" + sender.getName() + ": "+joinList(sendInfo,",")+"> "+message); // Send to recipients for (Player recipient: event.getRecipients()) { ArrayList<String> recvInfo = new ArrayList<String>(); // TODO: special item to hold, to receive all or send to all (infinity compass?) if (sender.equals(recipient)) { // Talking to ourselves // TODO: still garble? if talking through something deliverMessage(recipient, sender, message, recvInfo); continue; } if (!sender.getWorld().equals(recipient.getWorld())) { // Not in this world! // TODO: cross-world communication device? continue; } double distance = sender.getLocation().distance(recipient.getLocation()); recvInfo.add("d="+distance); // Talking into walkie-talkie device if (hasWalkieTalking(sender) && hasWalkieListening(recipient)) { ArrayList<String> recvInfoWalkie = new ArrayList<String>(recvInfo); double walkieMaxRange = plugin.getConfig().getDouble("walkieRangeMeters", 2000.0); double walkieGarbleDivisor = plugin.getConfig().getDouble("walkieGarbleDivisor", 2.0); double walkieClearRange = walkieMaxRange / walkieGarbleDivisor; recvInfoWalkie.add("walkie="+walkieMaxRange+"/"+walkieClearRange); if (distance < walkieClearRange){ // Coming in loud and clear! // TODO: show as from walkie-talkie, but with callsign of sender? (instead of "foo:[via walkie]" "walkie:foo") deliverMessage(recipient, sender, "walkie" + getDeviceTag() + message, recvInfoWalkie); } else if (distance < walkieMaxRange) { // Can't quite make you out.. double walkieClarity = 1 - ((distance - walkieClearRange) / walkieMaxRange); recvInfoWalkie.add("wc="+walkieClarity); deliverMessage(recipient, sender, "walkie" + getDeviceTag() + garbleMessage(message, walkieClarity), recvInfoWalkie); } if (!plugin.getConfig().getBoolean("walkieHearLocally", true)) { continue; } // also fall through and deliver message locally } double hearingRange = speakingRange; if (holdingBullhorn(sender)) { /* * actSlop is measured in yaw, which itself is measured in 256 degrees, instead of * 360. actSlop is the degrees yaw of the angle from sender to rec. * micSlop is the yaw angle that the sender is facing. the equation in the if * statement on the left hand side of the "less than" symbol gives the difference between the * two slopes and the right hand side of the if statement checks to make sure the difference * is less than 35 degrees by default. This makes sure the receiving player is in the "sound cone". * If so, the bullhorn multipier is applied to the hearingRange of this receiving player. */ double deltaZ = recipient.getLocation().getZ() - sender.getLocation().getZ(); double deltaX = recipient.getLocation().getX() - sender.getLocation().getX(); double actSlop = 0; if (deltaZ <= 0 && deltaX >= 0) actSlop = Math.toDegrees(Math.tan(deltaX/(-1*deltaZ)))+180; if (deltaZ >= 0 && deltaX > 0) actSlop = Math.toDegrees(Math.tan(deltaZ/(deltaX)))+270; if (deltaZ > 0 && deltaX <= 0) actSlop = Math.toDegrees(Math.tan((-1*deltaX)/(deltaZ))); if (deltaZ <= 0 && deltaX < 0) actSlop = Math.toDegrees(Math.tan((-1*deltaZ)/(-1*deltaX)))+90; actSlop %= 360; double micSlop = sender.getLocation().getYaw() * (360/256); double dMicSlop = (micSlop +180)%360; double dActSlop = (actSlop +180)%360; double degree = Math.abs(micSlop - actSlop); double ddegree = Math.abs(dMicSlop = dActSlop); recvInfo.add("mega-actSlop=" + actSlop); recvInfo.add("mega-micSlop=" + micSlop); recvInfo.add("mega-deltaZ=" + deltaZ); recvInfo.add("mega-deltaX=" + deltaX); recvInfo.add("mega-degree=" + degree); // If within 70 degrees (the default Minecraft FOV), heard bullhorn if (degree < plugin.getConfig().getDouble("bullhornWidthDegrees", 70.0) || ddegree < plugin.getConfig().getDouble("bullhornWidthDegrees", 70.0)){ recvInfo.add("mega-HEARD"); hearingRange *= plugin.getConfig().getDouble("bullhornFactor", 2.0); } } // Ear trumpets increase hearing range only double earTrumpetRange = getEarTrumpetRange(recipient); if (earTrumpetRange != 0 && sender.hasPermission("realisticchat.eartrumpet")) { recvInfo.add("ear="+earTrumpetRange); hearingRange += earTrumpetRange; } recvInfo.add("hr="+hearingRange); // Limit distance if (distance > hearingRange) { continue; } double clearRange = hearingRange / garbleRangeDivisor; if (distance > clearRange) { // At distances speakingRangeMeters..garbleRangeMeters (50..25), break up // with increasing probability the further away they are. // 24 = perfectly clear // 25 = slightly garbled // (distance-25)/50 // 50 = half clear // TODO: different easing function than linear? double noise = (distance - clearRange) / hearingRange; double clarity = 1 - noise; recvInfo.add("clarity="+clarity); deliverMessage(recipient, sender, garbleMessage(message, clarity), recvInfo); } else { deliverMessage(recipient, sender, message, recvInfo); } } // Deliver the message manually, so we can customize the chat display // TODO: we really should NOT cancel the event, instead let it through and use setFormat() // to customize the display. This will increase compatibility with other chat programs. // The problem is how to deliver the messages twice.. (sendMessage for one of them?) // See discussion at http://forums.bukkit.org/threads/help-how-to-stop-other-players-from-seeing-chat.66537/#post-1035424 event.setCancelled(true); } /** Get whether the player has a walkie-talkie ready to talk into. */ private static boolean hasWalkieTalking(Player player) { if (!plugin.getConfig().getBoolean("walkieEnable", true)) { return false; } if (!player.hasPermission("realisticchat.walkie.talk")) { return false; } ItemStack held = player.getItemInHand(); return held != null && held.getTypeId() == plugin.walkieItemId; } /** Get whether the player has a walkie-talkie ready for listening. */ private static boolean hasWalkieListening(Player player) { if (!plugin.getConfig().getBoolean("walkieEnable", true)) { return false; } if (!player.hasPermission("realisticchat.walkie.hear")) { return false; } ItemStack[] contents = player.getInventory().getContents(); final int HOTBAR_SIZE = 9; // Player can hear walkie if placed anywhere within their hotbar slots (not elsewhere) for (int i = 0; i < HOTBAR_SIZE; i += 1) { ItemStack item = contents[i]; if (item != null && item.getTypeId() == plugin.walkieItemId) { return true; } } return false; } /** Get whether the player has a bullhorn to talk into. */ private static boolean holdingBullhorn(Player player) { if (!plugin.getConfig().getBoolean("bullhornEnable", true)) { return false; } if (!player.hasPermission("realisticchat.bullhorn")) { return false; } ItemStack held = player.getItemInHand(); return held != null && held.getTypeId() == plugin.bullhornItemId; } /** Get the range increase of the ear trumpet the player is wearing, or 0 if none. Inspired by http://en.wikipedia.org/wiki/Ear_trumpet - 1600s precursor to modern electric hearing aid */ private double getEarTrumpetRange(Player player) { ItemStack ear = getEarTrumpet(player); if (ear == null) { return 0; } int level = ear.getEnchantmentLevel(EFFICIENCY); if (level > 3) { level = 3; } final double[] defaultRanges = { 100.0, 150.0, 400.0 }; double range = plugin.getConfig().getDouble("earTrumpet."+level+".rangeIncrease", defaultRanges[level - 1]); return range; } final private static Enchantment EFFICIENCY = Enchantment.DIG_SPEED; /** Get the ear trumpet item the player is wearing, or null. */ private ItemStack getEarTrumpet(Player player) { if (!plugin.getConfig().getBoolean("earTrumpetEnable", true)) { return null; } ItemStack helmet = player.getInventory().getHelmet(); if (helmet != null && helmet.getType() == Material.GOLD_HELMET && helmet.containsEnchantment(EFFICIENCY)) { return helmet; } else { return null; } } public static String joinList(ArrayList<String> list, String sep) { StringBuilder sb = new StringBuilder(); for (String item: list) { sb.append(item + sep); } String s = sb.toString(); if (s.length() == 0) { return ""; } else { return s.substring(0, s.length() - sep.length()); } } /** Count number of trailing exclamation marks */ private int countExclamationMarks(String message) { int yell = 0; while (message.length() > 1 && message.endsWith("!")) { message = message.substring(0, message.length() - 1); yell += 1; } return yell; } /** Count number of nested surrounding parenthesizes */ private int countParenthesizeNests(String message) { int whisper = 0; while (message.length() > 2 && message.startsWith("(") && message.endsWith(")")) { message = message.substring(1, message.length() - 1); whisper += 1; } return whisper; } /** Randomly garble a message (drop letters) as if it was incompletely heard. * * @param message The clear message * @param clarity Probability of getting through * @return The broken up message */ private String garbleMessage(String message, double clarity) { // Delete random letters StringBuilder newMessage = new StringBuilder(); // This string character iteration method is cumbersome, but it is // the most correct, especially if players are using plane 1 characters // see http://mindprod.com/jgloss/codepoint.html int i = 0; int drops = 0; while (i < message.length()) { int c = message.codePointAt(i); i += Character.charCount(c); if (random.nextDouble() < clarity) { newMessage.appendCodePoint(c); } else { // can't hear you.. if (random.nextDouble() < plugin.getConfig().getDouble("garblePartialChance", 0.10)) { // barely got through (dimmed) newMessage.append(plugin.dimMessageColor); newMessage.appendCodePoint(c); newMessage.append(plugin.messageColor); } else { newMessage.append(' '); drops += 1; } } } if (drops == message.length()) { // bad luck, message was completely obscured // TODO: improve conditional?; might have replaced all letters but not spaces.. String noise = plugin.getConfig().getString("garbleAllDroppedMessage", "~~~"); if (noise != null) { return noise; } } return new String(newMessage); } /** Get a special character used to separate device name from chat message. Should never appear in normal chat. */ public static String getDeviceTag() { return "\u0001"; // C0 Start of Heading (SOH) } /** Send a message to everyone on the server. */ public void globallyDeliverMessage(Player sender, String message) { ArrayList<String> sendInfo = new ArrayList<String>(); sendInfo.add("global"); for (Player recipient: Bukkit.getOnlinePlayers()) { deliverMessage(recipient, sender, "global" + getDeviceTag() + message, sendInfo); } } /** Send a properly-formatted chat message, to the user and to other plugins. The message can be prefixed with a device name + getDeviceTag() for special formatting. */ public static void deliverMessage(Player recipient, Player sender, String message, ArrayList<String> info) { PlayerChatEvent event = createChatEvent(recipient, sender, message, info); callChatEvent(event); } private static void callChatEvent(PlayerChatEvent event) { // Tag the message so we know it is ours.. event.setMessage(getDeviceTag() + event.getMessage()); // Allow other plugins to process event Bukkit.getServer().getPluginManager().callEvent(event); if (event.isCancelled()) { plugin.log.info(" ignoring chat event cancelled by other plugin: " + event); return; } // Deliver (possibly modified) chat to player as message // based on src/main/java/net/minecraft/server/NetServerHandler.java : chat() String s = String.format(event.getFormat(), event.getPlayer().getDisplayName(), event.getMessage()); // Strip the tag completely from the message, wherever it might be s = s.replace(getDeviceTag(), ""); //minecraftServer.console.sendMessage(s); // TODO for (Player recipient : event.getRecipients()) { recipient.sendMessage(s); } } /** Synthesize a new chat event between two players, with customized formatting. */ private static PlayerChatEvent createChatEvent(Player recipient, Player sender, String message, ArrayList<String> info) { ChatColor senderColor = (sender.equals(recipient) ? plugin.spokenPlayerColor : plugin.heardPlayerColor); String device = null; // Tagged message, from a device int divider = message.indexOf(getDeviceTag()); if (divider != -1) { device = message.substring(0, divider); message = message.substring(divider + 1); } // Get the message format accordingly depending on how it was received String defaultFormat = plugin.getConfig().getString("chatLineFormat", "%1$s: %2$s"); String format = defaultFormat; if (holdingBullhorn(sender)) { // TODO: move to device tagging on message like walkie/cell String direction = bullhornDirection(recipient, sender); if (direction != null && !direction.equals("")) { format = String.format(plugin.getConfig().getString("bullhornChatLineFormat", "%1$s [%3$s]: %2$s"), "%1$s", // player, replaced below "%2$s", // message, replaced below direction); } } if (device != null) { if (device.equals("walkie")) { format = plugin.getConfig().getString("walkieChatLineFormat", "[walkie] %1$s: %2$s"); } else if (device.equals("cell")) { format = plugin.getConfig().getString("smartphoneChatLineFormat", "[cell] %1$s: %2$s"); } else if (device.equals("global")) { format = plugin.getConfig().getString("globalChatLineFormat", "[global] %1$s: %2$s"); } } if (format == null) { format = defaultFormat; } // Add player name color to format string format = String.format(format, senderColor + "%1$s" + plugin.messageColor, "%2$s"); // Format the message //String formattedMessage = String.format(format, senderColor + sender.getDisplayName() + plugin.messageColor, message); //plugin.log.info(formattedMessage); //recipient.sendMessage(formattedMessage); // TODO: instead, use recipient.chat() and PlayerChatEvent setFormat(), so other plugins see the chat, too // or, construct a PlayerChatEvent and send it ourselves so other plugins can format messages from cells/walkies // .. but the challenge is avoiding infinite recursion (TODO: tagged messages, don't resend if tagged) plugin.log.info("[RealisticChat] ("+joinList(info, ",")+") "+sender.getName() + " -> " + recipient.getName() + ": " + message); // Output is the message format and message itself, in the event object PlayerChatEvent newEvent = new PlayerChatEvent(sender, message); newEvent.getRecipients().clear(); newEvent.getRecipients().add(recipient); newEvent.setFormat(format); return newEvent; } /** Get the direction a bullhorn-amplified message came from, if possible. */ private static String bullhornDirection(Player recipient, Player sender){ if (!plugin.getConfig().getBoolean("bullhornEnable", true) || !holdingBullhorn(sender)) { return ""; } String addition = ""; double recX = recipient.getLocation().getX(); double recZ = recipient.getLocation().getZ(); double senX = sender.getLocation().getX(); double senZ = sender.getLocation().getZ(); if (recZ > senZ) addition += "North"; if (recZ < senZ) addition += "South"; if (recX > senX) addition += "West"; if (recX < senX) addition += "East"; return addition; } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled=true) public void onPlayerItemHeld(PlayerItemHeldEvent event) { Player player = event.getPlayer(); int slot = event.getNewSlot(); ItemStack held = player.getInventory().getItem(slot); if (isSmartphone(held)) { SmartphoneCall pendingCall = SmartphoneCall.getRingingCall(player); if (pendingCall != null) { player.sendMessage("Answering call"); pendingCall.answer(player); } } else { // Switching off of phone hangs it up // TODO: other ways to hangup.. dropped item? SmartphoneCall call = SmartphoneCall.lookup(player); if (call != null) { call.hangup(); } } } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled=true) public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) { if (getGlobalPrefix() == null) { return; } if (event.getMessage().startsWith(getGlobalPrefix())) { globallyDeliverMessage(event.getPlayer(), event.getMessage().substring(getGlobalPrefix().length())); event.setCancelled(true); } } /** Get prefix for messages to be sent globally. May be a command (beginning with '/'), normal chat message, or null (if disabled) */ private String getGlobalPrefix() { return plugin.getConfig().getString("globalPrefix", "/g "); } /** Get whether the item is a smart phone device. */ private boolean isSmartphone(ItemStack item) { if (!plugin.getConfig().getBoolean("smartphoneEnable", true)) { return false; } return item != null && item.getTypeId() == plugin.smartphoneItemId; } /** Get whether the player is holding their smartphone, possibly speaking into it. */ public boolean holdingSmartphone(Player player) { return isSmartphone(player.getItemInHand()); } } public class RealisticChat extends JavaPlugin { Logger log = Logger.getLogger("Minecraft"); RealisticChatListener listener; int walkieItemId, bullhornItemId, smartphoneItemId; ChatColor spokenPlayerColor, heardPlayerColor, messageColor, dimMessageColor; public void onEnable() { // Copy default config getConfig().options().copyDefaults(true); saveConfig(); reloadConfig(); walkieItemId = getConfigItemId("walkieItem", Material.COMPASS.getId()); bullhornItemId = getConfigItemId("bullhornItem", Material.DIAMOND.getId()); smartphoneItemId = getConfigItemId("smartphoneItem", Material.WATCH.getId()); spokenPlayerColor = getConfigColor("chatSpokenPlayerColor", ChatColor.YELLOW); heardPlayerColor = getConfigColor("chatHeardPlayerColor", ChatColor.GREEN); messageColor = getConfigColor("chatMessageColor", ChatColor.WHITE); dimMessageColor = getConfigColor("chatDimMessageColor", ChatColor.DARK_GRAY); if (getConfig().getBoolean("earTrumpetEnable", true) && getConfig().getBoolean("earTrumpetEnableCrafting", true)) { loadRecipes(); } listener = new RealisticChatListener(this); SmartphoneCall.plugin = this; } /** Get a chat color from a configuration setting. */ private ChatColor getConfigColor(String name, ChatColor defaultColor) { String s = getConfig().getString(name); if (s == null) { return defaultColor; } try { return ChatColor.valueOf(s); } catch (IllegalArgumentException e) { log.warning("Bad color name: " + s + ", using default: " + defaultColor + ": " + e); return defaultColor; } } /** Get an item id from a configuration setting (name or numeric id) */ private int getConfigItemId(String name, int defaultId) { String s = getConfig().getString(name); if (s == null) { return defaultId; } // TODO: can we use ItemStack ConfigurationSerializable? might be easier.. Material material = Material.matchMaterial(s); if (material != null) { return material.getId(); } try { return Integer.parseInt(s, 10); } catch (NumberFormatException e) { log.warning("Bad item id: " + s + ", using default: " + defaultId); return defaultId; } } public void onDisable() { // TODO: new recipe API to remove..but won't work in 1.1-R4 so I can't use it on ExpHC yet :( } final private static Enchantment EFFICIENCY = Enchantment.DIG_SPEED; private void loadRecipes() { ItemStack earTrumpetWoodItem = new ItemStack(Material.GOLD_HELMET, 1); ItemStack earTrumpetLeatherItem = new ItemStack(Material.GOLD_HELMET, 1); ItemStack earTrumpetIronItem = new ItemStack(Material.GOLD_HELMET, 1); // TODO: add workaround BUKKIT-602 for 1.1-R4 // see https://github.com/mushroomhostage/SilkSpawners/commit/0763f29f217662c97a0b4a155649e14e8beb92c9 // https://bukkit.atlassian.net/browse/BUKKIT-602 Enchantments lost on crafting recipe output earTrumpetWoodItem.addUnsafeEnchantment(EFFICIENCY, 1); earTrumpetLeatherItem.addUnsafeEnchantment(EFFICIENCY, 2); earTrumpetIronItem.addUnsafeEnchantment(EFFICIENCY, 3); ShapedRecipe earTrumpetWood = new ShapedRecipe(earTrumpetWoodItem); ShapedRecipe earTrumpetLeather = new ShapedRecipe(earTrumpetLeatherItem); ShapedRecipe earTrumpetIron = new ShapedRecipe(earTrumpetIronItem); earTrumpetWood.shape( "WWW", "WDW"); earTrumpetWood.setIngredient('W', Material.WOOD); // planks earTrumpetWood.setIngredient('D', Material.DIAMOND); Bukkit.addRecipe(earTrumpetWood); earTrumpetLeather.shape( "LLL", "LDL"); earTrumpetLeather.setIngredient('L', Material.LEATHER); earTrumpetLeather.setIngredient('D', Material.DIAMOND); Bukkit.addRecipe(earTrumpetLeather); earTrumpetIron.shape( "III", "IDI"); earTrumpetIron.setIngredient('I', Material.IRON_INGOT); earTrumpetIron.setIngredient('D', Material.DIAMOND); Bukkit.addRecipe(earTrumpetIron); } }
true
false
null
null
diff --git a/Slick/tools/org/newdawn/slick/tools/peditor/ParticleEditor.java b/Slick/tools/org/newdawn/slick/tools/peditor/ParticleEditor.java index e62be57..2f36620 100644 --- a/Slick/tools/org/newdawn/slick/tools/peditor/ParticleEditor.java +++ b/Slick/tools/org/newdawn/slick/tools/peditor/ParticleEditor.java @@ -1,676 +1,674 @@ package org.newdawn.slick.tools.peditor; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.event.MouseMotionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JSlider; import javax.swing.JTabbedPane; import javax.swing.UIManager; import javax.swing.WindowConstants; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.filechooser.FileFilter; import org.lwjgl.LWJGLException; import org.newdawn.slick.CanvasGameContainer; import org.newdawn.slick.InputListener; import org.newdawn.slick.SlickException; import org.newdawn.slick.particles.ConfigurableEmitter; import org.newdawn.slick.particles.ParticleIO; import org.newdawn.slick.particles.ParticleSystem; import org.newdawn.slick.util.InputAdapter; import org.newdawn.slick.util.Log; /** * The bootstrap and main frame for the particle editor Pedigree. * * @author kevin */ public class ParticleEditor extends JFrame { /** The canvas displaying the particles */ private ParticleGame game; /** Create a new system */ private JMenuItem newSystem = new JMenuItem("New System"); /** Load a complete particle system */ private JMenuItem load = new JMenuItem("Load System"); /** Save a complete particle system */ private JMenuItem save = new JMenuItem("Save System"); /** Load a single particle emitter */ private JMenuItem imp = new JMenuItem("Import Emitter"); /** Clone a single particle emitter */ private JMenuItem clone = new JMenuItem("Clone Emitter"); /** Save a single particle emitter */ private JMenuItem exp = new JMenuItem("Export Emitter"); /** Toggle the HUD */ private JMenuItem hud = new JMenuItem("Toggle Overlay"); /** Toggle the HUD */ private JMenuItem loadBackground = new JMenuItem("Load Background Image"); /** Toggle the HUD */ private JMenuItem clearBackground = new JMenuItem("Clear Background Image"); /** Toggle the graphice editor */ private JMenuItem whiskas = new JMenuItem("Show/Hide Graph Editor"); /** Exit the editor */ private JMenuItem quit = new JMenuItem("Exit"); /** The visual list of emitters */ private EmitterList emitters; /** The controls for the initial emission settings */ private EmissionControls emissionControls; /** The positional controls for spawnng particles */ private PositionControls positionControls; /** The global settings for the emitter */ private SettingsPanel settingsPanel; /** The color controls for particles */ private ColorPanel colorPanel; /** The limiting controls for particles */ private LimitPanel limitPanel; /** The whiskas panel */ private WhiskasPanel whiskasPanel; /** Control for the type of particle system blending */ private JCheckBox additive = new JCheckBox("Additive Blending"); /** Control for the type of particle point usage */ private JCheckBox pointsEnabled = new JCheckBox("Use Points"); /** The currently selected particle emitter */ private ConfigurableEmitter selected; /** Chooser used to load/save/import/export */ private JFileChooser chooser = new JFileChooser(new File(".")); /** Reset the particle counts on the canvas */ private JButton reset = new JButton("Reset Max"); /** Play or Pause the current rendering */ private JButton pause = new JButton("Play/Pause"); /** The slider defining the movement of the system */ private JSlider systemMove = new JSlider(-100,100,0); /** The graph editor frame **/ private JFrame graphEditorFrame; /** The filter in use */ private FileFilter xmlFileFilter; /** * Create a new editor * * @throws LWJGLException Indicates a failure to create an OpenGL context + * @throws SlickException */ - public ParticleEditor() throws LWJGLException { + public ParticleEditor() throws LWJGLException, SlickException { super("Pedigree - Whiskas flavoured"); xmlFileFilter = new FileFilter() { public boolean accept(File f) { if (f.isDirectory()) { return true; } if (f.getName().endsWith(".xml")) { return true; } return false; } public String getDescription() { return "XML Files"; } }; chooser.setFileFilter(xmlFileFilter); // try { // InputStream in = ParticleEditor.class.getClassLoader().getResourceAsStream("org/newdawn/slick/tools/peditor/data/icon.gif"); // // setIconImage(ImageIO.read(in)); // } catch (IOException e) { // e.printStackTrace(); // } emitters = new EmitterList(this); emissionControls = new EmissionControls(); positionControls = new PositionControls(); settingsPanel = new SettingsPanel(emitters); colorPanel = new ColorPanel(); limitPanel = new LimitPanel(emitters); whiskasPanel= new WhiskasPanel( emitters, colorPanel, emissionControls ); JPopupMenu.setDefaultLightWeightPopupEnabled(false); JMenu file = new JMenu("File"); file.add(newSystem); file.addSeparator(); file.add(load); file.add(save); file.addSeparator(); file.add(imp); file.add(clone); file.add(exp); file.addSeparator(); file.add(hud); file.add(whiskas); file.addSeparator(); file.add(loadBackground); file.add(clearBackground); file.addSeparator(); file.add(quit); loadBackground.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { loadBackground(); } }); clearBackground.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { clearBackground(); } }); newSystem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { createNewSystem(); } }); hud.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { game.setHud(!game.isHudOn()); } }); load.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { loadSystem(); } }); save.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { saveSystem(); } }); clone.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { cloneEmitter(); } }); exp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { exportEmitter(); } }); imp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { importEmitter(); } }); quit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.exit(0); } }); whiskas.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { graphEditorFrame.setVisible(!graphEditorFrame.isVisible()); } }); JMenuBar bar = new JMenuBar(); bar.add(file); setJMenuBar(bar); game = new ParticleGame(this); final CanvasGameContainer container = new CanvasGameContainer(game); container.setSize(500,600); JPanel controls = new JPanel(); controls.setLayout(null); emitters.setBounds(0,0,300,150); emitters.setBorder(BorderFactory.createTitledBorder("Emitters")); controls.add(emitters); JTabbedPane tabs = new JTabbedPane(); tabs.setBounds(0,150,300,350); controls.add(tabs); tabs.add("Settings", settingsPanel); tabs.add("Emission", emissionControls); tabs.add("Position", positionControls); tabs.add("Rendering", colorPanel); tabs.add("Limit", limitPanel); tabs.add("Whiskas", whiskasPanel); JPanel panel = new JPanel(); panel.setLayout(null); container.setBounds(0,0,500,600); controls.setBounds(500,20,300,575); reset.setBounds(90,500,90,25); controls.add(reset); systemMove.setBounds(180,500,120,25); controls.add(systemMove); pause.setBounds(0,500,90,25); controls.add(pause); additive.setBounds(500,0,150,25); panel.add(additive); pointsEnabled.setBounds(650,0,150,25); panel.add(pointsEnabled); panel.add(container); panel.add(controls); systemMove.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { game.setSystemMove(systemMove.getValue(),false); } }); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); additive.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { updateBlendMode(); } }); pointsEnabled.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { game.getSystem().setUsePoints(pointsEnabled.isSelected()); } }); reset.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { game.resetCounts(); } }); pause.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { game.setPaused(!game.isPaused()); } }); ConfigurableEmitter test = new ConfigurableEmitter("Default"); emitters.add(test); game.addEmitter(test); additive.setSelected(true); setContentPane(panel); setSize(800,600); setResizable(false); setVisible(true); InputListener listener = new InputAdapter() { public void mousePressed(int x, int y, int button) { if (button != 0) { positionControls.setPosition(0,0); } systemMove.setValue(0); game.setSystemMove(0,true); } public void mouseMoved(int x, int y, int nx, int ny) { if (container.getContainer().getInput().isMouseButtonDown(0)) { int xp = nx - 250; int yp = ny - 300; positionControls.setPosition(xp,yp); systemMove.setValue(0); game.setSystemMove(0,true); } } }; game.setListener(listener); // init graph window initGraphEditorWindow(); emitters.setSelected(0); try { container.start(); } catch (SlickException e1) { Log.error(e1); } } /** * Load a background image to display behind the particle system */ private void loadBackground() { JFileChooser chooser = new JFileChooser("."); chooser.setDialogTitle("Open"); int resp = chooser.showOpenDialog(this); if (resp == JFileChooser.APPROVE_OPTION) { game.setBackgroundImage(chooser.getSelectedFile()); } } /** * Clear the background image in use */ private void clearBackground() { game.setBackgroundImage(null); } /** * init the graph editor window */ private void initGraphEditorWindow() { // create the window GraphEditorWindow editor = new GraphEditorWindow(); whiskasPanel.setEditor(editor); graphEditorFrame= new JFrame("Whiskas Gradient Editor"); graphEditorFrame.getContentPane().add(editor); graphEditorFrame.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE); graphEditorFrame.pack(); graphEditorFrame.setSize(600, 300); graphEditorFrame.setLocation(this.getX(), this.getY()+this.getHeight()); graphEditorFrame.setVisible(true); // try { // InputStream in = ParticleEditor.class.getClassLoader().getResourceAsStream("org/newdawn/slick/tools/peditor/data/icon.gif"); // // //graphEditorFrame.setIconImage(ImageIO.read(in)); // } catch (IOException e) { // e.printStackTrace(); // } } /** * Set the movement of the system * * @param move The movement of the system */ public void setSystemMove(int move) { systemMove.setValue(move); } /** * Import an emitter XML file */ public void importEmitter() { chooser.setDialogTitle("Open"); int resp = chooser.showOpenDialog(this); if (resp == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); File path = file.getParentFile(); try { final ConfigurableEmitter emitter = ParticleIO.loadEmitter(file); if (emitter.getImageName() != null) { File possible = new File(path, emitter.getImageName()); if (possible.exists()) { emitter.setImageName(possible.getAbsolutePath()); } else { chooser.setDialogTitle("Locate the image: "+emitter.getImageName()); resp = chooser.showOpenDialog(this); FileFilter filter = new FileFilter() { public boolean accept(File f) { if (f.isDirectory()) { return true; } return (f.getName().equals(emitter.getImageName())); } public String getDescription() { return emitter.getImageName(); } }; chooser.addChoosableFileFilter(filter); if (resp == JFileChooser.APPROVE_OPTION) { File image = chooser.getSelectedFile(); emitter.setImageName(image.getAbsolutePath()); path = image.getParentFile(); } chooser.resetChoosableFileFilters(); chooser.addChoosableFileFilter(xmlFileFilter); } } addEmitter(emitter); emitters.setSelected(emitter); } catch (IOException e) { Log.error(e); JOptionPane.showMessageDialog(this, e.getMessage()); } } } /** * Clone the selected emitter */ public void cloneEmitter() { if (selected == null) { return; } try { ByteArrayOutputStream bout = new ByteArrayOutputStream(); ParticleIO.saveEmitter(bout, selected); ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray()); ConfigurableEmitter emitter = ParticleIO.loadEmitter(bin); emitter.name = emitter.name + "_clone"; addEmitter(emitter); emitters.setSelected(emitter); } catch (IOException e) { Log.error(e); JOptionPane.showMessageDialog(this, e.getMessage()); } } /** * Export an emitter XML file */ public void exportEmitter() { if (selected == null) { return; } chooser.setDialogTitle("Save"); int resp = chooser.showSaveDialog(this); if (resp == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); if (!file.getName().endsWith(".xml")) { file = new File(file.getAbsolutePath()+".xml"); } try { ParticleIO.saveEmitter(file, selected); } catch (IOException e) { Log.error(e); JOptionPane.showMessageDialog(this, e.getMessage()); } } } /** * Create a completely new particle system */ public void createNewSystem() { game.clearSystem(additive.isSelected()); pointsEnabled.setSelected(false); emitters.clear(); } /** * Load a complete particle system XML description */ public void loadSystem() { chooser.setDialogTitle("Open"); int resp = chooser.showOpenDialog(this); if (resp == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); File path = file.getParentFile(); try { ParticleSystem system = ParticleIO.loadConfiguredSystem(file); game.setSystem(system); emitters.clear(); for (int i=0;i<system.getEmitterCount();i++) { final ConfigurableEmitter emitter = (ConfigurableEmitter) system.getEmitter(i); if (emitter.getImageName() != null) { File possible = new File(path, emitter.getImageName()); if (possible.exists()) { emitter.setImageName(possible.getAbsolutePath()); } else { chooser.setDialogTitle("Locate the image: "+emitter.getImageName()); FileFilter filter = new FileFilter() { public boolean accept(File f) { if (f.isDirectory()) { return true; } return (f.getName().equals(emitter.getImageName())); } public String getDescription() { return emitter.getImageName(); } }; chooser.addChoosableFileFilter(filter); resp = chooser.showOpenDialog(this); if (resp == JFileChooser.APPROVE_OPTION) { File image = chooser.getSelectedFile(); emitter.setImageName(image.getAbsolutePath()); path = image.getParentFile(); } chooser.setDialogTitle("Open"); chooser.resetChoosableFileFilters(); chooser.addChoosableFileFilter(xmlFileFilter); } } emitters.add(emitter); } additive.setSelected(system.getBlendingMode() == ParticleSystem.BLEND_ADDITIVE); pointsEnabled.setSelected(system.usePoints()); emitters.setSelected(0); } catch (IOException e) { Log.error(e); JOptionPane.showMessageDialog(this, e.getMessage()); } } } /** * Save a complete particle system XML description */ public void saveSystem() { int resp = chooser.showSaveDialog(this); if (resp == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); if (!file.getName().endsWith(".xml")) { file = new File(file.getAbsolutePath()+".xml"); } try { ParticleIO.saveConfiguredSystem(file, game.getSystem()); } catch (IOException e) { Log.error(e); JOptionPane.showMessageDialog(this, e.getMessage()); } } } /** * Add a new emitter to the editor * * @param emitter The emitter to add */ public void addEmitter(ConfigurableEmitter emitter) { emitters.add(emitter); game.addEmitter(emitter); } /** * Remove a particle emitter from the editor * * @param emitter The emitter to be removed */ public void removeEmitter(ConfigurableEmitter emitter) { emitters.remove(emitter); game.removeEmitter(emitter); } /** * Set the currently selected and edited particle emitter * * @param emitter The emitter that should be selected or null for none */ public void setCurrentEmitter(ConfigurableEmitter emitter) { this.selected = emitter; if (emitter == null) { emissionControls.setEnabled(false); settingsPanel.setEnabled(false); positionControls.setEnabled(false); colorPanel.setEnabled(false); limitPanel.setEnabled(false); whiskasPanel.setEnabled(false); } else { emissionControls.setEnabled(true); settingsPanel.setEnabled(true); positionControls.setEnabled(true); colorPanel.setEnabled(true); limitPanel.setEnabled(true); whiskasPanel.setEnabled(true); emissionControls.setTarget(emitter); settingsPanel.setTarget(emitter); positionControls.setTarget(emitter); settingsPanel.setTarget(emitter); colorPanel.setTarget(emitter); limitPanel.setTarget(emitter); whiskasPanel.setTarget(emitter); } } /** * Change the visual indicator for the current particle system * blend mode */ public void updateBlendMode() { if (additive.isSelected()) { game.getSystem().setBlendingMode(ParticleSystem.BLEND_ADDITIVE); } else { game.getSystem().setBlendingMode(ParticleSystem.BLEND_COMBINE); } } /** * Entry point in the editor * * @param argv The arguments passed on the command line */ public static void main(String[] argv) { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); new ParticleEditor(); } catch (Exception e) { Log.error(e); } } }
false
false
null
null
diff --git a/src/main/java/org/apache/commons/math3/optimization/linear/SimplexSolver.java b/src/main/java/org/apache/commons/math3/optimization/linear/SimplexSolver.java index bb7960b19..9446882c2 100644 --- a/src/main/java/org/apache/commons/math3/optimization/linear/SimplexSolver.java +++ b/src/main/java/org/apache/commons/math3/optimization/linear/SimplexSolver.java @@ -1,237 +1,238 @@ /* * 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.commons.math3.optimization.linear; import java.util.ArrayList; import java.util.List; import org.apache.commons.math3.exception.MaxCountExceededException; import org.apache.commons.math3.optimization.PointValuePair; import org.apache.commons.math3.util.Precision; /** * Solves a linear problem using the Two-Phase Simplex Method. * @version $Id$ * @since 2.0 */ public class SimplexSolver extends AbstractLinearOptimizer { /** Default amount of error to accept for algorithm convergence. */ private static final double DEFAULT_EPSILON = 1.0e-6; /** Default amount of error to accept in floating point comparisons (as ulps). */ private static final int DEFAULT_ULPS = 10; /** Amount of error to accept for algorithm convergence. */ private final double epsilon; /** Amount of error to accept in floating point comparisons (as ulps). */ private final int maxUlps; /** * Build a simplex solver with default settings. */ public SimplexSolver() { this(DEFAULT_EPSILON, DEFAULT_ULPS); } /** * Build a simplex solver with a specified accepted amount of error * @param epsilon the amount of error to accept for algorithm convergence * @param maxUlps amount of error to accept in floating point comparisons */ public SimplexSolver(final double epsilon, final int maxUlps) { this.epsilon = epsilon; this.maxUlps = maxUlps; } /** * Returns the column with the most negative coefficient in the objective function row. * @param tableau simple tableau for the problem * @return column with the most negative coefficient */ private Integer getPivotColumn(SimplexTableau tableau) { double minValue = 0; Integer minPos = null; for (int i = tableau.getNumObjectiveFunctions(); i < tableau.getWidth() - 1; i++) { final double entry = tableau.getEntry(0, i); // check if the entry is strictly smaller than the current minimum // do not use a ulp/epsilon check if (entry < minValue) { minValue = entry; minPos = i; } } return minPos; } /** * Returns the row with the minimum ratio as given by the minimum ratio test (MRT). * @param tableau simple tableau for the problem * @param col the column to test the ratio of. See {@link #getPivotColumn(SimplexTableau)} * @return row with the minimum ratio */ private Integer getPivotRow(SimplexTableau tableau, final int col) { // create a list of all the rows that tie for the lowest score in the minimum ratio test List<Integer> minRatioPositions = new ArrayList<Integer>(); double minRatio = Double.MAX_VALUE; for (int i = tableau.getNumObjectiveFunctions(); i < tableau.getHeight(); i++) { final double rhs = tableau.getEntry(i, tableau.getWidth() - 1); final double entry = tableau.getEntry(i, col); if (Precision.compareTo(entry, 0d, maxUlps) > 0) { final double ratio = rhs / entry; // check if the entry is strictly equal to the current min ratio // do not use a ulp/epsilon check final int cmp = Double.compare(ratio, minRatio); if (cmp == 0) { minRatioPositions.add(i); } else if (cmp < 0) { minRatio = ratio; minRatioPositions = new ArrayList<Integer>(); minRatioPositions.add(i); } } } if (minRatioPositions.size() == 0) { return null; } else if (minRatioPositions.size() > 1) { // there's a degeneracy as indicated by a tie in the minimum ratio test // 1. check if there's an artificial variable that can be forced out of the basis if (tableau.getNumArtificialVariables() > 0) { for (Integer row : minRatioPositions) { for (int i = 0; i < tableau.getNumArtificialVariables(); i++) { int column = i + tableau.getArtificialVariableOffset(); final double entry = tableau.getEntry(row, column); if (Precision.equals(entry, 1d, maxUlps) && row.equals(tableau.getBasicRow(column))) { return row; } } } } // 2. apply Bland's rule to prevent cycling: // take the row for which the corresponding basic variable has the smallest index // // see http://www.stanford.edu/class/msande310/blandrule.pdf // see http://en.wikipedia.org/wiki/Bland%27s_rule (not equivalent to the above paper) // // Additional heuristic: if we did not get a solution after half of maxIterations // revert to the simple case of just returning the top-most row // This heuristic is based on empirical data gathered while investigating MATH-828. if (getIterations() < getMaxIterations() / 2) { Integer minRow = null; int minIndex = tableau.getWidth(); + final int varStart = tableau.getNumObjectiveFunctions(); + final int varEnd = tableau.getWidth() - 1; for (Integer row : minRatioPositions) { - int i = tableau.getNumObjectiveFunctions(); - for (; i < tableau.getWidth() - 1 && !row.equals(minRow); i++) { - Integer basicRow = tableau.getBasicRow(i); + for (int i = varStart; i < varEnd && !row.equals(minRow); i++) { + final Integer basicRow = tableau.getBasicRow(i); if (basicRow != null && basicRow.equals(row)) { if (i < minIndex) { minIndex = i; minRow = row; } } } } return minRow; } } return minRatioPositions.get(0); } /** * Runs one iteration of the Simplex method on the given model. * @param tableau simple tableau for the problem * @throws MaxCountExceededException if the maximal iteration count has been exceeded * @throws UnboundedSolutionException if the model is found not to have a bounded solution */ protected void doIteration(final SimplexTableau tableau) throws MaxCountExceededException, UnboundedSolutionException { incrementIterationsCounter(); Integer pivotCol = getPivotColumn(tableau); Integer pivotRow = getPivotRow(tableau, pivotCol); if (pivotRow == null) { throw new UnboundedSolutionException(); } // set the pivot element to 1 double pivotVal = tableau.getEntry(pivotRow, pivotCol); tableau.divideRow(pivotRow, pivotVal); // set the rest of the pivot column to 0 for (int i = 0; i < tableau.getHeight(); i++) { if (i != pivotRow) { final double multiplier = tableau.getEntry(i, pivotCol); tableau.subtractRow(i, pivotRow, multiplier); } } } /** * Solves Phase 1 of the Simplex method. * @param tableau simple tableau for the problem * @throws MaxCountExceededException if the maximal iteration count has been exceeded * @throws UnboundedSolutionException if the model is found not to have a bounded solution * @throws NoFeasibleSolutionException if there is no feasible solution */ protected void solvePhase1(final SimplexTableau tableau) throws MaxCountExceededException, UnboundedSolutionException, NoFeasibleSolutionException { // make sure we're in Phase 1 if (tableau.getNumArtificialVariables() == 0) { return; } while (!tableau.isOptimal()) { doIteration(tableau); } // if W is not zero then we have no feasible solution if (!Precision.equals(tableau.getEntry(0, tableau.getRhsOffset()), 0d, epsilon)) { throw new NoFeasibleSolutionException(); } } /** {@inheritDoc} */ @Override public PointValuePair doOptimize() throws MaxCountExceededException, UnboundedSolutionException, NoFeasibleSolutionException { final SimplexTableau tableau = new SimplexTableau(getFunction(), getConstraints(), getGoalType(), restrictToNonNegative(), epsilon, maxUlps); solvePhase1(tableau); tableau.dropPhase1Objective(); while (!tableau.isOptimal()) { doIteration(tableau); } return tableau.getSolution(); } }
false
true
private Integer getPivotRow(SimplexTableau tableau, final int col) { // create a list of all the rows that tie for the lowest score in the minimum ratio test List<Integer> minRatioPositions = new ArrayList<Integer>(); double minRatio = Double.MAX_VALUE; for (int i = tableau.getNumObjectiveFunctions(); i < tableau.getHeight(); i++) { final double rhs = tableau.getEntry(i, tableau.getWidth() - 1); final double entry = tableau.getEntry(i, col); if (Precision.compareTo(entry, 0d, maxUlps) > 0) { final double ratio = rhs / entry; // check if the entry is strictly equal to the current min ratio // do not use a ulp/epsilon check final int cmp = Double.compare(ratio, minRatio); if (cmp == 0) { minRatioPositions.add(i); } else if (cmp < 0) { minRatio = ratio; minRatioPositions = new ArrayList<Integer>(); minRatioPositions.add(i); } } } if (minRatioPositions.size() == 0) { return null; } else if (minRatioPositions.size() > 1) { // there's a degeneracy as indicated by a tie in the minimum ratio test // 1. check if there's an artificial variable that can be forced out of the basis if (tableau.getNumArtificialVariables() > 0) { for (Integer row : minRatioPositions) { for (int i = 0; i < tableau.getNumArtificialVariables(); i++) { int column = i + tableau.getArtificialVariableOffset(); final double entry = tableau.getEntry(row, column); if (Precision.equals(entry, 1d, maxUlps) && row.equals(tableau.getBasicRow(column))) { return row; } } } } // 2. apply Bland's rule to prevent cycling: // take the row for which the corresponding basic variable has the smallest index // // see http://www.stanford.edu/class/msande310/blandrule.pdf // see http://en.wikipedia.org/wiki/Bland%27s_rule (not equivalent to the above paper) // // Additional heuristic: if we did not get a solution after half of maxIterations // revert to the simple case of just returning the top-most row // This heuristic is based on empirical data gathered while investigating MATH-828. if (getIterations() < getMaxIterations() / 2) { Integer minRow = null; int minIndex = tableau.getWidth(); for (Integer row : minRatioPositions) { int i = tableau.getNumObjectiveFunctions(); for (; i < tableau.getWidth() - 1 && !row.equals(minRow); i++) { Integer basicRow = tableau.getBasicRow(i); if (basicRow != null && basicRow.equals(row)) { if (i < minIndex) { minIndex = i; minRow = row; } } } } return minRow; } } return minRatioPositions.get(0); }
private Integer getPivotRow(SimplexTableau tableau, final int col) { // create a list of all the rows that tie for the lowest score in the minimum ratio test List<Integer> minRatioPositions = new ArrayList<Integer>(); double minRatio = Double.MAX_VALUE; for (int i = tableau.getNumObjectiveFunctions(); i < tableau.getHeight(); i++) { final double rhs = tableau.getEntry(i, tableau.getWidth() - 1); final double entry = tableau.getEntry(i, col); if (Precision.compareTo(entry, 0d, maxUlps) > 0) { final double ratio = rhs / entry; // check if the entry is strictly equal to the current min ratio // do not use a ulp/epsilon check final int cmp = Double.compare(ratio, minRatio); if (cmp == 0) { minRatioPositions.add(i); } else if (cmp < 0) { minRatio = ratio; minRatioPositions = new ArrayList<Integer>(); minRatioPositions.add(i); } } } if (minRatioPositions.size() == 0) { return null; } else if (minRatioPositions.size() > 1) { // there's a degeneracy as indicated by a tie in the minimum ratio test // 1. check if there's an artificial variable that can be forced out of the basis if (tableau.getNumArtificialVariables() > 0) { for (Integer row : minRatioPositions) { for (int i = 0; i < tableau.getNumArtificialVariables(); i++) { int column = i + tableau.getArtificialVariableOffset(); final double entry = tableau.getEntry(row, column); if (Precision.equals(entry, 1d, maxUlps) && row.equals(tableau.getBasicRow(column))) { return row; } } } } // 2. apply Bland's rule to prevent cycling: // take the row for which the corresponding basic variable has the smallest index // // see http://www.stanford.edu/class/msande310/blandrule.pdf // see http://en.wikipedia.org/wiki/Bland%27s_rule (not equivalent to the above paper) // // Additional heuristic: if we did not get a solution after half of maxIterations // revert to the simple case of just returning the top-most row // This heuristic is based on empirical data gathered while investigating MATH-828. if (getIterations() < getMaxIterations() / 2) { Integer minRow = null; int minIndex = tableau.getWidth(); final int varStart = tableau.getNumObjectiveFunctions(); final int varEnd = tableau.getWidth() - 1; for (Integer row : minRatioPositions) { for (int i = varStart; i < varEnd && !row.equals(minRow); i++) { final Integer basicRow = tableau.getBasicRow(i); if (basicRow != null && basicRow.equals(row)) { if (i < minIndex) { minIndex = i; minRow = row; } } } } return minRow; } } return minRatioPositions.get(0); }
diff --git a/src/model/ConcreteProductContainerManager.java b/src/model/ConcreteProductContainerManager.java index d165e6a..5cc6c35 100644 --- a/src/model/ConcreteProductContainerManager.java +++ b/src/model/ConcreteProductContainerManager.java @@ -1,171 +1,171 @@ package model; import java.io.Serializable; import java.util.Iterator; import java.util.Map; import java.util.Observable; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import model.Action.ActionType; @SuppressWarnings("serial") public class ConcreteProductContainerManager extends Observable implements Serializable, ProductContainerManager { private final Set<StorageUnit> rootStorageUnits; private final Map<String, StorageUnit> nameToStorageUnit; /** * Constructor * */ public ConcreteProductContainerManager() { rootStorageUnits = new TreeSet<StorageUnit>(); nameToStorageUnit = new TreeMap<String, StorageUnit>(); } @Override public void editProductGroup(ProductContainer parent, String oldName, String newName, ProductQuantity newTMS) { ProductGroup pg = parent.editProductGroup(oldName, newName, newTMS); setChanged(); Action a = new Action(pg, ActionType.EDIT); this.notifyObservers(a); } @Override public StorageUnit getRootStorageUnitByName(String productGroupName) { for (StorageUnit su : rootStorageUnits) { if (su.getName().equals(productGroupName) || su.containsProductGroup(productGroupName)) return su; } return null; } @Override public StorageUnit getRootStorageUnitForChild(ProductContainer child) { for (StorageUnit su : rootStorageUnits) { if (su.equals(child) || su.hasDescendantProductContainer(child)) return su; } return null; } /** * Gets the StorageUnit with the given name. * * @return The StorageUnit with the given name, or null, if not found * * @pre true * @post true */ @Override public StorageUnit getStorageUnitByName(String name) { return nameToStorageUnit.get(name); } @Override public Iterator<StorageUnit> getStorageUnitIterator() { return rootStorageUnits.iterator(); } /** * Determines whether the specified Storage Unit name is valid for adding a new Storage * Unit. * * @param name * The name to be tested * @return true if name is valid, false otherwise * * @pre true * @post true */ @Override public boolean isValidStorageUnitName(String name) { if (name == null || name.equals("")) return false; // From the Data Dictionary: Must be non-empty. Must be unique among all // Storage Units. for (StorageUnit su : rootStorageUnits) { if (name.equals(su.getName().toString())) return false; } return true; } /** * If pc is a StorageUnit, it is added to the list of StorageUnits managed. Notifies * observers of a change. * * @param pc * ProductContainer to be managed * * @pre pc != null * @post if(pc instanceof StorageUnit) getByName(pc.getName()) == pc */ @Override public void manage(ProductContainer pc) { if (pc instanceof StorageUnit) { StorageUnit storageUnit = (StorageUnit) pc; rootStorageUnits.add(storageUnit); nameToStorageUnit.put(storageUnit.getName(), storageUnit); } setChanged(); Action a = new Action(pc, ActionType.CREATE); this.notifyObservers(a); } /** * * @param name * @param su */ @Override public void setStorageUnitName(String name, StorageUnit su) { if (name.equals(su.getName())) return; if (!isValidStorageUnitName(name)) throw new IllegalArgumentException("Illegal storage unit name"); rootStorageUnits.remove(su); nameToStorageUnit.remove(su.getName()); su.setName(name); rootStorageUnits.add(su); nameToStorageUnit.put(name, su); setChanged(); Action a = new Action(su, ActionType.EDIT); this.notifyObservers(a); } /** * Remove pc from set of managed objects and notify observers of a change. * * @param pc * ProductContainer to be unmanaged * * @pre true * @post getByName(pc.getName()) == null */ @Override public void unmanage(ProductContainer pc) { if (pc instanceof StorageUnit) { StorageUnit storageUnit = (StorageUnit) pc; rootStorageUnits.remove(storageUnit); nameToStorageUnit.remove(storageUnit.getName()); } else { ProductGroup pg = (ProductGroup) pc; for (StorageUnit su : rootStorageUnits) { - if (su.containsProductGroup(pg.getName())) { + if (su.containsProductGroup(pg) || su.hasDescendantProductContainer(pg)) { su.remove(pg); } } } setChanged(); Action a = new Action(pc, ActionType.DELETE); this.notifyObservers(a); } }
true
true
public void unmanage(ProductContainer pc) { if (pc instanceof StorageUnit) { StorageUnit storageUnit = (StorageUnit) pc; rootStorageUnits.remove(storageUnit); nameToStorageUnit.remove(storageUnit.getName()); } else { ProductGroup pg = (ProductGroup) pc; for (StorageUnit su : rootStorageUnits) { if (su.containsProductGroup(pg.getName())) { su.remove(pg); } } } setChanged(); Action a = new Action(pc, ActionType.DELETE); this.notifyObservers(a); }
public void unmanage(ProductContainer pc) { if (pc instanceof StorageUnit) { StorageUnit storageUnit = (StorageUnit) pc; rootStorageUnits.remove(storageUnit); nameToStorageUnit.remove(storageUnit.getName()); } else { ProductGroup pg = (ProductGroup) pc; for (StorageUnit su : rootStorageUnits) { if (su.containsProductGroup(pg) || su.hasDescendantProductContainer(pg)) { su.remove(pg); } } } setChanged(); Action a = new Action(pc, ActionType.DELETE); this.notifyObservers(a); }
diff --git a/aQute.libg/src/aQute/libg/command/Command.java b/aQute.libg/src/aQute/libg/command/Command.java index 7e9a58bd6..1a1eb750a 100644 --- a/aQute.libg/src/aQute/libg/command/Command.java +++ b/aQute.libg/src/aQute/libg/command/Command.java @@ -1,194 +1,193 @@ package aQute.libg.command; import java.io.*; import java.util.*; import java.util.concurrent.*; import aQute.libg.reporter.*; public class Command { boolean trace; Reporter reporter; List<String> arguments = new ArrayList<String>(); long timeout = 0; - File cwd = new File("").getAbsoluteFile().getParentFile() - .getAbsoluteFile(); + File cwd = new File("").getAbsoluteFile(); static Timer timer = new Timer(); Process process; volatile boolean timedout; public int execute(Appendable stdout, Appendable stderr) throws Exception { return execute((InputStream) null, stdout, stderr); } public int execute(String input, Appendable stdout, Appendable stderr) throws Exception { InputStream in = new ByteArrayInputStream(input.getBytes("UTF-8")); return execute(in, stdout, stderr); } public int execute(InputStream in, Appendable stdout, Appendable stderr) throws Exception { int result; if (reporter != null) { reporter.trace("executing cmd: %s", arguments); } String args[] = arguments.toArray(new String[arguments.size()]); process = Runtime.getRuntime().exec(args, null, cwd); // Make sure the command will not linger when we go Runnable r = new Runnable() { public void run() { process.destroy(); } }; Thread hook = new Thread(r, arguments.toString()); Runtime.getRuntime().addShutdownHook(hook); TimerTask timer = null; OutputStream stdin = process.getOutputStream(); final InputStreamHandler handler = in != null ? new InputStreamHandler(in, stdin) : null; if (timeout != 0) { timer = new TimerTask() { public void run() { timedout = true; process.destroy(); if (handler != null) handler.interrupt(); } }; Command.timer.schedule(timer, timeout); } InputStream out = process.getInputStream(); try { InputStream err = process.getErrorStream(); try { new Collector(out, stdout).start(); new Collector(err, stdout).start(); if (handler != null) handler.start(); result = process.waitFor(); } finally { err.close(); } } finally { out.close(); if (timer != null) timer.cancel(); Runtime.getRuntime().removeShutdownHook(hook); if (handler != null) handler.interrupt(); } if (reporter != null) reporter.trace("cmd %s executed with result=%d, result: %s/%s", arguments, result, stdout, stderr); if( timedout ) return Integer.MIN_VALUE; byte exitValue = (byte) process.exitValue(); return exitValue; } public void add(String... args) { for (String arg : args) arguments.add(arg); } public void addAll(Collection<String> args) { arguments.addAll(args); } public void setTimeout(long duration, TimeUnit unit) { timeout = unit.toMillis(duration); } public void setTrace() { this.trace = true; } public void setReporter(Reporter reporter) { this.reporter = reporter; } public void setCwd(File dir) { if (!dir.isDirectory()) throw new IllegalArgumentException("Working directory must be a directory: " + dir); this.cwd = dir; } public void cancel() { process.destroy(); } class Collector extends Thread { final InputStream in; final Appendable sb; public Collector(InputStream inputStream, Appendable sb) { this.in = inputStream; this.sb = sb; } public void run() { try { int c = in.read(); while (c >= 0) { if (trace) System.out.print((char) c); sb.append((char) c); c = in.read(); } } catch (Exception e) { try { sb.append("\n**************************************\n"); sb.append(e.toString()); sb.append("\n**************************************\n"); } catch (IOException e1) { } if (reporter != null) { reporter.trace("cmd exec: %s", e); } } } } class InputStreamHandler extends Thread { final InputStream in; final OutputStream stdin; public InputStreamHandler(InputStream in, OutputStream stdin) { this.stdin = stdin; this.in = in; } public void run() { try { int c = in.read(); while (c >= 0) { stdin.write(c); c = in.read(); } } catch (InterruptedIOException e) { // Ignore here } catch (Exception e) { // Who cares? } } } public String toString() { StringBuilder sb = new StringBuilder(); String del = ""; for (String argument : arguments) { sb.append(del); sb.append(argument); del = " "; } return sb.toString(); } } diff --git a/biz.aQute.bnd/src/aQute/bnd/main/bnd.java b/biz.aQute.bnd/src/aQute/bnd/main/bnd.java index 6be57cda9..9707dff76 100755 --- a/biz.aQute.bnd/src/aQute/bnd/main/bnd.java +++ b/biz.aQute.bnd/src/aQute/bnd/main/bnd.java @@ -1,2098 +1,2098 @@ package aQute.bnd.main; import java.io.*; import java.net.*; import java.util.*; import java.util.jar.*; import java.util.prefs.*; import java.util.regex.*; import java.util.zip.*; import javax.xml.parsers.*; import javax.xml.transform.*; import javax.xml.transform.dom.*; import javax.xml.transform.stream.*; import javax.xml.xpath.*; import org.w3c.dom.*; import aQute.bnd.build.*; import aQute.bnd.libsync.*; import aQute.bnd.maven.*; import aQute.bnd.service.*; import aQute.bnd.service.action.*; import aQute.bnd.settings.*; import aQute.lib.deployer.*; import aQute.lib.jardiff.*; import aQute.lib.osgi.*; import aQute.lib.osgi.eclipse.*; import aQute.lib.tag.*; import aQute.libg.generics.*; import aQute.libg.version.*; /** * Utility to make bundles. * * TODO Add Javadoc comment for this type. * * @version $Revision: 1.14 $ */ public class bnd extends Processor { Settings settings = new Settings(); PrintStream out = System.out; static boolean exceptions = false; static boolean failok = false; private Project project; public static void main(String args[]) { bnd main = new bnd(); try { main.run(args); if (bnd.failok) return; System.exit(main.getErrors().size()); } catch (Exception e) { System.err.println("Software error occurred " + e); if (exceptions) e.printStackTrace(); } System.exit(-1); } void run(String[] args) throws Exception { int i = 0; try { for (; i < args.length; i++) { if ("-failok".equals(args[i])) { failok = true; } else if ("-exceptions".equals(args[i])) { exceptions = true; } else if ("-trace".equals(args[i])) { setTrace(true); } else if ("-pedantic".equals(args[i])) { setPedantic(true); } else if (args[i].indexOf('=') > 0) { String parts[] = args[i].split("\\s*(?!\\\\)=\\s*"); if (parts.length == 2) setProperty(parts[0], parts[1]); else error("invalid property def: %s", args[i]); } else if ("-base".equals(args[i])) { setBase(new File(args[++i]).getAbsoluteFile()); if (!getBase().isDirectory()) { out.println("-base must be a valid directory"); } else if (args[i].startsWith("-")) error("Invalid option: ", args[i]); } else break; } project = getProject(); if (project != null) { setParent(project); project.setPedantic(isPedantic()); project.setTrace(isTrace()); } trace("project = %s", project); if (i >= args.length) { if (project != null && project.isValid()) { trace("default build of current project"); project.build(); } else doHelp(); } else { if (!doProject(project, args, i)) { if (!doCommand(args, i)) { doFiles(args, i); } } } } catch (Throwable t) { if (exceptions) t.printStackTrace(); error("exception %s", t, t); } int n = 1; switch (getErrors().size()) { case 0: // System.err.println("No errors"); break; case 1: System.err.println("One error"); break; default: System.err.println(getErrors().size() + " errors"); } for (String msg : getErrors()) { System.err.println(n++ + " : " + msg); } n = 1; switch (getWarnings().size()) { case 0: // System.err.println("No warnings"); break; case 1: System.err.println("One warning"); break; default: System.err.println(getWarnings().size() + " warnings"); } for (String msg : getWarnings()) { System.err.println(n++ + " : " + msg); } } boolean doProject(Project project, String[] args, int i) throws Exception { if (project != null) { trace("project command %s", args[i]); Action a = project.getActions().get(args[i]); if (a != null) { a.execute(project, args[i++]); getInfo(project); return true; } } return false; } boolean doCommand(String args[], int i) throws Exception { trace("command %s", args[i]); if ("wrap".equals(args[i])) { doWrap(args, ++i); } else if ("maven".equals(args[i])) { MavenCommand maven = new MavenCommand(); maven.run(args, ++i); getInfo(maven); } else if ("global".equals(args[i])) { global(args, ++i); } else if ("print".equals(args[i])) { doPrint(args, ++i); } else if ("graph".equals(args[i])) { doDot(args, ++i); } else if ("create-repo".equals(args[i])) { createRepo(args, ++i); } else if ("release".equals(args[i])) { doRelease(args, ++i); } else if ("debug".equals(args[i])) { debug(args, ++i); } else if ("libsync".equals(args[i])) { doLibsync(args, ++i); } else if ("bump".equals(args[i])) { bump(args, ++i); } else if ("deliverables".equals(args[i])) { deliverables(args, ++i); } else if ("view".equals(args[i])) { doView(args, ++i); } else if ("buildx".equals(args[i])) { doBuild(args, ++i); } else if ("extract".equals(args[i])) { doExtract(args, ++i); } else if ("patch".equals(args[i])) { patch(args, ++i); } else if ("runtests".equals(args[i])) { runtests(args, ++i); } else if ("xref".equals(args[i])) { doXref(args, ++i); } else if ("eclipse".equals(args[i])) { doEclipse(args, ++i); } else if ("repo".equals(args[i])) { repo(args, ++i); } else if ("diff".equals(args[i])) { doDiff(args, ++i); } else if ("help".equals(args[i])) { doHelp(args, ++i); } else if ("macro".equals(args[i])) { doMacro(args, ++i); } else return false; return true; } boolean doFiles(String args[], int i) throws Exception { while (i < args.length) { String path = args[i]; if (path.endsWith(Constants.DEFAULT_BND_EXTENSION)) doBuild(getFile(path), new File[0], new File[0], null, "", new File(path) .getParentFile(), 0, new HashSet<File>()); else if (path.endsWith(Constants.DEFAULT_JAR_EXTENSION) || path.endsWith(Constants.DEFAULT_BAR_EXTENSION)) doPrint(path, -1); else error("Unknown file %s", path); i++; } return true; } private void bump(String[] args, int i) throws Exception { if (getProject() == null) { error("No project found, use -base <dir> bump"); return; } String mask = null; if (args.length > i) { mask = args[i]; if (mask.equalsIgnoreCase("major")) mask = "+00"; else if (mask.equalsIgnoreCase("minor")) mask = "=+0"; else if (mask.equalsIgnoreCase("micro")) mask = "==+"; else if (!mask.matches("(+=0){1,3}")) { error( "Invalid mask for version bump %s, is (minor|major|micro|<mask>), see $version for mask", mask); return; } } if (mask == null) getProject().bump(); else getProject().bump(mask); out.println(getProject().getProperty(BUNDLE_VERSION, "No version found")); } /** * Take the current project, calculate its dependencies from the repo and * create a mini-repo from it that can easily be unzipped. * * @param args * @param i * @throws Exception */ private void createRepo(String[] args, int i) throws Exception { Project project = getProject(); if (project == null) { error("not in a proper bnd project ... " + getBase()); return; } File out = getFile(project.getName() + ".repo.jar"); List<Instruction> skip = Create.list(); while (i < args.length) { if (args[i].equals("-o")) { i++; if (i < args.length) out = getFile(args[i]); else error("No arg for -out"); } else if (args[i].equals("-skip")) { i++; if (i < args.length) { Instruction instr = Instruction.getPattern(args[i]); skip.add(instr); } else error("No arg for -skip"); } else error("invalid arg for create-repo %s", args[i]); i++; } Jar output = new Jar(project.getName()); output.setDoNotTouchManifest(); addClose(output); getInfo(project); if (isOk()) { for (Container c : project.getBuildpath()) { addContainer(skip, output, c); } for (Container c : project.getRunbundles()) { addContainer(skip, output, c); } if (isOk()) { try { output.write(out); } catch (Exception e) { error("Could not write mini repo %s", e); } } } } private void addContainer(Collection<Instruction> skip, Jar output, Container c) throws Exception { trace("add container " + c); String prefix = "cnf/repo/"; switch (c.getType()) { case ERROR: error("Dependencies include %s", c.getError()); return; case REPO: case EXTERNAL: { String name = getName(skip, prefix, c, ".jar"); if (name != null) output.putResource(name, new FileResource(c.getFile())); trace("storing %s in %s", c, name); break; } case PROJECT: trace("not storing project " + c); break; case LIBRARY: { String name = getName(skip, prefix, c, ".lib"); if (name != null) { output.putResource(name, new FileResource(c.getFile())); trace("store library %s", name); for (Container child : c.getMembers()) { trace("store member %s", child); addContainer(skip, output, child); } } } } } String getName(Collection<Instruction> skip, String prefix, Container c, String extension) throws Exception { Manifest m = c.getManifest(); try { if (m == null) { error("No manifest found for %s", c); return null; } String bsn = m.getMainAttributes().getValue(BUNDLE_SYMBOLICNAME); if (bsn == null) { error("No bsn in manifest: %s", c); return null; } for (Instruction instr : skip) { if (instr.matches(bsn)) { if (instr.isNegated()) // - * - = +! break; else return null; // skip it } } int n = bsn.indexOf(';'); if (n > 0) { bsn = bsn.substring(0, n).trim(); } String version = m.getMainAttributes().getValue(BUNDLE_VERSION); if (version == null) version = "0"; Version v = new Version(version); version = v.getMajor() + "." + v.getMinor() + "." + v.getMicro(); if (c.getFile() != null && c.getFile().getName().endsWith("-latest.jar")) version = "latest"; return prefix + bsn + "/" + bsn + "-" + version + extension; } catch (Exception e) { error("Could not store repo file %s", c); } return null; } private void deliverables(String[] args, int i) throws Exception { Project project = getProject(); long start = System.currentTimeMillis(); Collection<Project> projects = project.getWorkspace().getAllProjects(); List<Container> containers = new ArrayList<Container>(); for (Project p : projects) { containers.addAll(p.getDeliverables()); } long duration = System.currentTimeMillis() - start; System.out.println("Took " + duration + " ms"); for (Container c : containers) { Version v = new Version(c.getVersion()); System.out.printf("%-40s %d.%d.%d %s\n", c.getBundleSymbolicName(), v.getMajor(), v .getMinor(), v.getMicro(), c.getFile()); } } private int doMacro(String[] args, int i) throws Exception { String result; for (; i < args.length; i++) { String cmd = args[i]; cmd = cmd.replaceAll("@\\{([^}])\\}", "\\${$1}"); cmd = cmd.replaceAll(":", ";"); cmd = cmd.replaceAll("[^$](.*)", "\\${$0}"); result = getReplacer().process(cmd); if (result != null && result.length() != 0) { Collection<String> parts = split(result); for (String s : parts) { out.println(s); } } else out.println("No result for " + cmd); } return i; } private void doRelease(String[] args, int i) throws Exception { Project project = getProject(); project.release(false); getInfo(project); } /** * Cross reference every class in the jar file to the files it references * * @param args * @param i */ private void doXref(String[] args, int i) { for (; i < args.length; i++) { try { File file = new File(args[i]); Jar jar = new Jar(file.getName(), file); try { for (Map.Entry<String, Resource> entry : jar.getResources().entrySet()) { String key = entry.getKey(); Resource r = entry.getValue(); if (key.endsWith(".class")) { InputStream in = r.openInputStream(); Clazz clazz = new Clazz(key, r); out.print(key); Set<String> xref = clazz.parseClassFile(); in.close(); for (String element : xref) { out.print("\t"); out.print(element); } out.println(); } } } finally { jar.close(); } } catch (Exception e) { e.printStackTrace(); } } } private void doEclipse(String[] args, int i) throws Exception { File dir = new File("").getAbsoluteFile(); if (args.length == i) doEclipse(dir); else { for (; i < args.length; i++) { doEclipse(new File(dir, args[i])); } } } private void doEclipse(File file) throws Exception { if (!file.isDirectory()) error("Eclipse requires a path to a directory: " + file.getAbsolutePath()); else { File cp = new File(file, ".classpath"); if (!cp.exists()) { error("Cannot find .classpath in project directory: " + file.getAbsolutePath()); } else { EclipseClasspath eclipse = new EclipseClasspath(this, file.getParentFile(), file); out.println("Classpath " + eclipse.getClasspath()); out.println("Dependents " + eclipse.getDependents()); out.println("Sourcepath " + eclipse.getSourcepath()); out.println("Output " + eclipse.getOutput()); out.println(); } } } final static int BUILD_SOURCES = 1; final static int BUILD_POM = 2; final static int BUILD_FORCE = 4; private void doBuild(String[] args, int i) throws Exception { File classpath[] = new File[0]; File workspace = null; File sourcepath[] = new File[0]; File output = null; String eclipse = ""; int options = 0; for (; i < args.length; i++) { if ("-workspace".startsWith(args[i])) { workspace = new File(args[++i]); } else if ("-classpath".startsWith(args[i])) { classpath = getClasspath(args[++i]); } else if ("-sourcepath".startsWith(args[i])) { String arg = args[++i]; String spaces[] = arg.split("\\s*,\\s*"); sourcepath = new File[spaces.length]; for (int j = 0; j < spaces.length; j++) { File f = new File(spaces[j]); if (!f.exists()) error("No such sourcepath entry: " + f.getAbsolutePath()); sourcepath[j] = f; } } else if ("-eclipse".startsWith(args[i])) { eclipse = args[++i]; } else if ("-noeclipse".startsWith(args[i])) { eclipse = null; } else if ("-output".startsWith(args[i])) { output = new File(args[++i]); } else if ("-sources".startsWith(args[i])) { options |= BUILD_SOURCES; } else if ("-pom".startsWith(args[i])) { options |= BUILD_POM; } else if ("-force".startsWith(args[i])) { options |= BUILD_FORCE; } else { if (args[i].startsWith("-")) error("Invalid option for bnd: " + args[i]); else { File properties = new File(args[i]); if (!properties.exists()) error("Cannot find bnd file: " + args[i]); else { if (workspace == null) workspace = properties.getParentFile(); doBuild(properties, classpath, sourcepath, output, eclipse, workspace, options, new HashSet<File>()); } output = null; } } } } private File[] getClasspath(String string) { String spaces[] = string.split("\\s*,\\s*"); File classpath[] = new File[spaces.length]; for (int j = 0; j < spaces.length; j++) { File f = new File(spaces[j]); if (!f.exists()) error("No such classpath entry: " + f.getAbsolutePath()); classpath[j] = f; } return classpath; } private void doBuild(File properties, File classpath[], File sourcepath[], File output, String eclipse, File workspace, int options, Set<File> building) throws Exception { properties = properties.getAbsoluteFile(); if (building.contains(properties)) { error("Circular dependency in pre build " + properties); return; } building.add(properties); Builder builder = new Builder(); try { builder.setPedantic(isPedantic()); builder.setProperties(properties); if (output == null) { String out = builder.getProperty("-output"); if (out != null) { output = getFile(properties.getParentFile(), out); if (!output.getName().endsWith(".jar")) output.mkdirs(); } else output = properties.getAbsoluteFile().getParentFile(); } String prebuild = builder.getProperty("-prebuild"); if (prebuild != null) prebuild(prebuild, properties.getParentFile(), classpath, sourcepath, output, eclipse, workspace, options, building); doEclipse(builder, properties, classpath, sourcepath, eclipse, workspace); if ((options & BUILD_SOURCES) != 0) builder.getProperties().setProperty("-sources", "true"); if (failok) builder.setProperty(Analyzer.FAIL_OK, "true"); Jar jar = builder.build(); getInfo(builder); if (getErrors().size() > 0 && !failok) return; String name = builder.getBsn() + DEFAULT_JAR_EXTENSION; if (output.isDirectory()) output = new File(output, name); output.getParentFile().mkdirs(); if ((options & BUILD_POM) != 0) { Resource r = new Pom(jar.getManifest()); jar.putResource("pom.xml", r); String path = output.getName().replaceAll("\\.jar$", ".pom"); if (path.equals(output.getName())) path = output.getName() + ".pom"; File pom = new File(output.getParentFile(), path); OutputStream out = new FileOutputStream(pom); try { r.write(out); } finally { out.close(); } } jar.setName(output.getName()); String msg = ""; if (!output.exists() || output.lastModified() <= jar.lastModified() || (options & BUILD_FORCE) != 0) { jar.write(output); } else { msg = "(not modified)"; } statistics(jar, output, msg); } finally { builder.close(); } } private void prebuild(String prebuild, File base, File[] classpath, File[] sourcepath, File output, String eclipse2, File workspace, int options, Set<File> building) throws Exception { // Force the output a directory if (output.isFile()) output = output.getParentFile(); Collection<String> parts = Processor.split(prebuild); for (String part : parts) { File f = new File(part); if (!f.exists()) f = new File(base, part); if (!f.exists()) { error("Trying to build a non-existent file: " + parts); continue; } try { doBuild(f, classpath, sourcepath, output, eclipse2, workspace, options, building); } catch (Exception e) { error("Trying to build: " + part + " " + e); } } } private void statistics(Jar jar, File output, String msg) { out.println(jar.getName() + " " + jar.getResources().size() + " " + output.length() + msg); } /** * @param properties * @param classpath * @param eclipse * @return * @throws IOException */ void doEclipse(Builder builder, File properties, File[] classpath, File sourcepath[], String eclipse, File workspace) throws IOException { if (eclipse != null) { File project = new File(workspace, eclipse).getAbsoluteFile(); if (project.exists() && project.isDirectory()) { try { EclipseClasspath path = new EclipseClasspath(this, project.getParentFile(), project); List<File> newClasspath = Create.copy(Arrays.asList(classpath)); newClasspath.addAll(path.getClasspath()); classpath = (File[]) newClasspath.toArray(classpath); List<File> newSourcepath = Create.copy(Arrays.asList(sourcepath)); newSourcepath.addAll(path.getSourcepath()); sourcepath = (File[]) newSourcepath.toArray(sourcepath); } catch (Exception e) { if (eclipse.length() > 0) error("Eclipse specified (" + eclipse + ") but getting error processing: " + e); } } else { if (eclipse.length() > 0) error("Eclipse specified (" + eclipse + ") but no project directory found"); } } builder.setClasspath(classpath); builder.setSourcepath(sourcepath); } private void doHelp() { doHelp(new String[0], 0); } private void doHelp(String[] args, int i) { if (args.length <= i) { out .println("bnd -failok? -exceptions? ( wrap | print | build | eclipse | xref | view )?"); out.println("See http://www.aQute.biz/Code/Bnd"); } else { while (args.length > i) { if ("wrap".equals(args[i])) { out.println("bnd wrap (-output <file|dir>)? (-properties <file>)? <jar-file>"); } else if ("print".equals(args[i])) { out.println("bnd wrap -verify? -manifest? -list? -eclipse <jar-file>"); } else if ("build".equals(args[i])) { out .println("bnd build (-output <file|dir>)? (-classpath <list>)? (-sourcepath <list>)? "); out.println(" -eclipse? -noeclipse? -sources? <bnd-file>"); } else if ("eclipse".equals(args[i])) { out.println("bnd eclipse"); } else if ("view".equals(args[i])) { out.println("bnd view <file> <resource-names>+"); } i++; } } } final static int VERIFY = 1; final static int MANIFEST = 2; final static int LIST = 4; final static int ECLIPSE = 8; final static int IMPEXP = 16; final static int USES = 32; final static int USEDBY = 64; final static int COMPONENT = 128; static final int HEX = 0; private void doPrint(String[] args, int i) throws Exception { int options = 0; for (; i < args.length; i++) { if ("-verify".startsWith(args[i])) options |= VERIFY; else if ("-manifest".startsWith(args[i])) options |= MANIFEST; else if ("-list".startsWith(args[i])) options |= LIST; else if ("-eclipse".startsWith(args[i])) options |= ECLIPSE; else if ("-impexp".startsWith(args[i])) options |= IMPEXP; else if ("-uses".startsWith(args[i])) options |= USES; else if ("-usedby".startsWith(args[i])) options |= USEDBY; else if ("-component".startsWith(args[i])) options |= COMPONENT; else if ("-all".startsWith(args[i])) options = -1; else { if (args[i].startsWith("-")) error("Invalid option for print: " + args[i]); else doPrint(args[i], options); } } } public void doPrint(String string, int options) throws Exception { File file = new File(string); if (!file.exists()) error("File to print not found: " + string); else { if (options == 0) options = VERIFY | MANIFEST | IMPEXP | USES; doPrint(file, options); } } private void doPrint(File file, int options) throws ZipException, IOException, Exception { Jar jar = new Jar(file.getName(), file); try { if ((options & VERIFY) != 0) { Verifier verifier = new Verifier(jar); verifier.setPedantic(isPedantic()); verifier.verify(); getInfo(verifier); } if ((options & MANIFEST) != 0) { Manifest manifest = jar.getManifest(); if (manifest == null) warning("JAR has no manifest " + file); else { out.println("[MANIFEST " + jar.getName() + "]"); SortedSet<String> sorted = new TreeSet<String>(); for (Object element : manifest.getMainAttributes().keySet()) { sorted.add(element.toString()); } for (String key : sorted) { Object value = manifest.getMainAttributes().getValue(key); format("%-40s %-40s\r\n", new Object[] { key, value }); } } out.println(); } if ((options & IMPEXP) != 0) { out.println("[IMPEXP]"); Manifest m = jar.getManifest(); if (m != null) { Map<String, Map<String, String>> imports = parseHeader(m.getMainAttributes() .getValue(Analyzer.IMPORT_PACKAGE)); Map<String, Map<String, String>> exports = parseHeader(m.getMainAttributes() .getValue(Analyzer.EXPORT_PACKAGE)); for (String p : exports.keySet()) { if (imports.containsKey(p)) { Map<String, String> attrs = imports.get(p); if (attrs.containsKey(Constants.VERSION_ATTRIBUTE)) { exports.get(p).put("imported-as", attrs.get(VERSION_ATTRIBUTE)); } } } print("Import-Package", new TreeMap<String, Map<String, String>>(imports)); print("Export-Package", new TreeMap<String, Map<String, String>>(exports)); } else warning("File has no manifest"); } if ((options & (USES | USEDBY)) != 0) { out.println(); Analyzer analyzer = new Analyzer(); analyzer.setPedantic(isPedantic()); analyzer.setJar(jar); analyzer.analyze(); if ((options & USES) != 0) { out.println("[USES]"); printMapOfSets(new TreeMap<String, Set<String>>(analyzer.getUses())); out.println(); } if ((options & USEDBY) != 0) { out.println("[USEDBY]"); printMapOfSets(invertMapOfCollection(analyzer.getUses())); } } if ((options & COMPONENT) != 0) { printComponents(out, jar); } if ((options & LIST) != 0) { out.println("[LIST]"); for (Map.Entry<String, Map<String, Resource>> entry : jar.getDirectories() .entrySet()) { String name = entry.getKey(); Map<String, Resource> contents = entry.getValue(); out.println(name); if (contents != null) { for (String element : contents.keySet()) { int n = element.lastIndexOf('/'); if (n > 0) element = element.substring(n + 1); out.print(" "); out.print(element); String path = element; if (name.length() != 0) path = name + "/" + element; Resource r = contents.get(path); if (r != null) { String extra = r.getExtra(); if (extra != null) { out.print(" extra='" + escapeUnicode(extra) + "'"); } } out.println(); } } else { out.println(name + " <no contents>"); } } out.println(); } } finally { jar.close(); } } private final char nibble(int i) { return "0123456789ABCDEF".charAt(i & 0xF); } private final String escapeUnicode(String s) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c >= ' ' && c <= '~' && c != '\\') sb.append(c); else { sb.append("\\u"); sb.append(nibble(c >> 12)); sb.append(nibble(c >> 8)); sb.append(nibble(c >> 4)); sb.append(nibble(c)); } } return sb.toString(); } /** * Print the components in this JAR. * * @param jar */ private void printComponents(PrintStream out, Jar jar) throws Exception { out.println("[COMPONENTS]"); Manifest manifest = jar.getManifest(); if (manifest == null) { out.println("No manifest"); return; } String componentHeader = manifest.getMainAttributes().getValue(Constants.SERVICE_COMPONENT); Map<String, Map<String, String>> clauses = parseHeader(componentHeader); for (String path : clauses.keySet()) { out.println(path); Resource r = jar.getResource(path); if (r != null) { InputStreamReader ir = new InputStreamReader(r.openInputStream()); OutputStreamWriter or = new OutputStreamWriter(out); try { copy(ir, or); } finally { or.flush(); ir.close(); } } else { out.println(" - no resource"); warning("No Resource found for service component: " + path); } } out.println(); } Map<String, Set<String>> invertMapOfCollection(Map<String, Set<String>> map) { Map<String, Set<String>> result = new TreeMap<String, Set<String>>(); for (Map.Entry<String, Set<String>> entry : map.entrySet()) { String name = entry.getKey(); if (name.startsWith("java.") && !name.equals("java.sql")) continue; Collection<String> used = entry.getValue(); for (String n : used) { if (n.startsWith("java.") && !n.equals("java.sql")) continue; Set<String> set = result.get(n); if (set == null) { set = new TreeSet<String>(); result.put(n, set); } set.add(name); } } return result; } void printMapOfSets(Map<String, Set<String>> map) { for (Map.Entry<String, Set<String>> entry : map.entrySet()) { String name = entry.getKey(); Set<String> used = new TreeSet<String>(entry.getValue()); for (Iterator<String> k = used.iterator(); k.hasNext();) { String n = (String) k.next(); if (n.startsWith("java.") && !n.equals("java.sql")) k.remove(); } String list = vertical(40, used); format("%-40s %s", new Object[] { name, list }); } } String vertical(int padding, Set<String> used) { StringBuffer sb = new StringBuffer(); String del = ""; for (Iterator<String> u = used.iterator(); u.hasNext();) { String name = (String) u.next(); sb.append(del); sb.append(name); sb.append("\r\n"); del = pad(padding); } if (sb.length() == 0) sb.append("\r\n"); return sb.toString(); } String pad(int i) { StringBuffer sb = new StringBuffer(); while (i-- > 0) sb.append(' '); return sb.toString(); } /** * View files from JARs * * We parse the commandline and print each file on it. * * @param args * @param i * @throws Exception */ private void doView(String[] args, int i) throws Exception { int options = 0; String charset = "UTF-8"; File output = null; for (; i < args.length; i++) { if ("-charset".startsWith(args[i])) charset = args[++i]; else if ("-output".startsWith(args[i])) { output = new File(args[++i]); } else break; } if (i >= args.length) { error("Insufficient arguments for view, no JAR"); return; } String jar = args[i++]; if (i >= args.length) { error("No Files to view"); return; } doView(jar, args, i, charset, options, output); } private void doView(String jar, String[] args, int i, String charset, int options, File output) { File path = new File(jar).getAbsoluteFile(); File dir = path.getParentFile(); if (dir == null) { dir = new File(""); } if (!dir.exists()) { error("No such file: " + dir.getAbsolutePath()); return; } String name = path.getName(); if (name == null) name = "META-INF/MANIFEST.MF"; Instruction instruction = Instruction.getPattern(path.getName()); File[] children = dir.listFiles(); for (int j = 0; j < children.length; j++) { String base = children[j].getName(); // out.println("Considering: " + // children[j].getAbsolutePath() + " " + // instruction.getPattern()); if (instruction.matches(base) ^ instruction.isNegated()) { for (; i < args.length; i++) { doView(children[j], args[i], charset, options, output); } } } } private void doView(File file, String resource, String charset, int options, File output) { // out.println("doView:" + file.getAbsolutePath() ); try { Instruction instruction = Instruction.getPattern(resource); FileInputStream fin = new FileInputStream(file); ZipInputStream in = new ZipInputStream(fin); ZipEntry entry = in.getNextEntry(); while (entry != null) { // out.println("view " + file + ": " // + instruction.getPattern() + ": " + entry.getName() // + ": " + output + ": " // + instruction.matches(entry.getName())); if (instruction.matches(entry.getName()) ^ instruction.isNegated()) doView(entry.getName(), in, charset, options, output); in.closeEntry(); entry = in.getNextEntry(); } in.close(); fin.close(); } catch (Exception e) { out.println("Can not process: " + file.getAbsolutePath()); e.printStackTrace(); } } private void doView(String name, ZipInputStream in, String charset, int options, File output) throws Exception { int n = name.lastIndexOf('/'); name = name.substring(n + 1); InputStreamReader rds = new InputStreamReader(in, charset); OutputStreamWriter wrt = new OutputStreamWriter(out); if (output != null) if (output.isDirectory()) wrt = new FileWriter(new File(output, name)); else wrt = new FileWriter(output); copy(rds, wrt); // rds.close(); also closes the stream which closes our zip it // seems if (output != null) wrt.close(); else wrt.flush(); } private void copy(Reader rds, Writer wrt) throws IOException { char buffer[] = new char[1024]; int size = rds.read(buffer); while (size > 0) { wrt.write(buffer, 0, size); size = rds.read(buffer); } } private void print(String msg, Map<String, Map<String, String>> ports) { if (ports.isEmpty()) return; out.println(msg); for (Map.Entry<String, Map<String, String>> entry : ports.entrySet()) { String key = entry.getKey(); Map<String, String> clause = Create.copy(entry.getValue()); clause.remove("uses:"); format(" %-38s %s\r\n", key.trim(), clause.isEmpty() ? "" : clause.toString()); } } private void format(String string, Object... objects) { if (objects == null || objects.length == 0) return; StringBuffer sb = new StringBuffer(); int index = 0; for (int i = 0; i < string.length(); i++) { char c = string.charAt(i); switch (c) { case '%': String s = objects[index++] + ""; int width = 0; int justify = -1; i++; c = string.charAt(i++); switch (c) { case '-': justify = -1; break; case '+': justify = 1; break; case '|': justify = 0; break; default: --i; } c = string.charAt(i++); while (c >= '0' && c <= '9') { width *= 10; width += c - '0'; c = string.charAt(i++); } if (c != 's') { throw new IllegalArgumentException("Invalid sprintf format: " + string); } if (s.length() > width) sb.append(s); else { switch (justify) { case -1: sb.append(s); for (int j = 0; j < width - s.length(); j++) sb.append(" "); break; case 1: for (int j = 0; j < width - s.length(); j++) sb.append(" "); sb.append(s); break; case 0: int spaces = (width - s.length()) / 2; for (int j = 0; j < spaces; j++) sb.append(" "); sb.append(s); for (int j = 0; j < width - s.length() - spaces; j++) sb.append(" "); break; } } break; default: sb.append(c); } } out.print(sb); } private void doWrap(String[] args, int i) throws Exception { int options = 0; File properties = null; File output = null; File classpath[] = null; for (; i < args.length; i++) { if ("-output".startsWith(args[i])) output = new File(args[++i]); else if ("-properties".startsWith(args[i])) properties = new File(args[++i]); else if ("-classpath".startsWith(args[i])) { classpath = getClasspath(args[++i]); } else { File bundle = new File(args[i]); doWrap(properties, bundle, output, classpath, options, null); } } } public boolean doWrap(File properties, File bundle, File output, File classpath[], int options, Map<String, String> additional) throws Exception { if (!bundle.exists()) { error("No such file: " + bundle.getAbsolutePath()); return false; } else { Analyzer analyzer = new Analyzer(); try { analyzer.setPedantic(isPedantic()); analyzer.setJar(bundle); Jar dot = analyzer.getJar(); if (properties != null) { analyzer.setProperties(properties); } if (additional != null) analyzer.putAll(additional, false); if (analyzer.getProperty(Analyzer.IMPORT_PACKAGE) == null) analyzer.setProperty(Analyzer.IMPORT_PACKAGE, "*;resolution:=optional"); if (analyzer.getProperty(Analyzer.BUNDLE_SYMBOLICNAME) == null) { Pattern p = Pattern.compile("(" + Verifier.SYMBOLICNAME.pattern() + ")(-[0-9])?.*\\.jar"); String base = bundle.getName(); Matcher m = p.matcher(base); base = "Untitled"; if (m.matches()) { base = m.group(1); } else { error("Can not calculate name of output bundle, rename jar or use -properties"); } analyzer.setProperty(Analyzer.BUNDLE_SYMBOLICNAME, base); } if (analyzer.getProperty(Analyzer.EXPORT_PACKAGE) == null) { String export = analyzer.calculateExportsFromContents(dot); analyzer.setProperty(Analyzer.EXPORT_PACKAGE, export); } if (classpath != null) analyzer.setClasspath(classpath); analyzer.mergeManifest(dot.getManifest()); // // Cleanup the version .. // String version = analyzer.getProperty(Analyzer.BUNDLE_VERSION); if (version != null) { version = Builder.cleanupVersion(version); analyzer.setProperty(Analyzer.BUNDLE_VERSION, version); } if (output == null) if (properties != null) output = properties.getAbsoluteFile().getParentFile(); else output = bundle.getAbsoluteFile().getParentFile(); String path = bundle.getName(); if (path.endsWith(DEFAULT_JAR_EXTENSION)) path = path.substring(0, path.length() - DEFAULT_JAR_EXTENSION.length()) + DEFAULT_BAR_EXTENSION; else path = bundle.getName() + DEFAULT_BAR_EXTENSION; if (output.isDirectory()) output = new File(output, path); analyzer.calcManifest(); Jar jar = analyzer.getJar(); getInfo(analyzer); statistics(jar, output, ""); File f = File.createTempFile("tmpbnd", ".jar"); f.deleteOnExit(); try { jar.write(f); jar.close(); if (!f.renameTo(output)) { copy(f, output); } } finally { f.delete(); } return getErrors().size() == 0; } finally { analyzer.close(); } } } void doDiff(String args[], int first) throws IOException { File base = new File(""); boolean strict = false; Jar targets[] = new Jar[2]; int n = 0; for (int i = first; i < args.length; i++) { if ("-d".equals(args[i])) base = getFile(base, args[++i]); else if ("-strict".equals(args[i])) strict = "true".equalsIgnoreCase(args[++i]); else if (args[i].startsWith("-")) error("Unknown option for diff: " + args[i]); else { if (n >= 2) System.err.println("Must have 2 files ... not more"); else { File f = getFile(base, args[i]); if (!f.isFile()) System.err.println("Not a file: " + f); else { try { Jar jar = new Jar(f); targets[n++] = jar; } catch (Exception e) { System.err.println("Not a JAR: " + f); } } } } } if (n != 2) { System.err.println("Must have 2 files ..."); return; } Diff diff = new Diff(); Map<String, Object> map = diff.diff(targets[0], targets[1], strict); diff.print(System.out, map, 0); for (Jar jar : targets) { jar.close(); } diff.close(); } void copy(File a, File b) { try { InputStream in = new FileInputStream(a); OutputStream out = new FileOutputStream(b); byte[] buffer = new byte[8196]; int size = in.read(buffer); while (size > 0) { out.write(buffer, 0, size); size = in.read(buffer); } in.close(); out.close(); } catch (IOException e) { error("While copying the output: %s -> %s", e, a, b); } } public void setOut(PrintStream out) { this.out = out; } public Project getProject() throws Exception { if (project != null) return project; try { project = Workspace.getProject(getBase()); if (project == null) return null; if (!project.isValid()) return null; return project; } catch (IllegalArgumentException e) { return null; } } /** * Printout all the variables. * * @param args * @param i * @throws Exception */ public void debug(String args[], int i) throws Exception { Project project = getProject(); System.out.println("Project: " + project); Properties p = project.getFlattenedProperties(); for (Object k : p.keySet()) { String key = (String) k; String s = p.getProperty(key); Collection<String> l = null; if (s.indexOf(',') > 0) l = split(s); else if (s.indexOf(':') > 0) l = split(s, "\\s*:\\s*"); if (l != null) { String del = key; for (String ss : l) { System.out.printf("%-40s %s\n", del, ss); del = ""; } } else System.out.printf("%-40s %s\n", key, s); } } /** * Manage the repo. * * <pre> * repo * list * put &lt;file|url&gt; * get &lt;bsn&gt; (&lt;version&gt;)? * fetch &lt;file|url&gt; * </pre> */ public void repo(String args[], int i) throws Exception { String bsn = null; String version = null; List<RepositoryPlugin> repos = new ArrayList<RepositoryPlugin>(); RepositoryPlugin writable = null; Project p = Workspace.getProject(getBase()); if (p != null) { repos.addAll(p.getWorkspace().getRepositories()); for (Iterator<RepositoryPlugin> rp = repos.iterator(); rp.hasNext();) { RepositoryPlugin rpp = rp.next(); if (rpp.canWrite()) { writable = rpp; break; } } } for (; i < args.length; i++) { if ("repos".equals(args[i])) { int n = 0; for (RepositoryPlugin repo : repos) { out.printf("%3d. %s\n", n++, repo); } } else if ("list".equals(args[i])) { String mask = null; if (i < args.length - 1) { mask = args[++i]; } repoList(repos, mask); } else if ("-repo".equals(args[i])) { String location = args[++i]; if (location.equals("maven")) { System.out.println("Maven"); MavenRepository maven = new MavenRepository(); maven.setProperties(new HashMap<String, String>()); maven.setReporter(this); repos = Arrays.asList((RepositoryPlugin) maven); } else { FileRepo repo = new FileRepo(); repo.setReporter(this); repo.setLocation(location); repos = Arrays.asList((RepositoryPlugin) repo); writable = repo; } } else if ("-bsn".equals(args[i])) { bsn = args[++i]; } else if ("-version".equals(args[i])) { version = args[++i]; } else if ("spring".equals(args[i])) { if (bsn == null || version == null) { error("-bsn and -version must be set before spring command is used"); } else { String url = String .format( "http://www.springsource.com/repository/app/bundle/version/download?name=%s&version=%s&type=binary", bsn, version); repoPut(writable, p, url, bsn, version); } } else if ("put".equals(args[i])) while (++i < args.length) { repoPut(writable, p, args[i], bsn, version); } else if ("get".equals(args[i])) repoGet(repos, args[++i]); else repoFetch(repos, args[++i]); } } private void repoGet(List<RepositoryPlugin> writable, String string) { } private void repoPut(RepositoryPlugin writable, Project project, String file, String bsn, String version) throws Exception { Jar jar = null; int n = file.indexOf(':'); if (n > 1 && n < 10) { jar = project.getValidJar(new URL(file)); } else { File f = getFile(file); if (f.isFile()) { jar = project.getValidJar(f); } } if (jar != null) { Manifest manifest = jar.getManifest(); if (bsn != null) manifest.getMainAttributes().putValue(Constants.BUNDLE_SYMBOLICNAME, bsn); if (version != null) manifest.getMainAttributes().putValue(Constants.BUNDLE_VERSION, version); writable.put(jar); } else error("There is no such file or url: " + file); } private void repoFetch(List<RepositoryPlugin> repos, String string) { File f = getFile(string); if (f.isFile()) { } else { // try { // URL url = new URL(string); // } catch (MalformedURLException mue) { // // } } } void repoList(List<RepositoryPlugin> repos, String mask) throws Exception { trace("list repo " + repos + " " + mask); Set<String> bsns = new TreeSet<String>(); for (RepositoryPlugin repo : repos) { bsns.addAll(repo.list(mask)); } for (String bsn : bsns) { Set<Version> versions = new TreeSet<Version>(); for (RepositoryPlugin repo : repos) { List<Version> result = repo.versions(bsn); if (result != null) versions.addAll(result); } out.printf("%-40s %s\n", bsn, versions); } } /** * Patch */ void patch(String args[], int i) throws Exception { for (; i < args.length; i++) { if ("create".equals(args[i]) && i + 3 < args.length) { createPatch(args[++i], args[++i], args[++i]); } else if ("apply".equals(args[i]) && i + 3 < args.length) { applyPatch(args[++i], args[++i], args[++i]); } else if ("help".equals(args[i])) { out.println("patch (create <old> <new> <patch> | patch <old> <patch> <new>)"); } else out.println("Patch does not recognize command? " + Arrays.toString(args)); } } void createPatch(String old, String newer, String patch) throws Exception { Jar a = new Jar(new File(old)); Manifest am = a.getManifest(); Jar b = new Jar(new File(newer)); Manifest bm = b.getManifest(); Set<String> delete = newSet(); for (String path : a.getResources().keySet()) { Resource br = b.getResource(path); if (br == null) { trace("DELETE %s", path); delete.add(path); } else { Resource ar = a.getResource(path); if (isEqual(ar, br)) { trace("UNCHANGED %s", path); b.remove(path); } else trace("UPDATE %s", path); } } bm.getMainAttributes().putValue("Patch-Delete", join(delete, ", ")); bm.getMainAttributes().putValue("Patch-Version", am.getMainAttributes().getValue("Bundle-Version")); b.write(new File(patch)); a.close(); a.close(); } private boolean isEqual(Resource ar, Resource br) throws Exception { InputStream ain = ar.openInputStream(); try { InputStream bin = br.openInputStream(); try { while (true) { int an = ain.read(); int bn = bin.read(); if (an == bn) { if (an == -1) return true; } else return false; } } finally { bin.close(); } } finally { ain.close(); } } void applyPatch(String old, String patch, String newer) throws Exception { Jar a = new Jar(new File(old)); Jar b = new Jar(new File(patch)); Manifest bm = b.getManifest(); String patchDelete = bm.getMainAttributes().getValue("Patch-Delete"); String patchVersion = bm.getMainAttributes().getValue("Patch-Version"); if (patchVersion == null) { error("To patch, you must provide a patch bundle.\nThe given " + patch + " bundle does not contain the Patch-Version header"); return; } Collection<String> delete = split(patchDelete); Set<String> paths = new HashSet<String>(a.getResources().keySet()); paths.removeAll(delete); for (String path : paths) { Resource br = b.getResource(path); if (br == null) b.putResource(path, a.getResource(path)); } bm.getMainAttributes().putValue("Bundle-Version", patchVersion); b.write(new File(newer)); a.close(); b.close(); } /** * Run the tests from a prepared bnd file. * * @param args * @param i * @throws Exception */ public void runtests(String args[], int i) throws Exception { int errors = 0; File cwd = new File("").getAbsoluteFile(); - Workspace ws = new Workspace(cwd.getParentFile().getAbsoluteFile()); + Workspace ws = new Workspace(cwd); File reportDir = getFile("reports"); delete(reportDir); reportDir.mkdirs(); Tag summary = new Tag("summary"); summary.addAttribute("date", new Date()); summary.addAttribute("ws", ws.getBase()); boolean hadOne = false; for (; i < args.length; i++) { if (args[i].startsWith("-reportdir")) { reportDir = getFile(args[i]).getAbsoluteFile(); if (!reportDir.isDirectory()) error("reportdir must be a directory " + reportDir); } else if (args[i].startsWith("-title")) { summary.addAttribute("title", args[++i]); } else if (args[i].startsWith("-dir")) { cwd = getFile(args[++i]).getAbsoluteFile(); } else if (args[i].startsWith("-workspace")) { File tmp = getFile(args[++i]).getAbsoluteFile(); ws = Workspace.getWorkspace(tmp); } else { File f = getFile(args[i]); errors += runtTest(f, ws, reportDir, summary); hadOne = true; } } if (!hadOne) { // See if we had any, if so, just use all files in // the current directory File[] files = cwd.listFiles(); for (File f : files) { if (f.getName().endsWith(".bnd")) errors += runtTest(f, ws, reportDir, summary); } } if (errors > 0) summary.addAttribute("errors", errors); for (String error : getErrors()) { Tag e = new Tag("error"); e.addContent(error); } for (String warning : getWarnings()) { Tag e = new Tag("warning"); e.addContent(warning); } File r = getFile(reportDir + "/summary.xml"); FileOutputStream out = new FileOutputStream(r); PrintWriter pw = new PrintWriter(new OutputStreamWriter(out)); try { summary.print(0, pw); } finally { pw.close(); out.close(); } System.out.println("Errors: " + errors); } private int runtTest(File testFile, Workspace ws, File reportDir, Tag summary) throws Exception { File tmpDir = new File(reportDir, "tmp"); tmpDir.mkdirs(); tmpDir.deleteOnExit(); Tag test = new Tag(summary, "test"); test.addAttribute("path", testFile.getAbsolutePath()); if (!testFile.isFile()) { error("No bnd file: %s", testFile); test.addAttribute("exception", "No bnd file found"); return 1; } Project project = new Project(ws, testFile.getAbsoluteFile().getParentFile(), testFile .getAbsoluteFile()); project.setTrace(isTrace()); project.setProperty(NOBUNDLES, "true"); ProjectTester tester = project.getProjectTester(); getInfo(project, project.toString() + ": "); if (!isOk()) return -1; tester.setContinuous(false); tester.setReportDir(tmpDir); test.addAttribute("title", project.toString()); long start = System.currentTimeMillis(); try { int errors = tester.test(); Collection<File> reports = tester.getReports(); for (File report : reports) { Tag bundle = new Tag(test, "bundle"); File dest = new File(reportDir, report.getName()); report.renameTo(dest); bundle.addAttribute("file", dest.getAbsolutePath()); doPerReport(bundle, dest); } switch (errors) { case ProjectLauncher.OK: return 0; case ProjectLauncher.CANCELED: test.addAttribute("failed", "canceled"); return 1; case ProjectLauncher.DUPLICATE_BUNDLE: test.addAttribute("failed", "duplicate bundle"); return 1; case ProjectLauncher.ERROR: test.addAttribute("failed", "unknown reason"); return 1; case ProjectLauncher.RESOLVE_ERROR: test.addAttribute("failed", "resolve error"); return 1; case ProjectLauncher.TIMEDOUT: test.addAttribute("failed", "timed out"); return 1; case ProjectLauncher.WARNING: test.addAttribute("warning", "true"); return 1; case ProjectLauncher.ACTIVATOR_ERROR: test.addAttribute("failed", "activator error"); return 1; default: if (errors > 0) { test.addAttribute("errors", errors); return errors; } else { test.addAttribute("failed", "unknown reason"); return 1; } } } catch (Exception e) { test.addAttribute("failed", e); return 1; } finally { long duration = System.currentTimeMillis() - start; test.addAttribute("duration", (duration + 500) / 1000); getInfo(project, project.toString() + ": "); } } /** * Calculate the coverage if there is coverage info in the test file. */ private void doPerReport(Tag report, File file) throws Exception { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); // never forget this! DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(file); XPathFactory xpathFactory = XPathFactory.newInstance(); XPath xpath = xpathFactory.newXPath(); doCoverage(report, doc, xpath); doHtmlReport(report, file, doc, xpath); } catch (Exception e) { report.addAttribute("coverage-failed", e.getMessage()); } } private void doCoverage(Tag report, Document doc, XPath xpath) throws XPathExpressionException { int bad = Integer.parseInt(xpath.evaluate("count(//method[count(ref)<2])", doc)); int all = Integer.parseInt(xpath.evaluate("count(//method)", doc)); report.addAttribute("coverage-bad", bad); report.addAttribute("coverage-all", all); } private void doHtmlReport(Tag report, File file, Document doc, XPath xpath) throws Exception { String path = file.getAbsolutePath(); if (path.endsWith(".xml")) path = path.substring(0, path.length() - 4); path += ".html"; File html = new File(path); trace("Creating html report: %s", html); TransformerFactory fact = TransformerFactory.newInstance(); InputStream in = getClass().getResourceAsStream("testreport.xsl"); if (in == null) { warning("Resource not found: test-report.xsl, no html report"); } else { FileWriter out = new FileWriter(html); try { Transformer transformer = fact.newTransformer(new StreamSource(in)); transformer.transform(new DOMSource(doc), new StreamResult(out)); trace("Transformed"); } finally { in.close(); out.close(); } } } /** * Extract a file from the JAR */ public void doExtract(String args[], int i) throws Exception { if (i >= args.length) { error("No arguments for extract"); return; } File f = getFile(args[i++]); if (!f.isFile()) { error("No JAR file to extract from: %s", f); return; } if (i == args.length) { System.out.println("FILES:"); doPrint(f, LIST); return; } Jar j = new Jar(f); try { Writer output = new OutputStreamWriter(out); while (i < args.length) { String path = args[i++]; Resource r = j.getResource(path); if (r == null) error("No such resource: %s in %s", path, f); else { InputStream in = r.openInputStream(); try { InputStreamReader rds = new InputStreamReader(in); copy(rds, output); output.flush(); } finally { in.close(); } } } } finally { j.close(); } } void doDot(String args[], int i) throws Exception { File out = getFile("graph.gv"); Builder b = new Builder(); for (; i < args.length; i++) { if ("-o".equals(args[i])) out = getFile(args[++i]); else if (args[i].startsWith("-")) error("Unknown option for dot: %s", args[i]); else b.addClasspath(getFile(args[i])); } b.setProperty(EXPORT_PACKAGE, "*"); b.setPedantic(isPedantic()); b.build(); FileWriter os = new FileWriter(out); PrintWriter pw = new PrintWriter(os); try { pw.println("digraph bnd {"); pw.println(" size=\"6,6\";"); pw.println("node [color=lightblue2, style=filled,shape=box];"); for (Map.Entry<String, Set<String>> uses : b.getUses().entrySet()) { for (String p : uses.getValue()) { if (!p.startsWith("java.")) pw.printf("\"%s\" -> \"%s\";\n", uses.getKey(), p); } } pw.println("}"); } finally { pw.close(); } } void doLibsync(String args[], int i) throws Exception { List<File> files = new ArrayList<File>(); while (i < args.length) { String v = args[i++]; if (v.startsWith("-")) { error("Invalid option for libsync: %s, use: libsync [-url <url>] <file|dir>...", v); } else { File f = getFile(v); if (!f.exists()) { error("Non existent file: %s", f); } else traverse(files, f); } } LibSync libsync; libsync = new LibSync(this); for (File file : files) { Jar jar = new Jar(file); try { System.out.printf("%40s-%-10s", jar.getManifest().getMainAttributes().getValue( BUNDLE_SYMBOLICNAME), jar.getManifest().getMainAttributes().getValue( BUNDLE_VERSION)); libsync.submit(jar); getInfo(libsync); System.out.printf(" ok\n"); } catch (Exception e) { System.out.printf(" failed %s\n", e.getMessage()); error("Submit to libsync failed for %s: %s", file, e); } finally { jar.close(); } } } private void traverse(List<File> files, File f) { if (f.isFile()) { if (f.getName().endsWith(".jar")) files.add(f); } else if (f.isDirectory()) { File[] subs = f.listFiles(); for (File sub : subs) { traverse(files, sub); } } } public void global(String args[], int i) throws BackingStoreException { Settings settings = new Settings(); if (args.length == i) { for (String key : settings.getKeys()) System.out.printf("%-30s %s\n", key, settings.globalGet(key, "<>")); } else { while (i < args.length) { boolean remove=false; if ( "-remove".equals(args[i])) { remove = true; i++; } if (i + 1 == args.length) { if ( remove ) settings.globalRemove(args[i]); else System.out.printf("%-30s %s\n", args[i], settings.globalGet(args[i], "<>")); i++; } else { settings.globalSet(args[i], args[i + 1]); i += 2; } } } } } diff --git a/biz.aQute.bndlib/src/aQute/bnd/build/Project.java b/biz.aQute.bndlib/src/aQute/bnd/build/Project.java index 581453471..677aa844b 100644 --- a/biz.aQute.bndlib/src/aQute/bnd/build/Project.java +++ b/biz.aQute.bndlib/src/aQute/bnd/build/Project.java @@ -1,1528 +1,1529 @@ package aQute.bnd.build; import java.io.*; import java.lang.reflect.*; import java.net.*; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.locks.*; import java.util.jar.*; import aQute.bnd.help.*; import aQute.bnd.service.*; import aQute.bnd.service.action.*; import aQute.lib.osgi.*; import aQute.lib.osgi.eclipse.*; import aQute.libg.generics.*; import aQute.libg.header.*; import aQute.libg.sed.*; /** * This class is NOT threadsafe * * @author aqute * */ public class Project extends Processor { final static String DEFAULT_ACTIONS = "build; label='Build', test; label='Test', run; label='Run', clean; label='Clean', release; label='Release', refreshAll; label=Refresh, deploy;label=Deploy"; public final static String BNDFILE = "bnd.bnd"; public final static String BNDCNF = "cnf"; final Workspace workspace; boolean preparedPaths; final Collection<Project> dependson = new LinkedHashSet<Project>(); final Collection<Container> buildpath = new LinkedHashSet<Container>(); final Collection<Container> testpath = new LinkedHashSet<Container>(); final Collection<Container> runpath = new LinkedHashSet<Container>(); final Collection<String> runfile = new LinkedHashSet<String>(); final Collection<File> sourcepath = new LinkedHashSet<File>(); final Collection<File> allsourcepath = new LinkedHashSet<File>(); final Collection<Container> bootclasspath = new LinkedHashSet<Container>(); final Collection<Container> runbundles = new LinkedHashSet<Container>(); final Lock lock = new ReentrantLock(true); volatile String lockingReason; volatile Thread lockingThread; File output; File target; boolean inPrepare; int revision; File files[]; private long buildtime; static List<Project> trail = new ArrayList<Project>(); public Project(Workspace workspace, File projectDir, File buildFile) throws Exception { super(workspace); this.workspace = workspace; setFileMustExist(false); setProperties(buildFile); assert workspace != null; // For backward compatibility reasons, we also read readBuildProperties(); } public Project(Workspace workspace, File buildDir) throws Exception { this(workspace, buildDir, new File(buildDir, BNDFILE)); } private void readBuildProperties() throws Exception { try { File f = getFile("build.properties"); if (f.isFile()) { Properties p = loadProperties(f); for (Enumeration<?> e = p.propertyNames(); e.hasMoreElements();) { String key = (String) e.nextElement(); String newkey = key; if (key.indexOf('$') >= 0) { newkey = getReplacer().process(key); } setProperty(newkey, p.getProperty(key)); } } } catch (Exception e) { e.printStackTrace(); } } public static Project getUnparented(File propertiesFile) throws Exception { propertiesFile = propertiesFile.getAbsoluteFile(); Workspace workspace = new Workspace(propertiesFile.getParentFile()); Project project = new Project(workspace, propertiesFile.getParentFile()); project.setProperties(propertiesFile); project.setFileMustExist(true); return project; } public synchronized boolean isValid() { return getBase().isDirectory() && getPropertiesFile().isFile(); } /** * Return a new builder that is nicely setup for this project. Please close * this builder after use. * * @param parent * The project builder to use as parent, use this project if null * @return * @throws Exception */ public synchronized ProjectBuilder getBuilder(ProjectBuilder parent) throws Exception { ProjectBuilder builder; if (parent == null) builder = new ProjectBuilder(this); else builder = new ProjectBuilder(parent); builder.setBase(getBase()); return builder; } public synchronized int getChanged() { return revision; } /* * Indicate a change in the external world that affects our build. This will * clear any cached results. */ public synchronized void setChanged() { // if (refresh()) { preparedPaths = false; files = null; revision++; // } } public Workspace getWorkspace() { return workspace; } public String toString() { return getBase().getName(); } /** * Set up all the paths */ public synchronized void prepare() throws Exception { if (!isValid()) { warning("Invalid project attempts to prepare: %s", this); return; } if (inPrepare) throw new CircularDependencyException(trail.toString() + "," + this); trail.add(this); try { if (!preparedPaths) { inPrepare = true; try { dependson.clear(); buildpath.clear(); sourcepath.clear(); allsourcepath.clear(); bootclasspath.clear(); runpath.clear(); runbundles.clear(); testpath.clear(); // We use a builder to construct all the properties for // use. setProperty("basedir", getBase().getAbsolutePath()); // If a bnd.bnd file exists, we read it. // Otherwise, we just do the build properties. if (!getPropertiesFile().isFile() && new File(getBase(), ".classpath").isFile()) { // Get our Eclipse info, we might depend on other // projects // though ideally this should become empty and void doEclipseClasspath(); } // Calculate our source directory File src = getSrc(); if (src.isDirectory()) { sourcepath.add(src); allsourcepath.add(src); } else sourcepath.add(getBase()); // Set default bin directory output = getFile(getProperty("bin", "bin")).getAbsoluteFile(); if (!output.exists()) { output.mkdirs(); getWorkspace().changedFile(output); } if (!output.isDirectory()) error("Can not find output directory: " + output); else if (!buildpath.contains(output)) buildpath.add(new Container(this, output)); // Where we store all our generated stuff. target = getFile(getProperty("target", "generated")); if (!target.exists()) { target.mkdirs(); getWorkspace().changedFile(target); } // We might have some other projects we want build // before we do anything, but these projects are not in // our path. The -dependson allows you to build them before. List<Project> dependencies = new ArrayList<Project>(); // dependencies.add( getWorkspace().getProject("cnf")); String dp = getProperty(Constants.DEPENDSON); Set<String> requiredProjectNames = parseHeader(dp).keySet(); List<DependencyContributor> dcs = getPlugins(DependencyContributor.class); for (DependencyContributor dc : dcs) dc.addDependencies(this, requiredProjectNames); for (String p : requiredProjectNames) { Project required = getWorkspace().getProject(p); if (required == null) error("No such project " + required + " on " + Constants.DEPENDSON); else { dependencies.add(required); } } // We have two paths that consists of repo files, projects, // or some other stuff. The doPath routine adds them to the // path and extracts the projects so we can build them // before. doPath(buildpath, dependencies, parseBuildpath(), bootclasspath); doPath(runpath, dependencies, parseRunpath(), bootclasspath); doPath(runbundles, dependencies, parseRunbundles(), null); doPath(testpath, dependencies, parseTestpath(), null); // We now know all dependent projects. But we also depend // on whatever those projects depend on. This creates an // ordered list without any duplicates. This of course // assumes // that there is no circularity. However, this is checked // by the inPrepare flag, will throw an exception if we // are circular. Set<Project> done = new HashSet<Project>(); done.add(this); allsourcepath.addAll(sourcepath); for (Project project : dependencies) project.traverse(dependson, done); for (Project project : dependson) { allsourcepath.addAll(project.getSourcePath()); } if (isOk()) preparedPaths = true; } finally { inPrepare = false; } } } finally { trail.remove(this); } } public File getSrc() { return new File(getBase(), getProperty("src", "src")); } private void traverse(Collection<Project> dependencies, Set<Project> visited) throws Exception { if (visited.contains(this)) return; visited.add(this); for (Project project : getDependson()) project.traverse(dependencies, visited); dependencies.add(this); } /** * Iterate over the entries and place the projects on the projects list and * all the files of the entries on the resultpath. * * @param resultpath * The list that gets all the files * @param projects * The list that gets any projects that are entries * @param entries * The input list of classpath entries */ private void doPath(Collection<Container> resultpath, Collection<Project> projects, Collection<Container> entries, Collection<Container> bootclasspath) { for (Container cpe : entries) { if (cpe.getError() != null) error(cpe.getError()); else { if (cpe.getType() == Container.TYPE.PROJECT) { projects.add(cpe.getProject()); } if (bootclasspath != null && cpe.getBundleSymbolicName().startsWith("ee.") || cpe.getAttributes().containsKey("boot")) bootclasspath.add(cpe); else resultpath.add(cpe); } } } /** * Parse the list of bundles that are a prerequisite to this project. * * Bundles are listed in repo specific names. So we just let our repo * plugins iterate over the list of bundles and we get the highest version * from them. * * @return */ private List<Container> parseBuildpath() throws Exception { return getBundles(Constants.STRATEGY_LOWEST, getProperty(Constants.BUILDPATH)); } private List<Container> parseRunpath() throws Exception { return getBundles(Constants.STRATEGY_HIGHEST, getProperty(Constants.RUNPATH)); } private List<Container> parseRunbundles() throws Exception { return getBundles(Constants.STRATEGY_HIGHEST, getProperty(Constants.RUNBUNDLES)); } private List<Container> parseTestpath() throws Exception { return getBundles(Constants.STRATEGY_HIGHEST, getProperty(Constants.TESTPATH)); } /** * Analyze the header and return a list of files that should be on the * build, test or some other path. The list is assumed to be a list of bsns * with a version specification. The special case of version=project * indicates there is a project in the same workspace. The path to the * output directory is calculated. The default directory ${bin} can be * overridden with the output attribute. * * @param strategy * STRATEGY_LOWEST or STRATEGY_HIGHEST * @param spec * The header * @return */ public List<Container> getBundles(int strategyx, String spec) throws Exception { List<Container> result = new ArrayList<Container>(); Map<String, Map<String, String>> bundles = parseHeader(spec); try { for (Iterator<Map.Entry<String, Map<String, String>>> i = bundles.entrySet().iterator(); i .hasNext();) { Map.Entry<String, Map<String, String>> entry = i.next(); String bsn = entry.getKey(); Map<String, String> attrs = entry.getValue(); Container found = null; String versionRange = attrs.get("version"); if (versionRange != null) { if (versionRange.equals("latest") || versionRange.equals("snapshot")) { found = getBundle(bsn, versionRange, strategyx, attrs); } } if (found == null) { if (versionRange != null && (versionRange.equals("project") || versionRange.equals("latest"))) { Project project = getWorkspace().getProject(bsn); if (project != null && project.exists()) { File f = project.getOutput(); found = new Container(project, bsn, "project", Container.TYPE.PROJECT, f, null, attrs); } else { error("Reference to project that does not exist in workspace\n" + " Project %s\n" + " Specification %s", bsn, spec); continue; } } else if (versionRange != null && versionRange.equals("file")) { File f = getFile(bsn); String error = null; if (!f.exists()) error = "File does not exist: " + f.getAbsolutePath(); if (f.getName().endsWith(".lib")) { found = new Container(this, bsn, "file", Container.TYPE.LIBRARY, f, error, attrs); } else { found = new Container(this, bsn, "file", Container.TYPE.EXTERNAL, f, error, attrs); } } else { found = getBundle(bsn, versionRange, strategyx, attrs); } } if (found != null) { List<Container> libs = found.getMembers(); for (Container cc : libs) { if (result.contains(cc)) warning("Multiple bundles with the same final URL: " + cc); result.add(cc); } } else { // Oops, not a bundle in sight :-( Container x = new Container(this, bsn, versionRange, Container.TYPE.ERROR, null, bsn + ";version=" + versionRange + " not found", attrs); result.add(x); warning("Can not find URL for bsn " + bsn); } } } catch (Exception e) { error("While tring to get the bundles from " + spec, e); e.printStackTrace(); } return result; } public Collection<Project> getDependson() throws Exception { prepare(); return dependson; } public Collection<Container> getBuildpath() throws Exception { prepare(); return buildpath; } public Collection<Container> getTestpath() throws Exception { prepare(); return testpath; } public Collection<Container> getRunpath() throws Exception { prepare(); return runpath; } public Collection<Container> getRunbundles() throws Exception { prepare(); return runbundles; } public Collection<File> getSourcePath() throws Exception { prepare(); return sourcepath; } public Collection<File> getAllsourcepath() throws Exception { prepare(); return allsourcepath; } public Collection<Container> getBootclasspath() throws Exception { prepare(); return bootclasspath; } public File getOutput() throws Exception { prepare(); return output; } private void doEclipseClasspath() throws Exception { EclipseClasspath eclipse = new EclipseClasspath(this, getWorkspace().getBase(), getBase()); eclipse.setRecurse(false); // We get the file directories but in this case we need // to tell ant that the project names for (File dependent : eclipse.getDependents()) { Project required = workspace.getProject(dependent.getName()); dependson.add(required); } for (File f : eclipse.getClasspath()) { buildpath.add(new Container(f)); } for (File f : eclipse.getBootclasspath()) { bootclasspath.add(new Container(f)); } sourcepath.addAll(eclipse.getSourcepath()); allsourcepath.addAll(eclipse.getAllSources()); output = eclipse.getOutput(); } public String _p_dependson(String args[]) throws Exception { return list(args, toFiles(getDependson())); } private Collection<?> toFiles(Collection<Project> projects) { List<File> files = new ArrayList<File>(); for (Project p : projects) { files.add(p.getBase()); } return files; } public String _p_buildpath(String args[]) throws Exception { return list(args, getBuildpath()); } public String _p_testpath(String args[]) throws Exception { return list(args, getRunpath()); } public String _p_sourcepath(String args[]) throws Exception { return list(args, getSourcePath()); } public String _p_allsourcepath(String args[]) throws Exception { return list(args, getAllsourcepath()); } public String _p_bootclasspath(String args[]) throws Exception { return list(args, getBootclasspath()); } public String _p_output(String args[]) throws Exception { if (args.length != 1) throw new IllegalArgumentException("${output} should not have arguments"); return getOutput().getAbsolutePath(); } private String list(String[] args, Collection<?> list) { if (args.length > 3) throw new IllegalArgumentException("${" + args[0] + "[;<separator>]} can only take a separator as argument, has " + Arrays.toString(args)); String separator = ","; if (args.length == 2) { separator = args[1]; } return join(list, separator); } protected Object[] getMacroDomains() { return new Object[] { workspace }; } public File release(Jar jar) throws Exception { String name = getProperty(Constants.RELEASEREPO); return release(name, jar); } /** * Release * * @param name * The repository name * @param jar * @return * @throws Exception */ public File release(String name, Jar jar) throws Exception { List<RepositoryPlugin> plugins = getRepositories(); RepositoryPlugin rp = null; for (RepositoryPlugin plugin : plugins) { if (!plugin.canWrite()) { continue; } if (name == null) { rp = plugin; break; } else if (name.equals(plugin.getName())) { rp = plugin; break; } } if (rp != null) { try { return rp.put(jar); } catch (Exception e) { error("Deploying " + jar.getName() + " on " + rp.getName(), e); } finally { jar.close(); } } return null; } public void release(boolean test) throws Exception { String name = getProperty(Constants.RELEASEREPO); release(name, test); } /** * Release * * @param name * The respository name * @param test * Run testcases * @throws Exception */ public void release(String name, boolean test) throws Exception { File[] jars = build(test); // If build fails jars will be null if (jars == null) { return; } for (File jar : jars) { Jar j = new Jar(jar); release(name, j); j.close(); } } /** * Get a bundle from one of the plugin repositories. * * @param bsn * The bundle symbolic name * @param range * The version range * @param lowest * set to LOWEST or HIGHEST * @return the file object that points to the bundle or null if not found * @throws Exception * when something goes wrong */ public Container getBundle(String bsn, String range, int strategyx, Map<String, String> attrs) throws Exception { if ("snapshot".equals(range)) { return getBundleFromProject(bsn, attrs); } if ("latest".equals(range)) { Container c = getBundleFromProject(bsn, attrs); if (c != null) return c; } List<RepositoryPlugin> plugins = getRepositories(); int useStrategy = strategyx; if (attrs != null) { String overrideStrategy = attrs.get("strategy"); if (overrideStrategy != null) { if ("highest".equalsIgnoreCase(overrideStrategy)) useStrategy = STRATEGY_HIGHEST; else if ("lowest".equalsIgnoreCase(overrideStrategy)) useStrategy = STRATEGY_LOWEST; else if ("exact".equalsIgnoreCase(overrideStrategy)) useStrategy = STRATEGY_EXACT; } } // If someone really wants the latest, lets give it to them. // regardless of they asked for a lowest strategy if (range != null && range.equals("latest")) useStrategy = STRATEGY_HIGHEST; // Maybe we want an exact match this time. // In that case we limit the range to be exactly // the version specified. We ignore it when a range // is used instead of a version if (useStrategy == STRATEGY_EXACT && range != null) { if (range.indexOf('(') < 0 && range.indexOf('[') < 0 && range.indexOf(',') < 0) { range = range.trim(); range = "[" + range + "," + range + "]"; } } for (RepositoryPlugin plugin : plugins) { File[] results = plugin.get(bsn, range); if (results != null && results.length > 0) { File f = results[useStrategy == STRATEGY_LOWEST ? 0 : results.length - 1]; if (f.getName().endsWith("lib")) return new Container(this, bsn, range, Container.TYPE.LIBRARY, f, null, attrs); else return new Container(this, bsn, range, Container.TYPE.REPO, f, null, attrs); } } return new Container(this, bsn, range, Container.TYPE.ERROR, null, bsn + ";version=" + range + " Not found in " + plugins, null); } /** * Look for the bundle in the workspace. The premise is that the bsn must * start with the project name. * * @param bsn * The bsn * @param attrs * Any attributes * @return * @throws Exception */ private Container getBundleFromProject(String bsn, Map<String, String> attrs) throws Exception { String pname = bsn; while (true) { Project p = getWorkspace().getProject(pname); if (p != null && p.isValid()) { Container c = p.getDeliverable(bsn, attrs); return c; } int n = pname.lastIndexOf('.'); if (n <= 0) return null; pname = pname.substring(0, n); } } /** * Deploy the file (which must be a bundle) into the repository. * * @param name * The repository name * @param file * bundle */ public void deploy(String name, File file) throws Exception { List<RepositoryPlugin> plugins = getRepositories(); RepositoryPlugin rp = null; for (RepositoryPlugin plugin : plugins) { if (!plugin.canWrite()) { continue; } if (name == null) { rp = plugin; break; } else if (name.equals(plugin.getName())) { rp = plugin; break; } } if (rp != null) { Jar jar = new Jar(file); try { rp.put(jar); return; } catch (Exception e) { error("Deploying " + file + " on " + rp.getName(), e); } finally { jar.close(); } return; } trace("No repo found " + file); throw new IllegalArgumentException("No repository found for " + file); } /** * Deploy the file (which must be a bundle) into the repository. * * @param file * bundle */ public void deploy(File file) throws Exception { String name = getProperty(Constants.DEPLOYREPO); deploy(name, file); } /** * Deploy the current project to a repository * * @throws Exception */ public void deploy() throws Exception { Map<String, Map<String, String>> deploy = parseHeader(getProperty(DEPLOY)); if (deploy.isEmpty()) { warning("Deploying but %s is not set to any repo", DEPLOY); return; } File[] outputs = getBuildFiles(); for (File output : outputs) { Jar jar = new Jar(output); try { for (Deploy d : getPlugins(Deploy.class)) { trace("Deploying %s to: %s", jar, d); try { if (d.deploy(this, jar)) trace("deployed %s successfully to %s", output, d); } catch (Exception e) { error("Error while deploying %s, %s", this, e); e.printStackTrace(); } } } finally { jar.close(); } } } /** * Macro access to the repository * * ${repo;<bsn>[;<version>[;<low|high>]]} */ public String _repo(String args[]) throws Exception { if (args.length < 2) throw new IllegalArgumentException( "Too few arguments for repo, syntax=: ${repo ';'<bsn> [ ; <version> [; ('HIGHEST'|'LOWEST')]}"); String bsns = args[1]; String version = null; int strategy = Constants.STRATEGY_HIGHEST; if (args.length > 2) { version = args[2]; if (args.length == 4) { if (args[3].equalsIgnoreCase("HIGHEST")) strategy = Constants.STRATEGY_HIGHEST; else if (args[3].equalsIgnoreCase("LOWEST")) strategy = STRATEGY_LOWEST; else error("${repo;<bsn>;<version>;<'highest'|'lowest'>} macro requires a strategy of 'highest' or 'lowest', and is " + args[3]); } } Collection<String> parts = split(bsns); List<String> paths = new ArrayList<String>(); for (String bsn : parts) { Container container = getBundle(bsn, version, strategy, null); add(paths, container); } return join(paths); } private List<RepositoryPlugin> getRepositories() { return getWorkspace().getRepositories(); } private void add(List<String> paths, Container container) throws Exception { if (container.getType() == Container.TYPE.LIBRARY) { List<Container> members = container.getMembers(); for (Container sub : members) { add(paths, sub); } } else { if (container.getError() == null) paths.add(container.getFile().getAbsolutePath()); else { paths.add("<<${repo} = " + container.getBundleSymbolicName() + "-" + container.getVersion() + " : " + container.getError() + ">>"); if ( isPedantic() ) { warning("Could not expand repo path request: %s ", container); } } } } public File getTarget() throws Exception { prepare(); return target; } /** * This is the external method that will pre-build any dependencies if it is * out of date. * * @param underTest * @return * @throws Exception */ public File[] build(boolean underTest) throws Exception { if (getProperty(NOBUNDLES) != null) return null; if (getProperty("-nope") != null) { warning("Please replace -nope with %s", NOBUNDLES); return null; } // Check if we have a local modification not yet build boolean outofdate = false; // Check for each dependency if it is locally modified or // its build time > our build time. for (Project dependency : getDependson()) { if (dependency != this) { if (outofdate || dependency.getBuildTime() <= dependency.lastModified()) { dependency.buildLocal(false); outofdate = true; } } } if (files == null || outofdate || getBuildTime() <= lastModified()) { trace("Building " + this); files = buildLocal(underTest); } return files; } /** * This method must only be called when it is sure that the project has been * build before in the same session. * * It is a bit yucky, but ant creates different class spaces which makes it * hard to detect we already build it. * * @return */ public File[] getBuildFiles() throws Exception { File f = new File(getTarget(), BUILDFILES); if (f.isFile()) { FileReader fin = new FileReader(f); BufferedReader rdr = new BufferedReader(fin); try { List<File> files = newList(); for (String s = rdr.readLine(); s != null; s = rdr.readLine()) { s = s.trim(); File ff = new File(s); if (!ff.isFile()) { error("buildfile lists file but the file does not exist %s", ff); } else files.add(ff); } return files.toArray(new File[files.size()]); } finally { fin.close(); } } return buildLocal(false); } /** * Build without doing any dependency checking. Make sure any dependent * projects are built first. * * @param underTest * @return * @throws Exception */ public File[] buildLocal(boolean underTest) throws Exception { if (getProperty(NOBUNDLES) != null) return null; long buildtime = System.currentTimeMillis(); File bfs = new File(getTarget(), BUILDFILES); bfs.delete(); files = null; ProjectBuilder builder = getBuilder(null); if (underTest) builder.setProperty(Constants.UNDERTEST, "true"); Jar jars[] = builder.builds(); File[] files = new File[jars.length]; for (int i = 0; i < jars.length; i++) { Jar jar = jars[i]; files[i] = saveBuild(jar); } getInfo(builder); builder.close(); if (isOk()) { this.files = files; // Write out the filenames in the buildfiles file // so we can get them later evenin another process FileWriter fw = new FileWriter(bfs); try { for (File f : files) { fw.append(f.getAbsolutePath()); fw.append("\n"); } } finally { fw.close(); } getWorkspace().changedFile(bfs); this.buildtime = buildtime; return files; } else return null; } public File saveBuild(Jar jar) throws Exception { try { String bsn = jar.getName(); File f = getOutputFile(bsn); String msg = ""; if (!f.exists() || f.lastModified() < jar.lastModified()) { reportNewer(f.lastModified(), jar); f.delete(); jar.write(f); if (!f.getParentFile().isDirectory()) f.getParentFile().mkdirs(); getWorkspace().changedFile(f); } else { msg = "(not modified since " + new Date(f.lastModified()) + ")"; } trace(jar.getName() + " (" + f.getName() + ") " + jar.getResources().size() + " " + msg); return f; } finally { jar.close(); } } private File getOutputFile(String bsn) throws Exception { return new File(getTarget(), bsn + ".jar"); } private void reportNewer(long lastModified, Jar jar) { if (isTrue(getProperty(Constants.REPORTNEWER))) { StringBuilder sb = new StringBuilder(); String del = "Newer than " + new Date(lastModified); for (Map.Entry<String, Resource> entry : jar.getResources().entrySet()) { if (entry.getValue().lastModified() > lastModified) { sb.append(del); del = ", \n "; sb.append(entry.getKey()); } } if (sb.length() > 0) warning(sb.toString()); } } /** * Refresh if we are based on stale data. This also implies our workspace. */ public boolean refresh() { boolean changed = false; if (isCnf()) { changed = workspace.refresh(); } return super.refresh() || changed; } public boolean isCnf() { return getBase().getName().equals(Workspace.CNFDIR); } public void propertiesChanged() { super.propertiesChanged(); preparedPaths = false; files = null; } public String getName() { return getBase().getName(); } public Map<String, Action> getActions() { Map<String, Action> all = newMap(); Map<String, Action> actions = newMap(); fillActions(all); getWorkspace().fillActions(all); for (Map.Entry<String, Action> action : all.entrySet()) { String key = getReplacer().process(action.getKey()); if (key != null && key.trim().length() != 0) actions.put(key, action.getValue()); } return actions; } public void fillActions(Map<String, Action> all) { List<NamedAction> plugins = getPlugins(NamedAction.class); for (NamedAction a : plugins) all.put(a.getName(), a); Map<String, Map<String, String>> actions = parseHeader(getProperty("-actions", DEFAULT_ACTIONS)); for (Map.Entry<String, Map<String, String>> entry : actions.entrySet()) { String key = Processor.removeDuplicateMarker(entry.getKey()); Action action; if (entry.getValue().get("script") != null) { // TODO check for the type action = new ScriptAction(entry.getValue().get("type"), entry.getValue().get( "script")); } else { action = new ReflectAction(key); } String label = entry.getValue().get("label"); all.put(label.toLowerCase(), action); } } public void release() throws Exception { release(false); } /** * Release. * * @param name * The repository name * @throws Exception */ public void release(String name) throws Exception { release(name, false); } public void clean() throws Exception { File target = getTarget(); if (target.isDirectory() && target.getParentFile() != null) { delete(target); } if (getOutput().isDirectory()) delete(getOutput()); getOutput().mkdirs(); } public File[] build() throws Exception { return build(false); } public void run() throws Exception { ProjectLauncher pl = getProjectLauncher(); pl.launch(); } public void test() throws Exception { clear(); ProjectTester tester = getProjectTester(); tester.setContinuous(false); tester.prepare(); if (!isOk()) { return; } int errors = tester.test(); if (errors == 0) { System.out.println("No Errors"); } else { if (errors > 0) { System.out.println(errors + " Error(s)"); } else System.out.println("Error " + errors); } } /** * This methods attempts to turn any jar into a valid jar. If this is a * bundle with manifest, a manifest is added based on defaults. If it is a * bundle, but not r4, we try to add the r4 headers. * * @param name * @param in * @return * @throws Exception */ public Jar getValidJar(File f) throws Exception { Jar jar = new Jar(f); return getValidJar(jar, f.getAbsolutePath()); } public Jar getValidJar(URL url) throws Exception { InputStream in = url.openStream(); try { Jar jar = new Jar(url.getFile().replace('/', '.'), in, System.currentTimeMillis()); return getValidJar(jar, url.toString()); } finally { in.close(); } } public Jar getValidJar(Jar jar, String id) throws Exception { Manifest manifest = jar.getManifest(); if (manifest == null) { trace("Wrapping with all defaults"); Builder b = new Builder(this); b.addClasspath(jar); b.setProperty("Bnd-Message", "Wrapped from " + id + "because lacked manifest"); b.setProperty(Constants.EXPORT_PACKAGE, "*"); b.setProperty(Constants.IMPORT_PACKAGE, "*;resolution:=optional"); jar = b.build(); } else if (manifest.getMainAttributes().getValue(Constants.BUNDLE_MANIFESTVERSION) == null) { trace("Not a release 4 bundle, wrapping with manifest as source"); Builder b = new Builder(this); b.addClasspath(jar); b.setProperty(Constants.PRIVATE_PACKAGE, "*"); b.mergeManifest(manifest); String imprts = manifest.getMainAttributes().getValue(Constants.IMPORT_PACKAGE); if (imprts == null) imprts = ""; else imprts += ","; imprts += "*;resolution=optional"; b.setProperty(Constants.IMPORT_PACKAGE, imprts); b.setProperty("Bnd-Message", "Wrapped from " + id + "because had incomplete manifest"); jar = b.build(); } return jar; } public String _project(String args[]) { return getBase().getAbsolutePath(); } public void bump(String mask) throws IOException { Sed sed = new Sed(getReplacer(), getPropertiesFile()); sed.replace("(Bundle-Version\\s*(:|=)\\s*)(([0-9]+(\\.[0-9]+(\\.[0-9]+)?)?))", "$1${version;" + mask + ";$3}"); sed.doIt(); refresh(); } public void bump() throws IOException { bump(getProperty(BUMPPOLICY, "=+0")); } public void action(String command) throws Throwable { Map<String, Action> actions = getActions(); Action a = actions.get(command); if (a == null) a = new ReflectAction(command); before(this, command); try { a.execute(this, command); } catch (Throwable t) { after(this, command, t); throw t; } } /** * Run all before command plugins * */ void before(Project p, String a) { List<CommandPlugin> testPlugins = getPlugins(CommandPlugin.class); for (CommandPlugin testPlugin : testPlugins) { testPlugin.before(this, a); } } /** * Run all after command plugins */ void after(Project p, String a, Throwable t) { List<CommandPlugin> testPlugins = getPlugins(CommandPlugin.class); for (int i = testPlugins.size() - 1; i >= 0; i--) { testPlugins.get(i).after(this, a, t); } } public String _findfile(String args[]) { File f = getFile(args[1]); List<String> files = new ArrayList<String>(); tree(files, f, "", Instruction.getPattern(args[2])); return join(files); } void tree(List<String> list, File current, String path, Instruction instr) { if (path.length() > 0) path = path + "/"; String subs[] = current.list(); if (subs != null) { for (String sub : subs) { File f = new File(current, sub); if (f.isFile()) { if (instr.matches(sub) && !instr.isNegated()) list.add(path + sub); } else tree(list, f, path + sub, instr); } } } public void refreshAll() { workspace.refresh(); refresh(); } @SuppressWarnings("unchecked") public void script(String type, String script) throws Exception { // TODO check tyiping List<Scripter> scripters = getPlugins(Scripter.class); if (scripters.isEmpty()) { error("Can not execute script because there are no scripters registered: %s", script); return; } Map x = (Map) getProperties(); scripters.get(0).eval((Map<String, Object>) x, new StringReader(script)); } public String _repos(String args[]) throws Exception { List<RepositoryPlugin> repos = getPlugins(RepositoryPlugin.class); List<String> names = new ArrayList<String>(); for (RepositoryPlugin rp : repos) names.add(rp.getName()); return join(names, ", "); } public String _help(String args[]) throws Exception { if (args.length == 1) return "Specify the option or header you want information for"; Syntax syntax = Syntax.HELP.get(args[1]); if (syntax == null) return "No help for " + args[1]; String what = null; if (args.length > 2) what = args[2]; if (what == null || what.equals("lead")) return syntax.getLead(); if (what == null || what.equals("example")) return syntax.getExample(); if (what == null || what.equals("pattern")) return syntax.getPattern(); if (what == null || what.equals("values")) return syntax.getValues(); return "Invalid type specified for help: lead, example, pattern, values"; } /** * Returns containers for the deliverables of this project. The deliverables * is the project builder for this project if no -sub is specified. * Otherwise it contains all the sub bnd files. * * @return A collection of containers * * @throws Exception */ public Collection<Container> getDeliverables() throws Exception { List<Container> result = new ArrayList<Container>(); Collection<? extends Builder> builders = getSubBuilders(); for (Builder builder : builders) { Container c = new Container(this, builder.getBsn(), builder.getVersion(), Container.TYPE.PROJECT, getOutputFile(builder.getBsn()), null, null); result.add(c); } return result; } /** * Return the builder associated with the give bnd file or null. The bnd.bnd * file can contain -sub option. This option allows specifying files in the * same directory that should drive the generation of multiple deliverables. * This method figures out if the bndFile is actually one of the bnd files * of a deliverable. * * @param bndFile * A file pointing to a bnd file. * @return null or the builder for a sub file. * @throws Exception */ public Builder getSubBuilder(File bndFile) throws Exception { bndFile = bndFile.getCanonicalFile(); // Verify that we are inside the project. File base = getBase().getCanonicalFile(); if (!bndFile.getAbsolutePath().startsWith(base.getAbsolutePath())) return null; Collection<? extends Builder> builders = getSubBuilders(); for (Builder sub : builders) { File propertiesFile = sub.getPropertiesFile(); if (propertiesFile != null) { if (propertiesFile.getCanonicalFile().equals(bndFile)) { // Found it! return sub; } } } return null; } /** * Answer the container associated with a given bsn. * * @param bndFile * A file pointing to a bnd file. * @return null or the builder for a sub file. * @throws Exception */ public Container getDeliverable(String bsn, Map<String, String> attrs) throws Exception { Collection<? extends Builder> builders = getSubBuilders(); for (Builder sub : builders) { if (sub.getBsn().equals(bsn)) return new Container(this, getOutputFile(bsn)); } return null; } /** * Get a list of the sub builders. A bnd.bnd file can contain the -sub * option. This will generate multiple deliverables. This method returns the * builders for each sub file. If no -sub option is present, the list will * contain a builder for the bnd.bnd file. * * @return A list of builders. * @throws Exception */ public Collection<? extends Builder> getSubBuilders() throws Exception { return getBuilder(null).getSubBuilders(); } /** * Calculate the classpath. We include our own runtime.jar which includes * the test framework and we include the first of the test frameworks * specified. * * @throws Exception */ Collection<File> toFile(Collection<Container> containers) throws Exception { ArrayList<File> files = new ArrayList<File>(); for (Container container : containers) { container.contributeFiles(files, this); } return files; } public Collection<String> getRunVM() { - return Processor.split(getProperty(RUNVM)); + Map<String,Map<String,String>> hdr = parseHeader(getProperty(RUNVM)); + return hdr.keySet(); } public Map<String, String> getRunProperties() { return OSGiHeader.parseProperties(getProperty(RUNPROPERTIES)); } /** * Get a launcher. * * @return * @throws Exception */ public ProjectLauncher getProjectLauncher() throws Exception { return getHandler(ProjectLauncher.class, getRunpath(), LAUNCHER_PLUGIN, "biz.aQute.launcher"); } public ProjectTester getProjectTester() throws Exception { return getHandler(ProjectTester.class, getTestpath(), TESTER_PLUGIN, "biz.aQute.junit"); } private <T> T getHandler(Class<T> target, Collection<Container> containers, String header, String defaultHandler) throws Exception { Class<? extends T> handlerClass = target; // Make sure we find at least one handler, but hope to find an earlier // one List<Container> withDefault = Create.list(); withDefault.addAll(containers); withDefault.addAll(getBundles(STRATEGY_HIGHEST, defaultHandler)); for (Container c : withDefault) { Manifest manifest = c.getManifest(); if (manifest != null) { String launcher = manifest.getMainAttributes().getValue(header); if (launcher != null) { Class<?> clz = getClass(launcher, c.getFile()); if (clz != null) { if (!target.isAssignableFrom(clz)) { error("Found a %s class in %s but it is not compatible with: %s", clz, c, target); } else { handlerClass = clz.asSubclass(target); Constructor<? extends T> constructor = handlerClass .getConstructor(Project.class); return constructor.newInstance(this); } } } } } throw new IllegalArgumentException("Default handler for " + header + " not found in " + defaultHandler); } public synchronized boolean lock(String reason) throws InterruptedException { if (!lock.tryLock(5, TimeUnit.SECONDS)) { error("Could not acquire lock for %s, was locked by %s for %s", reason, lockingThread, lockingReason); System.out.printf("Could not acquire lock for %s, was locked by %s for %s\n", reason, lockingThread, lockingReason); System.out.flush(); return false; } this.lockingReason = reason; this.lockingThread = Thread.currentThread(); return true; } public void unlock() { lockingReason = null; lock.unlock(); } public long getBuildTime() throws Exception { if (buildtime == 0) { files = getBuildFiles(); if (files != null && files.length >= 1) buildtime = files[0].lastModified(); } return buildtime; } }
false
false
null
null
diff --git a/src/vooga/fighter/controller/CharacterSelectController.java b/src/vooga/fighter/controller/CharacterSelectController.java index 02604cbf..1ff6dfce 100644 --- a/src/vooga/fighter/controller/CharacterSelectController.java +++ b/src/vooga/fighter/controller/CharacterSelectController.java @@ -1,77 +1,78 @@ package vooga.fighter.controller; import util.Location; import util.input.AlertObject; import util.input.Input; import util.input.InputClassTarget; import util.input.InputMethodTarget; import util.input.PositionObject; import vooga.fighter.controller.Controller; import vooga.fighter.controller.ControllerDelegate; import vooga.fighter.controller.GameInfo; import vooga.fighter.controller.OneVOneController; import vooga.fighter.model.*; import vooga.fighter.model.objects.MouseClickObject; import vooga.fighter.util.Paintable; import vooga.fighter.view.Canvas; import java.awt.Dimension; import java.util.List; import java.util.ResourceBundle; /** * * @author Jerry Li and Jack Matteucci */ @InputClassTarget public class CharacterSelectController extends MenuController { private int myCharLimit; private int myCharIndex; private Input myInput; public CharacterSelectController () { super(); } public void initializeRest(Canvas frame, ControllerDelegate manager, GameInfo gameinfo) { super.initializeRest(frame, manager, gameinfo); myCharLimit = getGameInfo().getNumCharacters(); myCharIndex = 0; } /** * Checks this controller's end conditions */ public void notifyEndCondition(String choice) { getGameInfo().addCharacters(choice); myCharIndex ++; if(myCharIndex >= myCharLimit){ removeListener(); getManager().notifyEndCondition(NEXT); } } @InputMethodTarget(name = "continue") public void mouseclick(PositionObject pos) { super.getMode().addObject(new MouseClickObject(pos.getPoint2D())); } public void removeListener(){ super.removeListener(); getInput().removeListener(this); } public void checkConditions(){ String choice = getMode().getChoice(); + if(!choice.equals("")) notifyEndCondition("1v1"); for(String other: getMode().getMenuNames()){ if(other.equals(choice)){ notifyEndCondition(choice); } } } } diff --git a/src/vooga/fighter/controller/MapSelectController.java b/src/vooga/fighter/controller/MapSelectController.java index 8e864cef..102c1522 100644 --- a/src/vooga/fighter/controller/MapSelectController.java +++ b/src/vooga/fighter/controller/MapSelectController.java @@ -1,76 +1,80 @@ package vooga.fighter.controller; import util.Location; import util.input.AlertObject; import util.input.Input; import util.input.InputClassTarget; import util.input.InputMethodTarget; import util.input.PositionObject; import vooga.fighter.controller.Controller; import vooga.fighter.controller.ControllerDelegate; import vooga.fighter.controller.GameInfo; import vooga.fighter.controller.OneVOneController; import vooga.fighter.model.*; import vooga.fighter.model.objects.MouseClickObject; import vooga.fighter.util.Paintable; import vooga.fighter.view.Canvas; import java.awt.Dimension; import java.util.List; import java.util.ResourceBundle; /** * * @author Jack Matteucci edited by Jerry Li */ @InputClassTarget public class MapSelectController extends MenuController { public MapSelectController () { super(); } public void initializeRest(Canvas frame, ControllerDelegate manager, GameInfo gameinfo) { super.initializeRest(frame, manager, gameinfo); } /** * Checks this controller's end conditions */ public void notifyEndCondition(String choice) { removeListener(); + getGameInfo().setMapName(choice); + getManager().notifyEndCondition(NEXT); if(BACK.equals(choice)) getManager().notifyEndCondition(BACK); else if (getMode().getMenuNames().contains(choice)){ getGameInfo().setMapName(choice); getManager().notifyEndCondition(NEXT); } } @InputMethodTarget(name = "continue") public void mouseclick(PositionObject pos) { super.getMode().addObject(new MouseClickObject(pos.getPoint2D())); - notifyEndCondition(getMode().getMenuNames().get(0)); } public void removeListener(){ super.removeListener(); getInput().removeListener(this); } public void checkConditions(){ String choice = getMode().getChoice(); + if(!choice.equals("")){ + notifyEndCondition("1v1"); + } for(String other: getMode().getMenuNames()){ if(other.equals(choice)){ - notifyEndCondition(choice); + notifyEndCondition("1v1"); } } } } diff --git a/src/vooga/fighter/controller/ModeSelectMenuController.java b/src/vooga/fighter/controller/ModeSelectMenuController.java index 491dea63..95a2bf6f 100644 --- a/src/vooga/fighter/controller/ModeSelectMenuController.java +++ b/src/vooga/fighter/controller/ModeSelectMenuController.java @@ -1,82 +1,83 @@ package vooga.fighter.controller; import util.Location; import util.input.AlertObject; import util.input.Input; import util.input.InputClassTarget; import util.input.InputMethodTarget; import util.input.PositionObject; import vooga.fighter.controller.Controller; import vooga.fighter.controller.ControllerDelegate; import vooga.fighter.controller.GameInfo; import vooga.fighter.controller.OneVOneController; import vooga.fighter.model.*; import vooga.fighter.model.objects.MouseClickObject; import vooga.fighter.util.Paintable; import vooga.fighter.view.Canvas; import java.awt.Dimension; import java.util.List; import java.util.ResourceBundle; /** * * @author Jerry Li & Jack Matteucci * */ @InputClassTarget public class ModeSelectMenuController extends MenuController { private ResourceBundle myResources; public ModeSelectMenuController () { super(); + // myResources = } public void initializeRest(Canvas frame, ControllerDelegate manager, GameInfo gameinfo) { super.initializeRest(frame, manager, gameinfo); } /** * Checks this controller's end conditions */ public void notifyEndCondition(String choice) { removeListener(); if(EXIT.equals(choice)){ getManager().exit(); } else if(BACK.equals(choice)){ getManager().notifyEndCondition(BACK); } else { //if(getMode().getMenuNames().contains(choice)){ getGameInfo().setGameMode(choice); - getGameInfo().setNumCharacters(Integer.parseInt(myResources.getString(choice))); + getGameInfo().setNumCharacters(2);//Integer.parseInt(myResources.getString(choice))); getManager().notifyEndCondition(NEXT); } } @InputMethodTarget(name = "continue") public void mouseclick(PositionObject pos) { super.getMode().addObject(new MouseClickObject(pos.getPoint2D())); - notifyEndCondition("test"); } public void removeListener(){ super.removeListener(); getInput().removeListener(this); } public void checkConditions(){ String choice = getMode().getChoice(); + if(!choice.equals("")) notifyEndCondition("1v1"); for(String other: getMode().getMenuNames()){ if(other.equals(choice)){ notifyEndCondition(choice); } } } }
false
false
null
null
diff --git a/src/Piece.java b/src/Piece.java index 85a6043..64f8e92 100644 --- a/src/Piece.java +++ b/src/Piece.java @@ -1,64 +1,64 @@ import java.awt.Image; import java.io.File; import java.io.IOException; import java.util.ArrayList; import javax.imageio.ImageIO; public abstract class Piece { public static final int BLACK = 1; public static final int WHITE = 2; protected int _color; protected boolean _hasMoved; Image _img; public Piece(int color) throws IOException { _color = color; _img = ImageIO.read(new File(getIconFilename())); } public boolean validMove(int currentX, int currentY, int requestedX, int requestedY, Board board) { int i; ArrayList<int[]> moves = allPossibleMoves(currentX, currentY, board); for (i = 0; i < moves.size(); i++) { if (requestedX == moves.get(i)[0] && requestedY == moves.get(i)[1]) { return true; } } return false; } // returns an ArrayList of coordinates. Coordinates are 2 length int arrays. protected abstract ArrayList<int[]> allPossibleMoves(int currentX, int currentY, Board board); public int getColor() { return _color; } public void setMoved(boolean moved) { _hasMoved = moved; } public Image getImage() { return _img; } private String getIconFilename() { String result = ""; if (getColor() == Piece.BLACK) { result += "b"; } else if (getColor() == Piece.WHITE) { result += "w"; } result += this.toString().toLowerCase(); - return "img/" + result + ".png"; + return "../img/" + result + ".png"; } } diff --git a/src/Screen.java b/src/Screen.java index cccd96d..073fff7 100644 --- a/src/Screen.java +++ b/src/Screen.java @@ -1,112 +1,112 @@ import java.awt.*; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.*; public class Screen extends JPanel { private static final long serialVersionUID = 1L; private Image _bg, _selector, _gameOverImg; private Board _board; private int _clickX, _clickY; private boolean _gameOver, _drawSelector; private int _selectorX, _selectorY; public Screen() throws IOException { _gameOver = false; - _bg = ImageIO.read(new File("img/background.png")); - _selector = ImageIO.read(new File("img/selector.png")); - _gameOverImg = ImageIO.read(new File("img/gameover.png")); + _bg = ImageIO.read(new File("../img/background.png")); + _selector = ImageIO.read(new File("../img/selector.png")); + _gameOverImg = ImageIO.read(new File("../img/gameover.png")); _drawSelector = false; _clickX = -1; _clickY = -1; this.addMouseListener(new MouseListener() { public void mouseReleased(MouseEvent e) { setLastClickPos(e.getX(),e.getY()); } public void mousePressed(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseClicked(MouseEvent e) { } }); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); //paint the chess board g.drawImage(_bg, 0, 0, null); //paint the selector if (_drawSelector && !_board.emptyAt(_selectorX/Cell.SIZE, _selectorY/Cell.SIZE)) { g.drawImage(_selector, _selectorX, _selectorY, null); } //paint the pieces int x, y; for (y = 0; y < Board.SIZE; y++) { for (x = 0; x < Board.SIZE; x++) { if (!_board.emptyAt(x, y)) { g.drawImage(_board.getPieceImageAt(x, y), x*Cell.SIZE, y*Cell.SIZE, null); } } } if (_gameOver) { x = getWidth()/2 - _gameOverImg.getWidth(null)/2; y = getHeight()/2 - _gameOverImg.getHeight(null)/2; g.drawImage(_gameOverImg, x, y, null); } } public void setBoard(Board chessBoard) { _board = chessBoard; } private void setLastClickPos(int x, int y) { _clickX = x; _clickY = y; } public int[] getLastClickPos() { int[] result = new int[]{_clickX, _clickY}; _clickX = -1; _clickY = -1; return result; } public void displayGameOver() { _gameOver = true; } public void addSelector(int x, int y) { _drawSelector = true; _selectorX = x*Cell.SIZE; _selectorY = y*Cell.SIZE; repaint(); } public void removeSelector() { _drawSelector = false; repaint(); } }
false
false
null
null
diff --git a/media/src/org/riotfamily/media/processing/FFmpeg.java b/media/src/org/riotfamily/media/processing/FFmpeg.java index cde166fbb..6d0b645f2 100644 --- a/media/src/org/riotfamily/media/processing/FFmpeg.java +++ b/media/src/org/riotfamily/media/processing/FFmpeg.java @@ -1,123 +1,123 @@ /* 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.riotfamily.media.processing; import java.io.File; import java.io.IOException; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.riotfamily.common.io.IOUtils; import org.riotfamily.media.meta.VideoMetaData; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.InitializingBean; import org.springframework.util.Assert; /** * @author Felix Gnass [fgnass at neteye dot de] * @since 7.0 */ public class FFmpeg implements InitializingBean { private Logger log = LoggerFactory.getLogger(FFmpeg.class); private static final Pattern DURATION_PATTERN = Pattern.compile( "Duration: (\\d\\d):(\\d\\d):(\\d\\d)"); private static final Pattern BITRATE_PATTERN = Pattern.compile( "bitrate: (\\d+) kb/s"); private static final Pattern VIDEO_PATTERN = Pattern.compile( - "Video: (\\w+).*?(\\d+)x(\\d+).*?(\\d+\\.?\\d+?) (fps|tb\\(r\\)|tbr)"); + "Video: (\\w+).*?(\\d+)x(\\d+).*?(\\d+\\.?\\d?k?) (fps|tb\\(r\\)|tbr)"); private static final Pattern AUDIO_PATTERN = Pattern.compile( "Audio: (\\w+).*?(\\d+) Hz, (mono|stereo)"); private String command; private String version; public void setCommand(String command) { this.command = command; } private String getDefaultCommand() { String os = System.getProperty("os.name"); return os.startsWith("Windows") ? "ffmpeg.exe" : "ffmpeg"; } public void afterPropertiesSet() { try { if (command == null) { command = getDefaultCommand(); } log.info("Looking for FFmpeg binary: " + command); version = IOUtils.exec(command, "-version"); log.info(version); } catch (IOException e) { log.warn("FFmpeg not found."); } } public boolean isAvailable() { return version != null; } public String getVersion() { return this.version; } public String invoke(List<String> args) throws IOException { Assert.state(isAvailable(), "FFmpeg binary '" + command + "' not found in path."); return IOUtils.exec(command, args); } public VideoMetaData identify(File file) throws IOException { String out = IOUtils.exec(command, "-i", file.getAbsolutePath()); VideoMetaData meta = new VideoMetaData(); Matcher m = DURATION_PATTERN.matcher(out); if (m.find()) { int hh = Integer.parseInt(m.group(1)); int mm = Integer.parseInt(m.group(2)); int ss = Integer.parseInt(m.group(3)); meta.setDuration(hh * 60 * 60 + mm * 60 + ss); } m = BITRATE_PATTERN.matcher(out); if (m.find()) { meta.setBps(Integer.parseInt(m.group(1))); } m = VIDEO_PATTERN.matcher(out); if (m.find()) { meta.setVideoCodec(m.group(1)); meta.setWidth(Integer.parseInt(m.group(2))); meta.setHeight(Integer.parseInt(m.group(3))); meta.setFps(Float.parseFloat(m.group(4))); } m = AUDIO_PATTERN.matcher(out); if (m.find()) { meta.setAudioCodec(m.group(1)); meta.setSamplingRate(Integer.parseInt(m.group(2))); meta.setStereo("stereo".equals(m.group(3))); } return meta; } }
true
false
null
null
diff --git a/test/org/jcouchdb/db/LocalDatabaseTestCase.java b/test/org/jcouchdb/db/LocalDatabaseTestCase.java index 4446935..728f2b8 100644 --- a/test/org/jcouchdb/db/LocalDatabaseTestCase.java +++ b/test/org/jcouchdb/db/LocalDatabaseTestCase.java @@ -1,680 +1,679 @@ package org.jcouchdb.db; -import static org.easymock.EasyMock.contains; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.io.IOUtils; import org.apache.log4j.Logger; import org.jcouchdb.document.Attachment; import org.jcouchdb.document.BaseDocument; import org.jcouchdb.document.DesignDocument; import org.jcouchdb.document.Document; import org.jcouchdb.document.DocumentInfo; import org.jcouchdb.document.ValueAndDocumentRow; import org.jcouchdb.document.ValueRow; import org.jcouchdb.document.View; import org.jcouchdb.document.ViewAndDocumentsResult; import org.jcouchdb.document.ViewResult; import org.jcouchdb.exception.DataAccessException; +import org.jcouchdb.exception.DocumentValidationException; import org.jcouchdb.exception.NotFoundException; import org.jcouchdb.exception.UpdateConflictException; -import org.jcouchdb.exception.DocumentValidationException; +import org.junit.Ignore; import org.junit.Test; import org.svenson.JSON; /** * Runs tests against a real couchdb database running on localhost * * @author shelmberger */ public class LocalDatabaseTestCase { private JSON jsonGenerator = new JSON(); private final static String COUCHDB_HOST = "localhost"; private final static int COUCHDB_PORT = Server.DEFAULT_PORT; private static final String TESTDB_NAME = "jcouchdb_test"; private static final String MY_FOO_DOC_ID = "myFoo/DocId"; private static final String BY_VALUE_FUNCTION = "function(doc) { if (doc.type == 'foo') { emit(doc.value,doc); } }"; private static final String COMPLEX_KEY_FUNCTION = "function(doc) { if (doc.type == 'foo') { emit([1,{\"value\":doc.value}],doc); } }"; protected static Logger log = Logger.getLogger(LocalDatabaseTestCase.class); public static Database createDatabaseForTest() { Server server = new ServerImpl(COUCHDB_HOST, COUCHDB_PORT); List<String> databases = server.listDatabases(); log.debug("databases = " + databases); if (!databases.contains(TESTDB_NAME)) { server.createDatabase(TESTDB_NAME); } return new Database(server,TESTDB_NAME); } @Test public void recreateTestDatabase() { try { Server server = new ServerImpl(COUCHDB_HOST, COUCHDB_PORT); List<String> databases = server.listDatabases(); log.debug("databases = " + databases); if (databases.contains(TESTDB_NAME)) { server.deleteDatabase(TESTDB_NAME); } server.createDatabase(TESTDB_NAME); } catch (RuntimeException e) { log.error("", e); } } @Test public void createTestDocuments() { Database db = createDatabaseForTest(); FooDocument foo = new FooDocument("bar!"); assertThat(foo.getId(), is(nullValue())); assertThat(foo.getRevision(), is(nullValue())); db.createDocument(foo); assertThat(foo.getId(), is(notNullValue())); assertThat(foo.getRevision(), is(notNullValue())); foo = new FooDocument("baz!"); foo.setProperty("baz2", "Some test value"); db.createDocument(foo); log.debug("-- resetted database ----------------------------------"); } @Test public void thatMapDocumentsWork() { Database db = createDatabaseForTest(); Map<String,String> doc = new HashMap<String, String>(); doc.put("foo", "value for the foo attribute"); doc.put("bar", "value for the bar attribute"); db.createDocument(doc); final String id = doc.get("_id"); assertThat(id, is(notNullValue())); assertThat(doc.get("_rev"), is(notNullValue())); doc = db.getDocument(Map.class, id); assertThat(doc.get("foo"), is("value for the foo attribute")); assertThat(doc.get("bar"), is("value for the bar attribute")); } @Test public void thatCreateNamedDocWorks() { FooDocument doc = new FooDocument("qux"); doc.setId(MY_FOO_DOC_ID); Database db = createDatabaseForTest(); db.createDocument(doc); assertThat(doc.getId(), is(MY_FOO_DOC_ID)); assertThat(doc.getRevision(), is(notNullValue())); } @Test public void thatUpdateDocWorks() { Database db = createDatabaseForTest(); FooDocument doc = db.getDocument(FooDocument.class, MY_FOO_DOC_ID); assertThat(doc.getValue(), is("qux")); doc.setValue("qux!"); db.updateDocument(doc); doc = db.getDocument(FooDocument.class, MY_FOO_DOC_ID); assertThat(doc.getValue(), is("qux!")); } @Test(expected = UpdateConflictException.class) public void thatUpdateConflictWorks() { FooDocument doc = new FooDocument("qux"); doc.setId(MY_FOO_DOC_ID); new Database(COUCHDB_HOST, COUCHDB_PORT, TESTDB_NAME).createDocument(doc); } @Test public void testGetAll() { Database db = createDatabaseForTest(); ViewResult<Map> result = db.listDocuments(null,null); List<ValueRow<Map>> rows = result.getRows(); String json = jsonGenerator.forValue(rows); System.out.println("rows = " + json); assertThat(rows.size(), is(4)); } @Test public void testGetAllBySeq() { Database db = createDatabaseForTest(); ViewResult<Map> result = db.listDocumentsByUpdateSequence(null,null); List<ValueRow<Map>> rows = result.getRows(); assertThat(rows.size(), is(4)); assertThat(rows.get(0).getKey().toString(), is("1")); assertThat(rows.get(1).getKey().toString(), is("2")); assertThat(rows.get(2).getKey().toString(), is("3")); assertThat(rows.get(3).getKey().toString(), is("5")); // this one was updated once String json = jsonGenerator.forValue(rows); log.debug("rows = " + json); } @Test public void testCreateDesignDocument() { Database db = createDatabaseForTest(); DesignDocument designDocument = new DesignDocument("foo"); designDocument.addView("byValue", new View(BY_VALUE_FUNCTION)); designDocument.addView("complex", new View(COMPLEX_KEY_FUNCTION)); log.debug("DESIGN DOC = " + jsonGenerator.dumpObjectFormatted(designDocument)); db.createDocument(designDocument); } @Test public void getDesignDocument() { Database db = createDatabaseForTest(); DesignDocument doc = db.getDesignDocument("foo"); log.debug(jsonGenerator.dumpObjectFormatted(doc)); assertThat(doc, is(notNullValue())); assertThat(doc.getId(), is(DesignDocument.PREFIX + "foo")); assertThat(doc.getViews().get("byValue").getMap(), is(BY_VALUE_FUNCTION)); } @Test public void queryDocuments() { Database db = createDatabaseForTest(); ViewResult<FooDocument> result = db.queryView("foo/byValue", FooDocument.class, null, null); assertThat(result.getRows().size(), is(3)); FooDocument doc = result.getRows().get(0).getValue(); assertThat(doc, is(notNullValue())); assertThat(doc.getValue(), is("bar!")); doc = result.getRows().get(1).getValue(); assertThat(doc, is(notNullValue())); assertThat(doc.getValue(), is("baz!")); doc = result.getRows().get(2).getValue(); assertThat(doc, is(notNullValue())); assertThat(doc.getId(), is(MY_FOO_DOC_ID)); assertThat(doc.getValue(), is("qux!")); } @Test public void queryViewAndDocuments() { Database db = createDatabaseForTest(); ViewAndDocumentsResult<Object,FooDocument> result = db.queryViewAndDocuments("foo/byValue", Object.class, FooDocument.class, null, null); assertThat(result.getRows().size(), is(3)); FooDocument doc = result.getRows().get(0).getDocument(); assertThat(doc, is(notNullValue())); assertThat(doc.getValue(), is("bar!")); doc = result.getRows().get(1).getDocument(); assertThat(doc, is(notNullValue())); assertThat(doc.getValue(), is("baz!")); doc = result.getRows().get(2).getDocument(); assertThat(doc, is(notNullValue())); assertThat(doc.getId(), is(MY_FOO_DOC_ID)); assertThat(doc.getValue(), is("qux!")); } @Test public void queryDocumentsWithComplexKey() { Database db = createDatabaseForTest(); ViewResult<FooDocument> result = db.queryView("foo/complex", FooDocument.class, null, null); assertThat(result.getRows().size(), is(3)); ValueRow<FooDocument> row = result.getRows().get(0); assertThat(jsonGenerator.forValue(row.getKey()), is("[1,{\"value\":\"bar!\"}]")); } @Test public void thatGetDocumentWorks() { Database db = createDatabaseForTest(); FooDocument doc = db.getDocument(FooDocument.class, MY_FOO_DOC_ID); assertThat(doc.getId(), is(MY_FOO_DOC_ID)); assertThat(doc.getRevision(), is(notNullValue())); assertThat(doc.getValue(), is("qux!")); log.debug(jsonGenerator.dumpObjectFormatted(doc)); } @Test public void thatAdHocViewsWork() { Database db = createDatabaseForTest(); ViewResult<FooDocument> result = db.queryAdHocView(FooDocument.class, "{ \"map\" : \"function(doc) { if (doc.baz2 == 'Some test value') emit(null,doc); } \" }", null, null); assertThat(result.getRows().size(), is(1)); FooDocument doc = result.getRows().get(0).getValue(); assertThat((String)doc.getProperty("baz2"), is("Some test value")); } @Test public void thatNonDocumentFetchingWorks() { Database db = createDatabaseForTest(); NotADocument doc = db.getDocument(NotADocument.class, MY_FOO_DOC_ID); assertThat(doc.getId(), is(MY_FOO_DOC_ID)); assertThat(doc.getRevision(), is(notNullValue())); assertThat((String)doc.getProperty("value"), is("qux!")); log.debug(jsonGenerator.dumpObjectFormatted(doc)); doc.setProperty("value", "changed"); db.updateDocument(doc); NotADocument doc2 = db.getDocument(NotADocument.class, MY_FOO_DOC_ID); assertThat((String)doc2.getProperty("value"), is("changed")); } @Test public void thatBulkCreationWorks() { Database db = createDatabaseForTest(); List<Document> docs = new ArrayList<Document>(); docs.add(new FooDocument("doc-1")); docs.add(new FooDocument("doc-2")); docs.add(new FooDocument("doc-3")); List<DocumentInfo> infos = db.bulkCreateDocuments(docs); assertThat(infos.size(), is(3)); } @Test public void thatBulkCreationWithIdsWorks() { Database db = createDatabaseForTest(); List<Document> docs = new ArrayList<Document>(); FooDocument fooDocument = new FooDocument("doc-2"); fooDocument.setId("second-foo-with-id"); docs.add(new FooDocument("doc-1")); docs.add(fooDocument); FooDocument fd2 = new FooDocument("doc-3"); fd2.setId(MY_FOO_DOC_ID); docs.add(fd2); List<DocumentInfo> infos = db.bulkCreateDocuments(docs); assertThat(infos.size(), is(3)); assertThat(infos.get(0).getId().length(), is(greaterThan(0))); assertThat(infos.get(1).getId(), is("second-foo-with-id")); // conflict results in error and reason being set assertThat(infos.get(2).getError().length(), is(greaterThan(0))); assertThat(infos.get(2).getReason().length(), is(greaterThan(0))); } @Test(expected=UpdateConflictException.class) public void thatUpdateConflictsWork() { FooDocument foo = new FooDocument("value foo"); FooDocument foo2 = new FooDocument("value foo2"); foo.setId("update_conflict"); foo2.setId("update_conflict"); Database db = createDatabaseForTest(); db.createDocument(foo); db.createDocument(foo2); } @Test public void thatDeleteWorks() { FooDocument foo = new FooDocument("a document"); Database db = createDatabaseForTest(); db.createDocument(foo); assertThat(foo.getId(), is ( notNullValue())); FooDocument foo2 = db.getDocument(FooDocument.class, foo.getId()); assertThat(foo.getValue(), is(foo2.getValue())); db.delete(foo); try { db.getDocument(FooDocument.class, foo.getId()); throw new IllegalStateException("document shouldn't be there anymore"); } catch(NotFoundException nfe) { // yay! } } @Test(expected = DataAccessException.class) public void thatDeleteFailsIfWrong() { Database db = createDatabaseForTest(); db.delete("fakeid", "fakrev"); } private int valueCount(ViewResult<FooDocument> viewResult, String value) { int cnt = 0; for (ValueRow<FooDocument> row : viewResult.getRows()) { if (row.getValue().getValue().equals(value)) { cnt++; } } return cnt; } @Test public void thatAttachmentHandlingWorks() throws UnsupportedEncodingException { final String attachmentContent = "The quick brown fox jumps over the lazy dog."; FooDocument fooDocument = new FooDocument("foo with attachment"); fooDocument.addAttachment("test", new Attachment("text/plain", attachmentContent.getBytes())); Database db = createDatabaseForTest(); db.createDocument(fooDocument); String id = fooDocument.getId(); // re-read document fooDocument = db.getDocument(FooDocument.class, id); Attachment attachment = fooDocument.getAttachments().get("test"); assertThat(attachment, is(notNullValue())); assertThat(attachment.isStub(), is(true)); assertThat(attachment.getContentType(), is("text/plain")); assertThat(attachment.getLength(), is(44l)); String content = new String(db.getAttachment(id, "test")); assertThat(content, is(attachmentContent)); String newRev = db.updateAttachment(fooDocument.getId(), fooDocument.getRevision(), "test", "text/plain", (attachmentContent+"!!").getBytes()); assertThat(newRev, is(notNullValue())); assertThat(newRev.length(), is(greaterThan(0))); content = new String(db.getAttachment(id, "test")); assertThat(content, is(attachmentContent+"!!")); newRev = db.deleteAttachment(fooDocument.getId(), newRev, "test"); assertThat(newRev, is(notNullValue())); assertThat(newRev.length(), is(greaterThan(0))); try { content = new String(db.getAttachment(id, "test")); throw new IllegalStateException("attachment should be gone by now"); } catch(NotFoundException e) { // yay! } newRev = db.createAttachment(fooDocument.getId(), newRev, "test", "text/plain", "TEST".getBytes()); assertThat(newRev, is(notNullValue())); assertThat(newRev.length(), is(greaterThan(0))); content = new String(db.getAttachment(id, "test")); assertThat(content, is("TEST")); } @Test public void thatViewKeyQueryingFromAllDocsWorks() { Database db = createDatabaseForTest(); ViewResult<Map> result = db.queryByKeys(Map.class, Arrays.asList(MY_FOO_DOC_ID,"second-foo-with-id"), null, null); assertThat(result.getRows().size(), is(2)); assertThat(result.getRows().get(0).getId(), is(MY_FOO_DOC_ID)); assertThat(result.getRows().get(1).getId(), is("second-foo-with-id")); } @Test public void thatViewKeyQueryingFromAllDocsWorks2() { Database db = createDatabaseForTest(); ViewResult<Map> result = db.queryByKeys(Map.class, Arrays.asList(MY_FOO_DOC_ID,"second-foo-with-id"), null, null); assertThat(result.getRows().size(), is(2)); assertThat(result.getRows().get(0).getId(), is(MY_FOO_DOC_ID)); assertThat(result.getRows().get(1).getId(), is("second-foo-with-id")); } @Test public void thatViewKeyQueryingWorks() { Database db = createDatabaseForTest(); ViewResult<FooDocument> result = db.queryViewByKeys("foo/byValue", FooDocument.class, Arrays.asList("doc-1","doc-2"), null, null); assertThat(result.getRows().size(), is(4)); assertThat( valueCount(result,"doc-1"), is(2)); assertThat( valueCount(result,"doc-2"), is(2)); } @Test public void thatViewAndDocumentQueryingWorks() { Database db = createDatabaseForTest(); ViewAndDocumentsResult<Object,FooDocument> result = db.queryViewAndDocumentsByKeys("foo/byValue", Object.class, FooDocument.class, Arrays.asList("doc-1"), null, null); List<ValueAndDocumentRow<Object, FooDocument>> rows = result.getRows(); assertThat(rows.size(), is(2)); ValueAndDocumentRow<Object, FooDocument> row = rows.get(0); assertThat(row.getDocument(), is(notNullValue())); assertThat(row.getDocument().getValue(), is("doc-1")); row = rows.get(1); assertThat(row.getDocument(), is(notNullValue())); assertThat(row.getDocument().getValue(), is("doc-1")); } @Test public void testPureBaseDocumentAccess() { Database db = createDatabaseForTest(); BaseDocument newdoc = new BaseDocument(); final String value = "baz403872349"; newdoc.setProperty("foo",value); // same as JSON: { foo: "baz..." } assertThat(newdoc.getId(), is(nullValue())); assertThat(newdoc.getRevision(), is(nullValue())); db.createDocument(newdoc); // auto-generated id given by the database assertThat(newdoc.getId().length(), is(greaterThan(0))); assertThat(newdoc.getRevision().length(), is(greaterThan(0))); BaseDocument doc = db.getDocument(BaseDocument.class, newdoc.getId()); assertThat((String)doc.getProperty("foo"), is(value)); } @Test public void testAttachmentStreaming() throws IOException { Database db = createDatabaseForTest(); final String docId = "attachmentStreamingDoc"; final String content = "Streaming test."; final String content2 = "Streaming test 2."; byte[] data = content.getBytes(); String revision = db.createAttachment(docId, null, "test.txt", "text/plain", new ByteArrayInputStream(data), data.length); assertThat(revision.length(), is(greaterThan(0))); Response resp = db.getAttachmentResponse(docId, "test.txt"); InputStream is = resp.getInputStream(); assertThat(new String(IOUtils.toByteArray(is)), is(content)); resp.destroy(); byte[] data2 = content2.getBytes(); revision = db.updateAttachment(docId, revision, "test.txt", "text/plain", new ByteArrayInputStream(data2), data2.length); resp = db.getAttachmentResponse(docId, "test.txt"); is = resp.getInputStream(); assertThat(new String(IOUtils.toByteArray(is)), is(content2)); resp.destroy(); } @Test public void testValidation() { String fn = "function(newDoc, oldDoc, userCtx){\n" + " if (newDoc.validationTestField && newDoc.validationTestField !== '123') {\n" + " throw({'forbidden':'not 123'});\n" + " }\n" + "}"; DesignDocument designDoc = new DesignDocument("validate_test"); designDoc.setValidateOnDocUpdate(fn); Database db = createDatabaseForTest(); assertThat(designDoc.getRevision(), is(nullValue())); db.createDocument(designDoc); assertThat(designDoc.getRevision(), is(notNullValue())); BaseDocument doc = new BaseDocument(); doc.setProperty("validationTestField", "123"); assertThat(doc.getRevision(), is(nullValue())); db.createDocument(doc); assertThat(doc.getRevision(), is(notNullValue())); doc.setProperty("validationTestField", "invalid"); DocumentValidationException e = null; try { db.updateDocument(doc); } catch(DocumentValidationException e2) { e = e2; } assertThat(e, is(notNullValue())); assertThat(e.getReason(), is("not 123")); assertThat(e.getError(), is("forbidden")); } @Test @Ignore public void thatHandlingHugeAttachmentsWorks() { Database db = createDatabaseForTest(); BaseDocument doc = new BaseDocument(); db.createDocument(doc); long length = (long)(Runtime.getRuntime().maxMemory() * 1.1); InputStream is = new SizedInputStreamMock((byte)'A', length); db.createAttachment(doc.getId(), doc.getRevision(), "hugeAttachment.txt", "text/plain", is, length); doc = db.getDocument(BaseDocument.class, doc.getId()); Map<String, Attachment> attachments = doc.getAttachments(); assertThat(attachments.size(), is(1)); Attachment attachment = attachments.get("hugeAttachment.txt"); assertThat(attachment, is(notNullValue())); assertThat(attachment.getLength(), is(length)); assertThat(attachment.getContentType(), is("text/plain")); assertThat(attachment.isStub(), is(true)); } }
false
false
null
null
diff --git a/src/main/java/com/jayway/maven/plugins/android/AndroidNdk.java b/src/main/java/com/jayway/maven/plugins/android/AndroidNdk.java index 73e19f3e..c1cbff08 100644 --- a/src/main/java/com/jayway/maven/plugins/android/AndroidNdk.java +++ b/src/main/java/com/jayway/maven/plugins/android/AndroidNdk.java @@ -1,63 +1,86 @@ /* * 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.jayway.maven.plugins.android; import java.io.*; import com.jayway.maven.plugins.android.phase05compile.NdkBuildMojo; +import org.apache.commons.lang.SystemUtils; +import org.apache.maven.plugin.MojoExecutionException; /** * Represents an Android NDK. * * @author Johan Lindquist <[email protected]> */ public class AndroidNdk { public static final String PROPER_NDK_HOME_DIRECTORY_MESSAGE = "Please provide a proper Android NDK directory path as configuration parameter <ndk><path>...</path></ndk> in the plugin <configuration/>. As an alternative, you may add the parameter to commandline: -Dandroid.ndk.path=... or set environment variable " + NdkBuildMojo.ENV_ANDROID_NDK_HOME + "."; private final File ndkPath; public AndroidNdk( File ndkPath ) { assertPathIsDirectory( ndkPath ); this.ndkPath = ndkPath; } private void assertPathIsDirectory( final File path ) { if ( path == null ) { throw new InvalidNdkException(PROPER_NDK_HOME_DIRECTORY_MESSAGE); } if ( !path.isDirectory() ) { throw new InvalidNdkException( "Path \"" + path + "\" is not a directory. " + PROPER_NDK_HOME_DIRECTORY_MESSAGE); } } - public String getStripper(String toolchain) - { - // LINUX : $NDK_PATH/toolchains/arm-linux-androideabi-4.4.3/prebuilt/linux-x86/bin/arm-linux-androideabi-strip - // WINDOWS : $NDK_PATH/toolchains/arm-linux-androideabi-4.4.3/prebuilt/windows/bin/arm-linux-androideabi-strip.exe - // FIXME: Must take into consideration windows here as well ... - return new File( ndkPath, "toolchains/" + toolchain + "/prebuilt/linux-x86/bin/arm-linux-androideabi-strip" ).getAbsolutePath(); + public String getStripper(String toolchain) throws MojoExecutionException { + final File stripper; + if ( SystemUtils.IS_OS_LINUX) { + stripper = new File( ndkPath, "toolchains/" + toolchain + "/prebuilt/linux-x86/bin/arm-linux-androideabi-strip" ); + } + else if (SystemUtils.IS_OS_WINDOWS) { + stripper = new File( ndkPath, "toolchains/" + toolchain + "/prebuilt/windows/bin/arm-linux-androideabi-strip.exe" ); + } + else if (SystemUtils.IS_OS_MAC || SystemUtils.IS_OS_MAC_OSX) { + stripper = new File( ndkPath, "toolchains/" + toolchain + "/prebuilt/darwin-x86/bin/arm-linux-androideabi-strip" ); + } + else { + throw new MojoExecutionException( "Could not resolve stripper for current OS: " + SystemUtils.OS_NAME ); + } + + // Some basic validation + if (!stripper.exists()) { + throw new MojoExecutionException( "Strip binary " + stripper.getAbsolutePath() + " does not exist, please double check the toolchain and OS used" ); + } + + // We should be good to go + return stripper.getAbsolutePath(); } /** * Returns the complete path for the ndk-build tool, based on this NDK. * * @return the complete path as a <code>String</code>, including the tool's filename. */ public String getNdkBuildPath() { - return new File( ndkPath, "/ndk-build" ).getAbsolutePath(); + if (SystemUtils.IS_OS_WINDOWS) { + return new File( ndkPath, "/ndk-build.cmd" ).getAbsolutePath(); + } + else { + return new File( ndkPath, "/ndk-build" ).getAbsolutePath(); + } } } \ No newline at end of file
false
false
null
null
diff --git a/src/main/java/com/censoredsoftware/demigods/conversation/Prayer.java b/src/main/java/com/censoredsoftware/demigods/conversation/Prayer.java index 8aa3ebb8..1bafb496 100644 --- a/src/main/java/com/censoredsoftware/demigods/conversation/Prayer.java +++ b/src/main/java/com/censoredsoftware/demigods/conversation/Prayer.java @@ -1,1237 +1,1237 @@ package com.censoredsoftware.demigods.conversation; import java.lang.reflect.Field; import java.util.List; import java.util.Map; import java.util.UUID; import org.apache.commons.lang.StringUtils; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.conversations.*; import org.bukkit.entity.Entity; import org.bukkit.entity.ExperienceOrb; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.block.Action; import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import com.censoredsoftware.demigods.Demigods; import com.censoredsoftware.demigods.Elements; import com.censoredsoftware.demigods.data.DataManager; import com.censoredsoftware.demigods.deity.Deity; import com.censoredsoftware.demigods.helper.ListedConversation; import com.censoredsoftware.demigods.language.Translation; import com.censoredsoftware.demigods.location.DLocation; import com.censoredsoftware.demigods.player.DCharacter; import com.censoredsoftware.demigods.player.DPlayer; import com.censoredsoftware.demigods.player.Notification; import com.censoredsoftware.demigods.structure.Structure; import com.censoredsoftware.demigods.util.*; import com.google.common.collect.Lists; import com.google.common.collect.Maps; @SuppressWarnings("unchecked") public class Prayer implements ListedConversation { @Override public org.bukkit.event.Listener getUniqueListener() { return new Listener(); } /** * Defines categories that can be used during prayer. */ public enum Menu { CONFIRM_FORSAKE('F', new ConfirmForsake()), CANCEL_FORSAKE('X', new CancelForsake()), CONFIRM_CHARACTER('C', new ConfirmCharacter()), CREATE_CHARACTER('1', new CreateCharacter()), VIEW_CHARACTERS('2', new ViewCharacters()), VIEW_WARPS('3', new ViewWarps()), FORSAKE_CHARACTER('4', new Forsake()), VIEW_NOTIFICATIONS('5', new ViewNotifications()); private final char id; private final Elements.Conversations.Category category; private Menu(char id, Elements.Conversations.Category category) { this.id = id; this.category = category; } public char getId() { return this.id; } public Elements.Conversations.Category getCategory() { return this.category; } public static Menu getFromId(char id) { for(Menu menu : Menu.values()) if(menu.getId() == id) return menu; return null; } } @Override public Conversation startMenu(Player player) { return startPrayer(player); } public static Conversation startPrayer(Player player) { try { Map<Object, Object> conversationContext = Maps.newHashMap(); if(!Demigods.isRunningSpigot()) { // Compatibility with vanilla Bukkit Field sessionDataField = ConversationContext.class.getDeclaredField("sessionData"); sessionDataField.setAccessible(true); if(DataManager.hasKeyTemp(player.getName(), "prayer_context")) conversationContext = (Map<Object, Object>) sessionDataField.get(DataManager.getValueTemp(player.getName(), "prayer_context")); } else { // Grab the context Map if(DataManager.hasKeyTemp(player.getName(), "prayer_context")) conversationContext.putAll(((ConversationContext) DataManager.getValueTemp(player.getName(), "prayer_context")).getAllSessionData()); } // Build the conversation and begin Conversation prayerConversation = Demigods.conversation.withEscapeSequence("/exit").withLocalEcho(false).withInitialSessionData(conversationContext).withFirstPrompt(new StartPrayer()).buildConversation(player); prayerConversation.begin(); return prayerConversation; } catch(NoSuchFieldException ignored) {} catch(IllegalAccessException ignored) {} return null; } // Main prayer menu static class StartPrayer extends ValidatingPrompt { @Override public String getPromptText(ConversationContext context) { // Define variables Player player = (Player) context.getForWhom(); // Clear chat Demigods.message.clearRawChat(player); // Send NoGrief menu Demigods.message.clearRawChat(player); player.sendRawMessage(ChatColor.AQUA + " -- Prayer Menu --------------------------------------"); player.sendRawMessage(" "); for(String message : Demigods.language.getTextBlock(Translation.Text.PRAYER_INTRO)) player.sendRawMessage(message); player.sendRawMessage(" "); player.sendRawMessage(ChatColor.GRAY + " To begin, choose an option by entering its number in the chat:"); player.sendRawMessage(" "); for(Menu menu : Menu.values()) if(menu.getCategory().canUse(context)) player.sendRawMessage(ChatColor.GRAY + " [" + menu.getId() + ".] " + menu.getCategory().getChatName()); return ""; } @Override protected boolean isInputValid(ConversationContext context, String message) { try { Menu menu = Menu.getFromId(Character.toUpperCase(message.charAt(0))); return menu != null && menu.getCategory().canUse(context); } catch(Exception ignored) {} return false; } @Override protected Prompt acceptValidatedInput(ConversationContext context, String message) { return Menu.getFromId(Character.toUpperCase(message.charAt(0))).getCategory(); } } // Warps static class ViewWarps extends ValidatingPrompt implements Elements.Conversations.Category { @Override public String getChatName() { return ChatColor.LIGHT_PURPLE + "View Warps " + ChatColor.GRAY + "(& Invites)"; } @Override public boolean canUse(ConversationContext context) { return DPlayer.Util.getPlayer((Player) context.getForWhom()).getCurrent() != null; } @Override public String getPromptText(ConversationContext context) { // Define variables Player player = (Player) context.getForWhom(); DCharacter character = DPlayer.Util.getPlayer((Player) context.getForWhom()).getCurrent(); Demigods.message.clearRawChat(player); player.sendRawMessage(ChatColor.YELLOW + Titles.chatTitle("Viewing Warps & Invites")); player.sendRawMessage(" "); if(character.getMeta().hasWarps() || character.getMeta().hasInvites()) { player.sendRawMessage(ChatColor.LIGHT_PURPLE + " Light purple" + ChatColor.GRAY + " represents the warp(s) at this location."); player.sendRawMessage(" "); for(Map.Entry<String, Object> entry : character.getMeta().getWarps().entrySet()) { Location location = DLocation.Util.load(UUID.fromString(entry.getValue().toString())).toLocation(); player.sendRawMessage((player.getLocation().distance(location) < 8 ? ChatColor.LIGHT_PURPLE : ChatColor.GRAY) + " " + StringUtils.capitalize(entry.getKey().toLowerCase()) + ChatColor.GRAY + " (" + StringUtils.capitalize(location.getWorld().getName().toLowerCase()) + ": " + Math.round(location.getX()) + ", " + Math.round(location.getY()) + ", " + Math.round(location.getZ()) + ")"); } for(Map.Entry<String, Object> entry : character.getMeta().getInvites().entrySet()) { Location location = DLocation.Util.load(UUID.fromString(entry.getValue().toString())).toLocation(); player.sendRawMessage((player.getLocation().distance(location) < 8 ? ChatColor.LIGHT_PURPLE : ChatColor.GRAY) + " " + StringUtils.capitalize(entry.getKey().toLowerCase()) + ChatColor.GRAY + " (" + StringUtils.capitalize(location.getWorld().getName().toLowerCase()) + ": " + Math.round(location.getX()) + ", " + Math.round(location.getY()) + ", " + Math.round(location.getZ()) + ") " + ChatColor.GREEN + "Invited by [ALLAN!!]"); // TODO: Invited by } player.sendRawMessage(" "); player.sendRawMessage(ChatColor.GRAY + " Type " + ChatColor.YELLOW + "new <warp name>" + ChatColor.GRAY + " to create a warp at this Altar,"); player.sendRawMessage(ChatColor.YELLOW + " warp <warp name>" + ChatColor.GRAY + " to teleport to a warp, or " + ChatColor.YELLOW + "delete"); player.sendRawMessage(ChatColor.YELLOW + " <warp name>" + ChatColor.GRAY + " remove a warp. You can also invite a player"); player.sendRawMessage(ChatColor.GRAY + " by using " + ChatColor.YELLOW + "invite <player/character> <warp name>" + ChatColor.GRAY + "."); } else { player.sendRawMessage(ChatColor.RED + " You have no warps or invites!"); player.sendRawMessage(" "); player.sendRawMessage(ChatColor.GRAY + " Type " + ChatColor.YELLOW + "new <warp name>" + ChatColor.GRAY + " to create a warp at this Altar."); } // Display notifications if available if(context.getSessionData("warp_notifications") != null && !((List<Translation.Text>) context.getSessionData("warp_notifications")).isEmpty()) { // Grab the notifications List<Translation.Text> notifications = (List<Translation.Text>) context.getSessionData("warp_notifications"); player.sendRawMessage(" "); // List them for(Translation.Text notification : notifications) player.sendRawMessage(" " + Demigods.language.getText(notification)); // Remove them notifications.clear(); } return ""; } @Override protected boolean isInputValid(ConversationContext context, String message) { // Define variables DCharacter character = DPlayer.Util.getPlayer((Player) context.getForWhom()).getCurrent(); String arg0 = message.split(" ")[0]; String arg1 = message.split(" ").length >= 2 ? message.split(" ")[1] : null; String arg2 = message.split(" ").length >= 3 ? message.split(" ")[2] : null; return message.equalsIgnoreCase("menu") || arg0.equalsIgnoreCase("new") && StringUtils.isAlphanumeric(arg1) && !character.getMeta().getWarps().containsKey(arg1.toLowerCase()) || ((arg0.equalsIgnoreCase("warp") || arg0.equalsIgnoreCase("delete")) && (character.getMeta().getWarps().containsKey(arg1.toLowerCase()) || character.getMeta().getInvites().containsKey(arg1.toLowerCase())) || (arg0.equalsIgnoreCase("invite") && (DCharacter.Util.charExists(arg1) || Bukkit.getOfflinePlayer(arg1) != null && DPlayer.Util.getPlayer(Bukkit.getOfflinePlayer(arg1)).getCurrent() != null) && arg2 != null && character.getMeta().getWarps().containsKey(arg2.toLowerCase()))); } @Override protected Prompt acceptValidatedInput(ConversationContext context, String message) { // Define variables Player player = (Player) context.getForWhom(); DCharacter character = DPlayer.Util.getPlayer((Player) context.getForWhom()).getCurrent(); String arg0 = message.split(" ")[0]; String arg1 = message.split(" ").length >= 2 ? message.split(" ")[1] : null; String arg2 = message.split(" ").length >= 3 ? message.split(" ")[2] : null; // Create and save the notification list context.setSessionData("warp_notifications", Lists.newArrayList()); List<Translation.Text> notifications = (List<Translation.Text>) context.getSessionData("warp_notifications"); Demigods.message.clearRawChat(player); if(message.equalsIgnoreCase("menu")) { // THEY WANT THE MENU!? SOCK IT TO 'EM! return new StartPrayer(); } if(arg0.equalsIgnoreCase("new")) { // Save notification notifications.add(Translation.Text.NOTIFICATION_WARP_CREATED); // Add the warp character.getMeta().addWarp(arg1, player.getLocation()); // Return to view warps return new ViewWarps(); } else if(arg0.equalsIgnoreCase("delete")) { // Save notification notifications.add(Translation.Text.NOTIFICATION_WARP_DELETED); // Remove the warp/invite if(character.getMeta().getWarps().containsKey(arg1.toLowerCase())) character.getMeta().removeWarp(arg1); else if(character.getMeta().getInvites().containsKey(arg1.toLowerCase())) character.getMeta().removeInvite(arg1); // Return to view warps return new ViewWarps(); } else if(arg0.equalsIgnoreCase("invite")) { // Save notification notifications.add(Translation.Text.NOTIFICATION_INVITE_SENT); // Define variables DCharacter invitee = DCharacter.Util.charExists(arg1) ? DCharacter.Util.getCharacterByName(arg1) : DPlayer.Util.getPlayer(Bukkit.getOfflinePlayer(arg1)).getCurrent(); Location warp = DLocation.Util.load(UUID.fromString(character.getMeta().getWarps().get(arg2).toString())).toLocation(); // Add the invite invitee.getMeta().addInvite(character.getName(), warp); // Message the player if they're online if(invitee.getOfflinePlayer().isOnline()) { invitee.getOfflinePlayer().getPlayer().sendMessage(ChatColor.LIGHT_PURPLE + "You've been invited to a warp by " + character.getName() + "!"); invitee.getOfflinePlayer().getPlayer().sendMessage(ChatColor.GRAY + "Go to an Altar to accept this invite."); } // Return to warps menu return new ViewWarps(); } else if(arg0.equalsIgnoreCase("warp")) { // Disable prayer DPlayer.Util.togglePrayingSilent(player, false, true); // Teleport and message if(character.getMeta().getWarps().containsKey(arg1.toLowerCase())) player.teleport(DLocation.Util.load(UUID.fromString(character.getMeta().getWarps().get(arg1.toLowerCase()).toString())).toLocation()); else if(character.getMeta().getInvites().containsKey(arg1.toLowerCase())) { player.teleport(DLocation.Util.load(UUID.fromString(character.getMeta().getInvites().get(arg1.toLowerCase()).toString())).toLocation()); character.getMeta().removeInvite(arg1.toLowerCase()); } player.sendMessage(ChatColor.GRAY + "Teleported to " + ChatColor.LIGHT_PURPLE + StringUtils.capitalize(arg1.toLowerCase()) + ChatColor.GRAY + "."); } return null; } } // Notifications static class ViewNotifications extends ValidatingPrompt implements Elements.Conversations.Category { @Override public String getChatName() { return ChatColor.GREEN + "View Notifications"; } @Override public boolean canUse(ConversationContext context) { DCharacter character = DPlayer.Util.getPlayer((Player) context.getForWhom()).getCurrent(); return character != null && character.getMeta().hasNotifications(); } @Override public String getPromptText(ConversationContext context) { // Define variables Player player = (Player) context.getForWhom(); DCharacter character = DPlayer.Util.getPlayer((Player) context.getForWhom()).getCurrent(); Demigods.message.clearRawChat(player); player.sendRawMessage(ChatColor.YELLOW + Titles.chatTitle("Viewing Notifications")); player.sendRawMessage(" "); for(String string : character.getMeta().getNotifications()) { Notification notification = Notification.Util.load(UUID.fromString(string)); // Determine color ChatColor color; switch(notification.getDanger()) { case GOOD: color = ChatColor.GREEN; break; case BAD: color = ChatColor.RED; break; case NEUTRAL: default: color = ChatColor.YELLOW; break; } // Set expires String expires = notification.hasExpiration() ? ChatColor.GRAY + " (expires in " + Times.getTimeTagged(notification.getExpiration(), true) + ")" : ""; // Send the notification player.sendRawMessage(color + " " + notification.getMessage() + expires); } player.sendRawMessage(" "); for(String message : Demigods.language.getTextBlock(Translation.Text.NOTIFICATIONS_PRAYER_FOOTER)) player.sendRawMessage(message); return ""; } @Override protected boolean isInputValid(ConversationContext context, String message) { return message.equalsIgnoreCase("clear") || message.equalsIgnoreCase("menu"); } @Override protected Prompt acceptValidatedInput(ConversationContext context, String message) { // Define variables DCharacter character = DPlayer.Util.getPlayer((Player) context.getForWhom()).getCurrent(); if(message.equalsIgnoreCase("menu")) { // THEY WANT THE MENU!? SOCK IT TO 'EM! return new StartPrayer(); } else if(message.equalsIgnoreCase("clear")) { // Clear them for(String string : character.getMeta().getNotifications()) Notification.remove(Notification.Util.load(UUID.fromString(string))); character.getMeta().clearNotifications(); // Send to the menu return new StartPrayer(); } return null; } } // Character viewing static class ViewCharacters extends ValidatingPrompt implements Elements.Conversations.Category { @Override public String getChatName() { return ChatColor.YELLOW + "View Characters"; } @Override public boolean canUse(ConversationContext context) { return DPlayer.Util.getPlayer((Player) context.getForWhom()).getCharacters() != null && !DPlayer.Util.getPlayer((Player) context.getForWhom()).getCharacters().isEmpty(); } @Override public String getPromptText(ConversationContext context) { // Define variables Player player = (Player) context.getForWhom(); Demigods.message.clearRawChat(player); player.sendRawMessage(ChatColor.YELLOW + Titles.chatTitle("Viewing Character")); player.sendRawMessage(" "); player.sendRawMessage(ChatColor.LIGHT_PURPLE + " Light purple" + ChatColor.GRAY + " represents your current character."); player.sendRawMessage(" "); for(DCharacter character : DPlayer.Util.getPlayer(player).getCharacters()) player.sendRawMessage((character.isActive() ? ChatColor.LIGHT_PURPLE : ChatColor.GRAY) + " " + character.getName() + ChatColor.GRAY + " [" + character.getDeity().getColor() + character.getDeity().getName() + ChatColor.GRAY + " / Fav: " + Strings.getColor(character.getMeta().getFavor(), character.getMeta().getMaxFavor()) + character.getMeta().getFavor() + ChatColor.GRAY + " (of " + ChatColor.GREEN + character.getMeta().getMaxFavor() + ChatColor.GRAY + ") / Asc: " + ChatColor.GREEN + character.getMeta().getAscensions() + ChatColor.GRAY + "]"); player.sendRawMessage(" "); player.sendRawMessage(ChatColor.GRAY + " Type " + ChatColor.YELLOW + "<character name> info" + ChatColor.GRAY + " for detailed information or"); player.sendRawMessage(ChatColor.GRAY + " type " + ChatColor.YELLOW + "<character name> switch" + ChatColor.GRAY + " to change your current"); player.sendRawMessage(ChatColor.GRAY + " character."); player.sendRawMessage(" "); player.sendRawMessage(ChatColor.GRAY + " Use " + ChatColor.YELLOW + "menu" + ChatColor.GRAY + " to return to the main menu."); return ""; } @Override protected boolean isInputValid(ConversationContext context, String message) { String[] splitMsg = message.split(" "); DPlayer player = DPlayer.Util.getPlayer((Player) context.getForWhom()); DCharacter character = DCharacter.Util.getCharacterByName(splitMsg[0]); return message.equalsIgnoreCase("menu") || splitMsg.length == 2 && (DPlayer.Util.hasCharName((Player) context.getForWhom(), splitMsg[0]) && (splitMsg[1].equalsIgnoreCase("info") || (DPlayer.Util.hasCharName((Player) context.getForWhom(), splitMsg[0]) && splitMsg[1].equalsIgnoreCase("switch")) && (player.getCurrent() == null || !player.getCurrent().getName().equalsIgnoreCase(character.getName())))); } @Override protected Prompt acceptValidatedInput(ConversationContext context, String message) { String arg0 = message.split(" ")[0]; String arg1 = message.split(" ").length == 2 ? message.split(" ")[1] : ""; if(message.equalsIgnoreCase("menu")) return new StartPrayer(); if(arg1.equalsIgnoreCase("info")) { context.setSessionData("viewing_character", arg0); return new DetailedInfo(); } else if(arg1.equalsIgnoreCase("switch")) DPlayer.Util.getPlayer((Player) context.getForWhom()).switchCharacter(DCharacter.Util.getCharacterByName(arg0)); return null; } // Detailed character info class DetailedInfo extends ValidatingPrompt { @Override public String getPromptText(ConversationContext context) { // Define variables Player player = (Player) context.getForWhom(); DCharacter character = DCharacter.Util.getCharacterByName(context.getSessionData("viewing_character").toString()); String status = character.isActive() ? ChatColor.LIGHT_PURPLE + "" + ChatColor.ITALIC + "(Current) " + ChatColor.RESET : ChatColor.RED + "" + ChatColor.ITALIC + "(Inactive) " + ChatColor.RESET; // Clear chat Demigods.message.clearRawChat(player); // Send the player the info player.sendRawMessage(ChatColor.YELLOW + Titles.chatTitle("Viewing Character")); player.sendRawMessage(" "); player.sendRawMessage(" " + status + ChatColor.YELLOW + character.getName() + ChatColor.GRAY + " > Allied to " + character.getDeity().getColor() + character.getDeity() + ChatColor.GRAY + " of the " + ChatColor.GOLD + character.getAlliance() + "s"); player.sendRawMessage(ChatColor.GRAY + " --------------------------------------------------"); player.sendRawMessage(ChatColor.GRAY + " Health: " + ChatColor.WHITE + Strings.getColor(character.getHealth(), 20) + character.getHealth() + ChatColor.GRAY + " (of " + ChatColor.GREEN + 20 + ChatColor.GRAY + ")" + ChatColor.GRAY + " | Hunger: " + ChatColor.WHITE + Strings.getColor(character.getHunger(), 20) + character.getHunger() + ChatColor.GRAY + " (of " + ChatColor.GREEN + 20 + ChatColor.GRAY + ")" + ChatColor.GRAY + " | Exp: " + ChatColor.WHITE + Math.round(character.getExperience())); // TODO: Exp isn't correct. player.sendRawMessage(ChatColor.GRAY + " --------------------------------------------------"); player.sendRawMessage(" "); player.sendRawMessage(ChatColor.GRAY + " Ascensions: " + ChatColor.GREEN + character.getMeta().getAscensions()); player.sendRawMessage(ChatColor.GRAY + " Favor: " + Strings.getColor(character.getMeta().getFavor(), character.getMeta().getMaxFavor()) + character.getMeta().getFavor() + ChatColor.GRAY + " (of " + ChatColor.GREEN + character.getMeta().getMaxFavor() + ChatColor.GRAY + ") " + ChatColor.YELLOW + "+5 every " + Demigods.config.getSettingInt("regeneration.favor") + " seconds"); // TODO: This should change with "perks" (assuming that we implement faster favor regeneration perks). player.sendRawMessage(" "); if(character.isActive()) player.sendRawMessage(ChatColor.GRAY + " Type " + ChatColor.YELLOW + "back" + ChatColor.GRAY + " to return to your characters."); else { player.sendRawMessage(ChatColor.GRAY + " Type " + ChatColor.YELLOW + "back" + ChatColor.GRAY + " to return to your characters or type " + ChatColor.YELLOW + "switch"); player.sendRawMessage(ChatColor.GRAY + " to change your current character to " + character.getDeity().getColor() + character.getName() + ChatColor.GRAY + "."); } return ""; } @Override protected boolean isInputValid(ConversationContext context, String message) { DPlayer player = DPlayer.Util.getPlayer((Player) context.getForWhom()); DCharacter character = DCharacter.Util.getCharacterByName(context.getSessionData("viewing_character").toString()); return message.equalsIgnoreCase("back") || (message.equalsIgnoreCase("switch") && (player.getCurrent() == null || !player.getCurrent().getName().equalsIgnoreCase(character.getName()))); } @Override protected Prompt acceptValidatedInput(ConversationContext context, String message) { if(message.equalsIgnoreCase("back")) return new ViewCharacters(); else if(message.equalsIgnoreCase("switch")) DPlayer.Util.getPlayer((Player) context.getForWhom()).switchCharacter(DCharacter.Util.getCharacterByName(context.getSessionData("viewing_character").toString())); return null; } } } // Deity forsaking static class Forsake extends ValidatingPrompt implements Elements.Conversations.Category { @Override public String getChatName() { return ChatColor.DARK_RED + "Forsake Current Deity"; } @Override public boolean canUse(ConversationContext context) { DCharacter character = DPlayer.Util.getPlayer((Player) context.getForWhom()).getCurrent(); return character != null && ((Player) context.getForWhom()).hasPermission("demigods.basic.forsake") && !DataManager.hasKeyTemp(((Player) context.getForWhom()).getName(), "currently_creating") && !DataManager.hasKeyTemp(((Player) context.getForWhom()).getName(), "currently_forsaking"); } @Override public String getPromptText(ConversationContext context) { // Define variables Player player = (Player) context.getForWhom(); DCharacter character = DPlayer.Util.getPlayer((Player) context.getForWhom()).getCurrent(); Deity deity = character.getDeity(); Demigods.message.clearRawChat(player); player.sendRawMessage(ChatColor.YELLOW + Titles.chatTitle("Forsake Current Deity")); player.sendRawMessage(" "); player.sendRawMessage(" " + deity.getColor() + deity.getName() + ChatColor.GRAY + " is angry with your decision and demands"); player.sendRawMessage(ChatColor.GRAY + " payment from you before forsaking!"); player.sendRawMessage(" "); player.sendRawMessage(ChatColor.GRAY + " Are you sure that you want to forsake " + deity.getColor() + deity.getName() + ChatColor.GRAY + "? " + ChatColor.GRAY + "(y/n)"); return ""; } @Override protected boolean isInputValid(ConversationContext context, String message) { return message.equalsIgnoreCase("y") || message.equalsIgnoreCase("n"); } @Override protected Prompt acceptValidatedInput(ConversationContext context, String message) { if(message.equalsIgnoreCase("n")) return new StartPrayer(); else if(message.equalsIgnoreCase("y")) { // Define variables Player player = (Player) context.getForWhom(); DCharacter character = DPlayer.Util.getPlayer((Player) context.getForWhom()).getCurrent(); Deity deity = character.getDeity(); Demigods.message.clearRawChat(player); player.sendRawMessage(ChatColor.YELLOW + Titles.chatTitle("Forsake Current Deity")); player.sendRawMessage(" "); player.sendRawMessage(" " + deity.getColor() + deity.getName() + ChatColor.GRAY + " requires that you bring the following items"); player.sendRawMessage(ChatColor.GRAY + " before forsaking:"); player.sendRawMessage(" "); for(Map.Entry<Material, Integer> entry : deity.getForsakeItems().entrySet()) player.sendRawMessage(ChatColor.GRAY + " " + Unicodes.rightwardArrow() + " " + ChatColor.YELLOW + entry.getValue() + " " + Strings.beautify(entry.getKey().name()).toLowerCase() + (entry.getValue() > 1 ? "s" : "")); player.sendRawMessage(" "); player.sendRawMessage(ChatColor.GRAY + " Return to an Altar after obtaining these items to finish"); player.sendRawMessage(ChatColor.GRAY + " forsaking."); player.sendRawMessage(" "); player.sendRawMessage(ChatColor.AQUA + " Your prayer has been disabled."); player.sendRawMessage(" "); // Save temporary data, end the conversation, and return DataManager.saveTemp(((Player) context.getForWhom()).getName(), "currently_forsaking", true); DataManager.saveTimed(player.getName(), "currently_forsaking", true, 600); DPlayer.Util.togglePrayingSilent(player, false, true); } return null; } } // Forsaking confirmation static class ConfirmForsake extends ValidatingPrompt implements Elements.Conversations.Category { @Override public String getChatName() { return ChatColor.DARK_RED + "Finish Forsaking"; } @Override public boolean canUse(ConversationContext context) { Player player = (Player) context.getForWhom(); return DataManager.hasKeyTemp(player.getName(), "currently_forsaking") && DataManager.hasTimed(player.getName(), "currently_forsaking"); } @Override public String getPromptText(ConversationContext context) { // Define variables Player player = (Player) context.getForWhom(); Deity deity = DPlayer.Util.getPlayer(player).getCurrent().getDeity(); // Clear chat Demigods.message.clearRawChat(player); // Ask them if they have the items player.sendRawMessage(ChatColor.YELLOW + Titles.chatTitle("Forsaking " + deity.getName())); player.sendRawMessage(" "); player.sendRawMessage(ChatColor.AQUA + " Do you have the following items in your inventory? " + ChatColor.GRAY + "(y/n)"); player.sendRawMessage(" "); for(Map.Entry<Material, Integer> entry : deity.getForsakeItems().entrySet()) player.sendRawMessage(ChatColor.GRAY + " " + Unicodes.rightwardArrow() + " " + ChatColor.YELLOW + entry.getValue() + " " + Strings.beautify(entry.getKey().name()).toLowerCase() + (entry.getValue() > 1 ? "s" : "")); return ""; } @Override protected boolean isInputValid(ConversationContext context, String message) { return message.contains("y") || message.contains("n"); } @Override protected Prompt acceptValidatedInput(ConversationContext context, String message) { Player player = (Player) context.getForWhom(); // Open inventory Inventory inv = Bukkit.getServer().createInventory(player, 9, "Place Items Here"); player.openInventory(inv); return null; } } // Forsaking cancellation static class CancelForsake extends MessagePrompt implements Elements.Conversations.Category { @Override public String getChatName() { return ChatColor.DARK_RED + "Cancel Forsaking"; } @Override public boolean canUse(ConversationContext context) { Player player = (Player) context.getForWhom(); return DataManager.hasKeyTemp(player.getName(), "currently_forsaking") && DataManager.hasTimed(player.getName(), "currently_forsaking"); } @Override public String getPromptText(ConversationContext context) { // Define variables Player player = (Player) context.getForWhom(); Deity deity = DPlayer.Util.getPlayer(player).getCurrent().getDeity(); // Cancel the temp data DataManager.removeTemp(player.getName(), "currently_forsaking"); DataManager.removeTimed(player.getName(), "currently_forsaking"); return ""; } @Override protected Prompt getNextPrompt(ConversationContext context) { return new StartPrayer(); } } // Character creation static class CreateCharacter extends ValidatingPrompt implements Elements.Conversations.Category { @Override public String getChatName() { return ChatColor.GREEN + "Create Character"; } @Override public boolean canUse(ConversationContext context) { return ((Player) context.getForWhom()).hasPermission("demigods.basic.create") && !DataManager.hasKeyTemp(((Player) context.getForWhom()).getName(), "currently_creating") && !DataManager.hasKeyTemp(((Player) context.getForWhom()).getName(), "currently_forsaking"); } @Override public String getPromptText(ConversationContext context) { Demigods.message.clearRawChat((Player) context.getForWhom()); return ChatColor.AQUA + "Continue to character creation?" + ChatColor.GRAY + " (y/n)"; } @Override protected boolean isInputValid(ConversationContext context, String message) { return message.contains("y") || message.contains("n"); } @Override protected ValidatingPrompt acceptValidatedInput(ConversationContext context, String message) { if(message.contains("y")) return new ChooseName(); return new StartPrayer(); } class ChooseName extends ValidatingPrompt { @Override public String getPromptText(ConversationContext context) { Player player = (Player) context.getForWhom(); Demigods.message.clearRawChat(player); player.sendRawMessage(ChatColor.YELLOW + Titles.chatTitle("Creating Character")); player.sendRawMessage(" "); if(context.getSessionData("name_errors") == null) { // No errors, continue player.sendRawMessage(ChatColor.AQUA + " Enter a name: " + ChatColor.GRAY + "(Alpha-Numeric Only)"); } else { // Grab the errors List<Translation.Text> errors = (List<Translation.Text>) context.getSessionData("name_errors"); // List the errors for(Translation.Text error : errors) { player.sendRawMessage(ChatColor.RED + " " + Demigods.language.getText(error).replace("{maxCaps}", String.valueOf(Demigods.config.getSettingInt("character.max_caps_in_name")))); } // Ask for a new name player.sendRawMessage(" "); player.sendRawMessage(ChatColor.AQUA + " Enter a different name: " + ChatColor.GRAY + "(Alpha-Numeric Only)"); } return ""; } @Override protected boolean isInputValid(ConversationContext context, String name) { Player player = (Player) context.getForWhom(); if(name.length() < 4 || name.length() > 14 || !StringUtils.isAlphanumeric(name) || Strings.hasCapitalLetters(name, Demigods.config.getSettingInt("character.max_caps_in_name")) || DPlayer.Util.hasCharName(player, name)) { // Create the list List<Translation.Text> errors = Lists.newArrayList(); // Check the errors if(name.length() < 4 || name.length() >= 14) errors.add(Translation.Text.ERROR_NAME_LENGTH); if(!StringUtils.isAlphanumeric(name)) errors.add(Translation.Text.ERROR_ALPHA_NUMERIC); if(Strings.hasCapitalLetters(name, Demigods.config.getSettingInt("character.max_caps_in_name"))) errors.add(Translation.Text.ERROR_MAX_CAPS); if(DCharacter.Util.charExists(name) || Strings.containsAnyInCollection(name, Demigods.language.getBlackList())) errors.add(Translation.Text.ERROR_CHAR_EXISTS); // Save the info context.setSessionData("name_errors", errors); return false; } else { context.setSessionData("name_errors", null); return true; } } @Override protected ConfirmName acceptValidatedInput(ConversationContext context, String name) { context.setSessionData("chosen_name", name); return new ConfirmName(); } } class ConfirmName extends ValidatingPrompt { @Override public String getPromptText(ConversationContext context) { Demigods.message.clearRawChat((Player) context.getForWhom()); return ChatColor.GRAY + "Are you sure you want to use " + ChatColor.YELLOW + context.getSessionData("chosen_name") + ChatColor.GRAY + "? (y/n)"; } @Override protected boolean isInputValid(ConversationContext context, String message) { return message.contains("y") || message.contains("n"); } @Override protected Prompt acceptValidatedInput(ConversationContext context, String message) { if(message.contains("y")) return new ChooseAlliance(); else { context.setSessionData("chosen_name", null); return new ChooseName(); } } } class ChooseAlliance extends ValidatingPrompt { @Override public String getPromptText(ConversationContext context) { Player player = (Player) context.getForWhom(); Demigods.message.clearRawChat(player); player.sendRawMessage(ChatColor.YELLOW + Titles.chatTitle("Creating Character")); player.sendRawMessage(" "); player.sendRawMessage(ChatColor.AQUA + " Please choose an Alliance: " + ChatColor.GRAY + "(Type in the name of the Alliance)"); player.sendRawMessage(" "); for(String alliance : Deity.Util.getLoadedDeityAlliances()) player.sendRawMessage(ChatColor.GRAY + " " + Unicodes.rightwardArrow() + " " + ChatColor.YELLOW + StringUtils.capitalize(alliance.toLowerCase())); return ""; } @Override protected boolean isInputValid(ConversationContext context, String alliance) { - return Deity.Util.getLoadedDeityAlliances().contains(alliance); + return Deity.Util.getLoadedDeityAlliances().toString().toLowerCase().contains(alliance); } @Override protected Prompt acceptValidatedInput(ConversationContext context, String alliance) { context.setSessionData("chosen_alliance", alliance); return new ConfirmAlliance(); } } class ConfirmAlliance extends ValidatingPrompt { @Override public String getPromptText(ConversationContext context) { Demigods.message.clearRawChat((Player) context.getForWhom()); - return ChatColor.GRAY + "Are you sure you want to use " + ChatColor.YELLOW + StringUtils.capitalize(((String) context.getSessionData("chosen_alliance")).toLowerCase()) + ChatColor.GRAY + "? (y/n)"; + return ChatColor.GRAY + "Are you sure you want to join the " + ChatColor.YELLOW + StringUtils.capitalize(((String) context.getSessionData("chosen_alliance")).toLowerCase()) + "s" + ChatColor.GRAY + "? (y/n)"; } @Override protected boolean isInputValid(ConversationContext context, String message) { return message.contains("y") || message.contains("n"); } @Override protected Prompt acceptValidatedInput(ConversationContext context, String message) { if(message.contains("y")) return new ChooseDeity(); else { context.setSessionData("chosen_alliance", null); return new ChooseAlliance(); } } } class ChooseDeity extends ValidatingPrompt { @Override public String getPromptText(ConversationContext context) { Player player = (Player) context.getForWhom(); Demigods.message.clearRawChat(player); player.sendRawMessage(ChatColor.YELLOW + Titles.chatTitle("Creating Character")); player.sendRawMessage(" "); player.sendRawMessage(ChatColor.AQUA + " Please choose a Deity: " + ChatColor.GRAY + "(Type in the name of the Deity)"); player.sendRawMessage(" "); for(Deity deity : Deity.Util.getAllDeitiesInAlliance((String) context.getSessionData("chosen_alliance"))) if(player.hasPermission(deity.getPermission())) player.sendRawMessage(ChatColor.GRAY + " " + Unicodes.rightwardArrow() + " " + ChatColor.YELLOW + StringUtils.capitalize(deity.getName())); return ""; } @Override protected boolean isInputValid(ConversationContext context, String deityName) { return Deity.Util.getDeity(deityName) != null; } @Override protected Prompt acceptValidatedInput(ConversationContext context, String deityName) { context.setSessionData("chosen_deity", deityName); return new ConfirmDeity(); } } class ConfirmDeity extends ValidatingPrompt { @Override public String getPromptText(ConversationContext context) { Demigods.message.clearRawChat((Player) context.getForWhom()); Deity deity = Deity.Util.getDeity((String) context.getSessionData("chosen_deity")); return ChatColor.GRAY + "Are you sure you want to use " + deity.getColor() + deity.getName() + ChatColor.GRAY + "? (y/n)"; } @Override protected boolean isInputValid(ConversationContext context, String message) { return message.contains("y") || message.contains("n"); } @Override protected Prompt acceptValidatedInput(ConversationContext context, String message) { if(message.contains("y")) { // Define variables Player player = (Player) context.getForWhom(); String chosenDeity = (String) context.getSessionData("chosen_deity"); // Give the player further directions Demigods.message.clearRawChat(player); player.sendRawMessage(ChatColor.AQUA + " Before you can confirm your lineage with " + ChatColor.YELLOW + StringUtils.capitalize(chosenDeity) + ChatColor.AQUA + ","); player.sendRawMessage(ChatColor.AQUA + " you must first sacrifice the following items:"); player.sendRawMessage(" "); for(Map.Entry<Material, Integer> entry : Deity.Util.getDeity(chosenDeity).getClaimItems().entrySet()) player.sendRawMessage(ChatColor.GRAY + " " + Unicodes.rightwardArrow() + " " + ChatColor.YELLOW + entry.getValue() + " " + Strings.beautify(entry.getKey().name()).toLowerCase() + (entry.getValue() > 1 ? "s" : "")); player.sendRawMessage(" "); player.sendRawMessage(ChatColor.GRAY + " After you obtain these items, return to an Altar to"); player.sendRawMessage(ChatColor.GRAY + " confirm your new character."); player.sendRawMessage(" "); player.sendRawMessage(ChatColor.AQUA + " Your prayer has been disabled."); player.sendRawMessage(" "); // Save temporary data, end the conversation, and return DataManager.saveTemp(((Player) context.getForWhom()).getName(), "currently_creating", true); DataManager.saveTimed(player.getName(), "currently_creating", true, 600); DPlayer.Util.togglePrayingSilent(player, false, true); return null; } else { context.setSessionData("chosen_deity", null); return new ChooseDeity(); } } } } // Character confirmation static class ConfirmCharacter extends ValidatingPrompt implements Elements.Conversations.Category { @Override public String getChatName() { return ChatColor.GREEN + "Confirm Character"; } @Override public boolean canUse(ConversationContext context) { Player player = (Player) context.getForWhom(); return DataManager.hasKeyTemp(player.getName(), "currently_creating") && DataManager.hasTimed(player.getName(), "currently_creating"); } @Override public String getPromptText(ConversationContext context) { // Define variables Player player = (Player) context.getForWhom(); String chosenDeity = (String) context.getSessionData("chosen_deity"); // Clear chat Demigods.message.clearRawChat(player); // Ask them if they have the items player.sendRawMessage(ChatColor.YELLOW + Titles.chatTitle("Confirming Character")); player.sendRawMessage(" "); player.sendRawMessage(ChatColor.AQUA + " Do you have the following items in your inventory?" + ChatColor.GRAY + " (y/n)"); player.sendRawMessage(" "); for(Map.Entry<Material, Integer> entry : Deity.Util.getDeity(chosenDeity).getClaimItems().entrySet()) player.sendRawMessage(ChatColor.GRAY + " " + Unicodes.rightwardArrow() + " " + ChatColor.YELLOW + entry.getValue() + " " + Strings.beautify(entry.getKey().name()).toLowerCase() + (entry.getValue() > 1 ? "s" : "")); return ""; } @Override protected boolean isInputValid(ConversationContext context, String message) { return message.contains("y") || message.contains("n"); } @Override protected Prompt acceptValidatedInput(ConversationContext context, String message) { Player player = (Player) context.getForWhom(); // Open inventory Inventory inv = Bukkit.getServer().createInventory(player, 9, "Place Your Tributes Here"); player.openInventory(inv); return null; } } public static class Listener implements org.bukkit.event.Listener { @EventHandler(priority = EventPriority.HIGH) public void prayerInteract(PlayerInteractEvent event) { if(event.getClickedBlock() == null || event.getAction() != Action.RIGHT_CLICK_BLOCK) return; // Define variables Player player = event.getPlayer(); // First we check if the player is clicking a prayer block if(Structures.isClickableBlockWithFlag(event.getClickedBlock().getLocation(), Structure.Flag.PRAYER_LOCATION)) { if(!DPlayer.Util.isPraying(player)) { if(DPlayer.Util.getPlayer(player).canPvp()) { for(String message : Demigods.language.getTextBlock(Translation.Text.PVP_NO_PRAYER)) player.sendMessage(message); event.setCancelled(true); return; } // Toggle praying DPlayer.Util.togglePraying(player, true); // Tell nearby players that the user is praying for(Entity entity : player.getNearbyEntities(20, 20, 20)) if(entity instanceof Player) ((Player) entity).sendMessage(ChatColor.AQUA + Demigods.language.getText(Translation.Text.KNELT_FOR_PRAYER).replace("{player}", ChatColor.stripColor(player.getDisplayName()))); } else if(DPlayer.Util.isPraying(player)) { // Toggle prayer to false DPlayer.Util.togglePraying(player, false); } event.setCancelled(true); } } @EventHandler(priority = EventPriority.MONITOR) public void confirmDeity(InventoryCloseEvent event) { try { if(!(event.getPlayer() instanceof Player)) return; Player player = (Player) event.getPlayer(); // If it isn't a confirmation chest then exit if(!event.getInventory().getName().contains("Place Your Tributes Here")) return; // Exit if this isn't for character creation if(!DPlayer.Util.isPraying(player)) return; // Define variables ConversationContext prayerContext = DPlayer.Util.getPrayerContext(player); String chosenName = (String) prayerContext.getSessionData("chosen_name"); Deity deity = Deity.Util.getDeity((String) prayerContext.getSessionData("chosen_deity")); String deityAlliance = deity.getAlliance(); // Check the chest items int items = 0; int neededItems = deity.getClaimItems().size(); for(Map.Entry<Material, Integer> entry : deity.getClaimItems().entrySet()) if(event.getInventory().containsAtLeast(new ItemStack(entry.getKey()), entry.getValue())) items++; // Stop their praying DPlayer.Util.togglePrayingSilent(player, false, true); // Clear chat and send update Demigods.message.clearRawChat(player); player.sendMessage(ChatColor.YELLOW + "The " + deityAlliance + "s are pondering your offerings..."); if(neededItems == items) { // Accepted, finish everything up! DCharacter.Util.create(DPlayer.Util.getPlayer(player), deity.getName(), chosenName, true); // Message them and do cool things player.sendMessage(ChatColor.GREEN + Demigods.language.getText(Translation.Text.CHARACTER_CREATE_COMPLETE).replace("{deity}", deity.getName())); player.getWorld().strikeLightningEffect(player.getLocation()); for(int i = 0; i < 20; i++) player.getWorld().spawn(player.getLocation(), ExperienceOrb.class); // Remove temp data DataManager.removeTemp(player.getName(), "currently_creating"); DataManager.removeTimed(player.getName(), "currently_creating"); // Clear the prayer session DPlayer.Util.clearPrayerSession(player); } else { player.sendMessage(ChatColor.RED + "You have been denied entry into the lineage of " + deity.getName() + "!"); } // Clear the confirmation case event.getInventory().clear(); } catch(Exception e) { // Print error for debugging e.printStackTrace(); } } @EventHandler(priority = EventPriority.MONITOR) public void forsakeDeity(InventoryCloseEvent event) { try { if(!(event.getPlayer() instanceof Player)) return; Player player = (Player) event.getPlayer(); // If it isn't a confirmation chest then exit if(!event.getInventory().getName().contains("Place Items Here")) return; // Exit if this isn't for character creation if(!DPlayer.Util.isPraying(player)) return; // Define variables DCharacter character = DPlayer.Util.getPlayer(player).getCurrent(); Deity deity = character.getDeity(); // Check the chest items int items = 0; int neededItems = deity.getForsakeItems().size(); for(Map.Entry<Material, Integer> entry : deity.getForsakeItems().entrySet()) if(event.getInventory().containsAtLeast(new ItemStack(entry.getKey()), entry.getValue())) items++; // Stop their praying DPlayer.Util.togglePrayingSilent(player, false, true); // Clear chat and send update Demigods.message.clearRawChat(player); player.sendMessage(ChatColor.YELLOW + deity.getName() + " is debating your departure..."); if(neededItems == items) { // Accepted, delete the character and message the player character.remove(); player.sendMessage(ChatColor.GREEN + "You are now free from the will of " + deity.getName() + "!"); // Add potion effects for fun PotionEffect potion = new PotionEffect(PotionEffectType.WEAKNESS, 1200, 3); player.addPotionEffect(potion); // Remove temp DataManager.removeTemp(player.getName(), "currently_forsaking"); DataManager.removeTimed(player.getName(), "currently_forsaking"); // Clear the prayer session DPlayer.Util.clearPrayerSession(player); } else { player.sendMessage(ChatColor.RED + deity.getName() + " has denied your forsaking!"); } // Clear the confirmation case event.getInventory().clear(); } catch(Exception e) { // Print error for debugging e.printStackTrace(); } } @EventHandler(priority = EventPriority.MONITOR) private void onPlayerMove(PlayerMoveEvent event) { // Define variables Player player = event.getPlayer(); if(DPlayer.Util.isPraying(player) && event.getTo().distance((Location) DataManager.getValueTemp(player.getName(), "prayer_location")) >= Demigods.config.getSettingInt("zones.prayer_radius")) DPlayer.Util.togglePraying(player, false); } } }
false
false
null
null
diff --git a/src/awesome/ID3View.java b/src/awesome/ID3View.java index ed1337b..9cf729c 100644 --- a/src/awesome/ID3View.java +++ b/src/awesome/ID3View.java @@ -1,286 +1,286 @@ package awesome; import javax.swing.*; import javax.swing.event.TreeExpansionEvent; import javax.swing.event.TreeExpansionListener; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.filechooser.FileSystemView; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreeSelectionModel; import java.awt.*; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.awt.event.*; public class ID3View extends JFrame implements TreeSelectionListener, TreeExpansionListener { private static final long serialVersionUID = 3797307884995261587L; private JTextField titleField; private JTextField albumField; private JTextField yearField; private JTextField artistField; private JTree fileTree; private JLabel coverContainer; private JSplitPane splitPane; public ID3View() { setSize(700, 500); setTitle("Awesome ID3"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //TODO: Change to ID3Controller.exitApplication() splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); splitPane.setDividerLocation(-1); getContentPane().add(splitPane, BorderLayout.CENTER); createTree(); createMenu(); createDetailForm(); } /** * creates and initializes the menu bar of the frame and its subcomponents. */ private void createMenu(){ JMenuBar menuBar = new JMenuBar(); JMenu menuMain = new JMenu("Awesome ID3"); JMenuItem itemSave = new JMenuItem("Save Changes"); JMenuItem itemReload = new JMenuItem("Reload MP3 Files"); JMenuItem itemChangeDir = new JMenuItem("Choose Music Directory..."); JMenuItem itemExit = new JMenuItem("Exit Awesome ID3"); itemExit.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { ID3Controller.getController().exitApplication(); } }); itemSave.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) fileTree.getLastSelectedPathComponent(); if(selectedNode == null) return; Object userObject = selectedNode.getUserObject(); if(userObject instanceof MP3File){ MP3File mp3 = (MP3File) userObject; mp3.setAlbum(albumField.getText()); mp3.setArtist(artistField.getText()); mp3.setTitle(titleField.getText()); mp3.setYear(yearField.getText()); try { mp3.save(); } catch (IOException e) { presentException(e); } } } }); menuMain.add(itemSave); menuMain.addSeparator(); menuMain.add(itemReload); //menuMain.addSeparator(); //maybe it's prettier menuMain.add(itemChangeDir); menuMain.addSeparator(); menuMain.add(itemExit); menuBar.add(menuMain); this.setJMenuBar(menuBar); } /** * creates and initializes the tree used to present the directory structure. */ private void createTree(){ // initializes the tree //TODO: Initialize with correct directory DefaultMutableTreeNode topNode = buildFileTree(new Directory(new File(FileSystemView.getFileSystemView().getHomeDirectory(),"/Music"))); //in "" you can add a subpath e.g. /Music/iTunes for mac users fileTree = new JTree(topNode); fileTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); fileTree.addTreeSelectionListener(this); fileTree.addTreeExpansionListener(this); // packs the tree into a scroll pane. JScrollPane treePane = new JScrollPane(fileTree); treePane.setPreferredSize(new Dimension(150, 10)); treePane.setMinimumSize(new Dimension(150, 10)); treePane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); treePane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); splitPane.setLeftComponent(treePane); } private DefaultMutableTreeNode buildFileTree(FilePathInfo pathInfo) { if(pathInfo.isDirectory() && (MP3File.containsMP3s(pathInfo.getFile()))){ DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode(pathInfo); ArrayList<FilePathInfo> subFiles = (ArrayList<FilePathInfo>) pathInfo.listFiles(); for(FilePathInfo fpi : subFiles){ if(MP3File.containsMP3s(fpi.getFile())) { rootNode.add(buildFileTree(fpi)); } } return rootNode; } else { return new DefaultMutableTreeNode(pathInfo); } } /** * creates and initializes the fields used to display and modify the * detailed information of a mp3 file. */ private void createDetailForm(){ JPanel detailPanel = new JPanel(); detailPanel.setLayout(new BorderLayout()); JPanel textDetailPanel = new JPanel(); GridBagLayout textDetailLayout = new GridBagLayout(); textDetailPanel.setLayout(textDetailLayout); GridBagConstraints textDetailConstraints = new GridBagConstraints(GridBagConstraints.RELATIVE, GridBagConstraints.RELATIVE, 4, 2, 0.0, 0.0, GridBagConstraints.BASELINE_LEADING, GridBagConstraints.HORIZONTAL, new Insets(10,20,0,5), 0, 0); GridBagConstraints textDetailConstraintsFill = (GridBagConstraints) textDetailConstraints.clone(); textDetailConstraintsFill.weightx = 0.5; //textDetailConstraintsFill.insets = new Insets(10,5,0,20); JLabel titleLabel = new JLabel("<html><b>Title</b></html>"); textDetailPanel.add(titleLabel, textDetailConstraints); titleField = new JTextField(25); textDetailPanel.add(titleField, textDetailConstraintsFill); JLabel albumLabel = new JLabel("<html><b>Album</b></html>"); textDetailPanel.add(albumLabel, textDetailConstraints); albumField = new JTextField(25); textDetailPanel.add(albumField, textDetailConstraintsFill); textDetailConstraints.gridy = 2; textDetailConstraintsFill.gridy = 2; JLabel yearLabel = new JLabel("<html><b>Year</b></html>"); textDetailPanel.add(yearLabel, textDetailConstraints); yearField = new JTextField(25); textDetailPanel.add(yearField, textDetailConstraintsFill); JLabel artistLabel = new JLabel("<html><b>Artist</b></html>"); textDetailPanel.add(artistLabel, textDetailConstraints); artistField = new JTextField(25); textDetailPanel.add(artistField, textDetailConstraintsFill); detailPanel.add(textDetailPanel, BorderLayout.NORTH); coverContainer = new JLabel(); coverContainer.setIcon(null); coverContainer.addMouseListener(new MouseAdapter(){ /** * @see java.awt.event.MouseAdapter#mouseClicked(java.awt.event.MouseEvent) */ @Override public void mouseClicked(MouseEvent e) { if(e.getButton() == MouseEvent.BUTTON1){ DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) fileTree.getLastSelectedPathComponent(); if(selectedNode == null) return; Object userObject = selectedNode.getUserObject(); if(userObject instanceof MP3File){ MP3File mp3 = (MP3File) userObject; JFileChooser fileChooser = new JFileChooser(); fileChooser.setFileFilter(new ImageFileFilter()); if(fileChooser.showOpenDialog(ID3View.this) == JFileChooser.APPROVE_OPTION){ File file = fileChooser.getSelectedFile(); mp3.readCoverFromFile(file); coverContainer.setIcon(new ImageIcon(mp3.getCover())); coverContainer.setText(""); } } } } }); FlowLayout coverLayout = new FlowLayout(); coverLayout.setAlignment(FlowLayout.CENTER); JPanel outerCoverContainer = new JPanel(coverLayout); outerCoverContainer.add(coverContainer); detailPanel.add(outerCoverContainer, BorderLayout.CENTER); splitPane.setRightComponent(detailPanel); } public void presentException(Exception ex){ - JOptionPane.showMessageDialog(null, + JOptionPane.showMessageDialog(this, ex.getMessage(), "An Error Occured", JOptionPane.ERROR_MESSAGE); } @Override // The event handler for the tree public void valueChanged(TreeSelectionEvent event) { updateDetailForm(); } private void updateDetailForm() { DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) fileTree.getLastSelectedPathComponent(); if(selectedNode == null) return; Object userObject = selectedNode.getUserObject(); if(userObject instanceof MP3File){ MP3File mp3 = (MP3File) userObject; titleField.setText(mp3.getTitle()); albumField.setText(mp3.getAlbum()); yearField.setText(mp3.getYear()); artistField.setText(mp3.getArtist()); if(mp3.getCover() != null){ coverContainer.setText(""); coverContainer.setIcon(new ImageIcon(mp3.getCover())); } else { coverContainer.setText("Click here to add Cover"); coverContainer.setIcon(null); } // mp3.getfile.getAbsolutePath } } @Override public void treeExpanded(TreeExpansionEvent event) { recalculateDividerLocation(); } @Override public void treeCollapsed(TreeExpansionEvent event) { recalculateDividerLocation(); } private void recalculateDividerLocation() { //+25 is for scrollbar splitPane.setDividerLocation((fileTree.getPreferredSize().getWidth()+25) / (float) splitPane.getSize().getWidth()); } }
true
false
null
null
diff --git a/model/org/eclipse/cdt/core/settings/model/ACExclusionFilterEntry.java b/model/org/eclipse/cdt/core/settings/model/ACExclusionFilterEntry.java index d9ce89697..b6211cbdd 100644 --- a/model/org/eclipse/cdt/core/settings/model/ACExclusionFilterEntry.java +++ b/model/org/eclipse/cdt/core/settings/model/ACExclusionFilterEntry.java @@ -1,89 +1,89 @@ /******************************************************************************* * Copyright (c) 2007 Intel Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Intel Corporation - Initial API and implementation *******************************************************************************/ package org.eclipse.cdt.core.settings.model; import java.util.Arrays; import org.eclipse.core.resources.IFolder; import org.eclipse.core.runtime.IPath; public abstract class ACExclusionFilterEntry extends ACPathEntry implements ICExclusionPatternPathEntry { private IPath[] exclusionPatterns; private final static char[][] UNINIT_PATTERNS = new char[][] { "Non-initialized yet".toCharArray() }; //$NON-NLS-1$ char[][]fullCharExclusionPatterns = UNINIT_PATTERNS; - public ACExclusionFilterEntry(IPath path, IPath exclusionPatterns[] , int flags) { + ACExclusionFilterEntry(IPath path, IPath exclusionPatterns[] , int flags) { super(path, flags); this.exclusionPatterns = exclusionPatterns != null ? (IPath[])exclusionPatterns.clone() : new IPath[0]; } - public ACExclusionFilterEntry(IFolder rc, IPath exclusionPatterns[], int flags) { + ACExclusionFilterEntry(IFolder rc, IPath exclusionPatterns[], int flags) { super(rc, flags); this.exclusionPatterns = exclusionPatterns != null ? (IPath[])exclusionPatterns.clone() : new IPath[0]; } - public ACExclusionFilterEntry(String value, IPath exclusionPatterns[], int flags) { + ACExclusionFilterEntry(String value, IPath exclusionPatterns[], int flags) { super(value, flags); this.exclusionPatterns = exclusionPatterns != null ? (IPath[])exclusionPatterns.clone() : new IPath[0]; } protected final boolean isFile() { return false; } /** * Returns the exclusion patterns * @return IPath[] */ public IPath[] getExclusionPatterns() { return exclusionPatterns; } /** * Returns a char based representation of the exclusions patterns full path. */ public char[][] fullExclusionPatternChars() { if (this.fullCharExclusionPatterns == UNINIT_PATTERNS) { int length = this.exclusionPatterns.length; this.fullCharExclusionPatterns = new char[length][]; IPath path = getFullPath(); if(path == null) path = getLocation(); IPath prefixPath = path.removeTrailingSeparator(); for (int i = 0; i < length; i++) { this.fullCharExclusionPatterns[i] = prefixPath.append(this.exclusionPatterns[i]).toString().toCharArray(); } } return this.fullCharExclusionPatterns; } public boolean equals(Object other) { if(!super.equals(other)) return false; ACExclusionFilterEntry otherEntry = (ACExclusionFilterEntry)other; return Arrays.equals(exclusionPatterns, otherEntry.exclusionPatterns); } public int hashCode() { return super.hashCode() + exclusionPatterns.hashCode(); } public boolean equalsByContents(ICSettingEntry entry) { if(!super.equalsByContents(entry)) return false; ACExclusionFilterEntry otherEntry = (ACExclusionFilterEntry)entry; return Arrays.equals(exclusionPatterns, otherEntry.exclusionPatterns); } } diff --git a/model/org/eclipse/cdt/core/settings/model/ACPathEntry.java b/model/org/eclipse/cdt/core/settings/model/ACPathEntry.java index f89cc83ea..5e077de95 100644 --- a/model/org/eclipse/cdt/core/settings/model/ACPathEntry.java +++ b/model/org/eclipse/cdt/core/settings/model/ACPathEntry.java @@ -1,87 +1,87 @@ /******************************************************************************* * Copyright (c) 2007 Intel Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Intel Corporation - Initial API and implementation *******************************************************************************/ package org.eclipse.cdt.core.settings.model; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; public abstract class ACPathEntry extends ACSettingEntry implements ICPathEntry { // IPath fFullPath; // IPath fLocation; // private IPath fPath; - public ACPathEntry(IResource rc, int flags) { + ACPathEntry(IResource rc, int flags) { super(rc.getFullPath().toString(), flags | RESOLVED | VALUE_WORKSPACE_PATH); // fFullPath = rc.getFullPath(); // fPath = rc.getFullPath(); // fLocation = rc.getLocation(); } /* public ACLanguageSettingPathEntry(IPath fullPath, IPath location, int flags) { super(flags); fLocation = location; fFullPath = fullPath; } */ - public ACPathEntry(String value, int flags) { + ACPathEntry(String value, int flags) { super(value, flags); } - public ACPathEntry(IPath path, int flags) { + ACPathEntry(IPath path, int flags) { super(path.toString(), flags /*| RESOLVED*/); // fPath = path; // if(isValueWorkspacePath()) // fFullPath = path; // else // fLocation = path; } public IPath getFullPath() { if(isValueWorkspacePath()) return new Path(getValue()); if(isResolved()) { IPath path = new Path(getValue()); return fullPathForLocation(path); } return null; } protected IPath fullPathForLocation(IPath location){ IResource rcs[] = isFile() ? (IResource[])ResourcesPlugin.getWorkspace().getRoot().findFilesForLocation(location) : (IResource[])ResourcesPlugin.getWorkspace().getRoot().findContainersForLocation(location); if(rcs.length > 0) return rcs[0].getFullPath(); return null; } protected abstract boolean isFile(); public IPath getLocation() { if(!isValueWorkspacePath()) return new Path(getValue()); if(isResolved()){ IPath path = new Path(getValue()); IResource rc = ResourcesPlugin.getWorkspace().getRoot().findMember(path); if(rc != null) return rc.getLocation(); } return null; } public boolean isValueWorkspacePath() { return checkFlags(VALUE_WORKSPACE_PATH); } } diff --git a/model/org/eclipse/cdt/core/settings/model/ACSettingEntry.java b/model/org/eclipse/cdt/core/settings/model/ACSettingEntry.java index abf6f468c..a5d8ebfdf 100644 --- a/model/org/eclipse/cdt/core/settings/model/ACSettingEntry.java +++ b/model/org/eclipse/cdt/core/settings/model/ACSettingEntry.java @@ -1,117 +1,117 @@ /******************************************************************************* * Copyright (c) 2007 Intel Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Intel Corporation - Initial API and implementation *******************************************************************************/ package org.eclipse.cdt.core.settings.model; public abstract class ACSettingEntry implements ICSettingEntry { int fFlags; String fName; - public ACSettingEntry(String name, int flags){ + ACSettingEntry(String name, int flags){ fName = name; fFlags = flags; } public boolean isBuiltIn() { return checkFlags(BUILTIN); } public boolean isReadOnly() { return checkFlags(READONLY); } protected boolean checkFlags(int flags){ return (fFlags & flags) == flags; } public String getName() { return fName; } public String getValue() { //name and value differ only for macro entry and have the same contents //for all other entries return fName; } public boolean isResolved() { return checkFlags(RESOLVED); } public boolean equals(Object other){ if(other == this) return true; if(!(other instanceof ACSettingEntry)) return false; ACSettingEntry e = (ACSettingEntry)other; if(getKind() != e.getKind()) return false; if(fFlags != e.fFlags) return false; if(!fName.equals(e.fName)) return false; return true; } public int hashCode(){ return getKind() + fFlags + fName.hashCode(); } public int getFlags() { return fFlags; } public boolean equalsByContents(ICSettingEntry entry) { return equalsByName(entry); } protected int getByNameMatchFlags(){ return (fFlags & (~ (BUILTIN | READONLY))); } public final boolean equalsByName(ICSettingEntry entry) { if(entry == this) return true; if(!(entry instanceof ACSettingEntry)) return false; ACSettingEntry e = (ACSettingEntry)entry; if(getKind() != e.getKind()) return false; if(getByNameMatchFlags() != e.getByNameMatchFlags()) return false; if(!fName.equals(e.fName)) return false; return true; } public final int codeForNameKey(){ return getKind() + getByNameMatchFlags() + fName.hashCode(); } public int codeForContentsKey(){ return codeForNameKey(); } }
false
false
null
null
diff --git a/src/com/capstonecontrol/LogsActivity.java b/src/com/capstonecontrol/LogsActivity.java index 007505c..8bad6b3 100644 --- a/src/com/capstonecontrol/LogsActivity.java +++ b/src/com/capstonecontrol/LogsActivity.java @@ -1,524 +1,523 @@ package com.capstonecontrol; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.lang.Math; import com.capstonecontrol.client.ModulesRequestFactory; import com.capstonecontrol.client.ModulesRequestFactory.ModuleEventFetchRequest; import com.capstonecontrol.client.ModulesRequestFactory.ScheduledModuleEventFetchRequest; import com.capstonecontrol.shared.ModuleEventProxy; import com.capstonecontrol.shared.ScheduledModuleEventProxy; import com.google.web.bindery.requestfactory.shared.Receiver; import com.google.web.bindery.requestfactory.shared.ServerFailure; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.os.StrictMode; import android.os.StrictMode.ThreadPolicy; import android.util.Log; import android.view.View; import android.view.Window; import android.view.View.OnClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.Spinner; public class LogsActivity extends BarListActivity { private Context mContext = this; private static final String TAG = "LogsActivity"; public static List<ModuleEvent> moduleEvents = new ArrayList<ModuleEvent>(); public static List<ModuleEvent> moduleEventsSuggested = new ArrayList<ModuleEvent>(); public static ArrayList<String> moduleEventsList = new ArrayList<String>(); public static List<ScheduledModuleEvent> scheduledModuleEvents = new ArrayList<ScheduledModuleEvent>(); private Button submitButton; private Button suggestButton; private Button profilesButton; private ListView lv; Spinner dateSpinner, moduleSpinner, typeSpinner; @Override public void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_NO_TITLE); super.onCreate(savedInstanceState); this.setContentView(R.layout.logs); // @TODO REMOVE BELOW AND PUT AND POST STATEMENT IN ITS OWN THREAD ThreadPolicy tp = ThreadPolicy.LAX; StrictMode.setThreadPolicy(tp); // enable bar enableBar(); // enable POST capabilities enablePOST(); // handle spinners setUpSpinners(); // set up submit button setUpSubmitButton(); // set up profiles button setUpProfilesButton(); // set up suggested profile button setUpSuggestButton(); } private void setUpProfilesButton() { this.profilesButton = (Button) this.findViewById(R.id.setupProfile); this.profilesButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { // first disable the button Intent myIntent = new Intent(view.getContext(), ScheduledEventsActivity.class); startActivity(myIntent); } }); } private void setUpSubmitButton() { this.submitButton = (Button) this.findViewById(R.id.submitButton); this.submitButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { // first disable the button submitButton.setEnabled(false); suggestButton.setEnabled(false); // clear previous request moduleEvents.clear(); scheduledModuleEvents.clear(); // now get the new info displayMessageList("Refreshing..."); // decide which methord to call logs or scheduled String typeSpinnerValue = typeSpinner.getSelectedItem() .toString(); if (typeSpinnerValue.equals("Log")) { getLogInfo(true, false); } else { getScheduledInfo(); } } }); } private void setUpSuggestButton() { this.suggestButton = (Button) this.findViewById(R.id.suggestProfile); this.suggestButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { // first disable the button submitButton.setEnabled(false); suggestButton.setEnabled(false); // clear previous request moduleEvents.clear(); moduleEventsSuggested.clear(); // now get the new info displayMessageList("Calculating suggested profiles..."); getLogInfo(false, true); } }); } protected void displaySuggestedProfiles() { String tempString; submitButton.setEnabled(true); suggestButton.setEnabled(true); moduleEventsList.clear(); int hour, minute; for (int i = 0; i < moduleEventsSuggested.size(); i++) { hour = moduleEventsSuggested.get(i).getDate().getHours(); minute = moduleEventsSuggested.get(i).getDate().getMinutes(); if (hour < 10) { tempString = "0" + Integer.toString(hour) + ":"; } else { tempString = Integer.toString(hour) + ":"; } if (minute < 10) { tempString += "0" + Integer.toString(minute); } else { Calendar cal = Calendar.getInstance(); tempString += Integer.toString(minute); } tempString += " " + moduleEventsSuggested.get(i).getModuleName(); tempString += " " + moduleEventsSuggested.get(i).getModuleType(); tempString += " " + moduleEventsSuggested.get(i).getValue(); if (moduleEventsSuggested.get(i).getOccuranceCount() > 3) { moduleEventsList.add(tempString); } } ArrayAdapter<String> arrayAdapter = // new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, // BarActivity.alertsList); new ArrayAdapter<String>(this, R.layout.list_text_style2, moduleEventsList); lv.setAdapter(arrayAdapter); } private void calculateSuggestedProfiles() { ModuleEvent moduleEventI; ModuleEvent moduleEventJ; Date dateI; Date dateJ; Date eventSuggestDate; int fifteenMinIntervals; int timeDifference = 9; int minutesI; int minutesJ; for (int i = 0; i < moduleEvents.size(); i++) { moduleEventI = moduleEvents.get(i); for (int j = 0; j < moduleEvents.size(); j++) { moduleEventJ = moduleEvents.get(j); // now that we have two modules to compare, lets do it // first check to see if same module and type if (moduleEventI.getModuleName().equals( moduleEventJ.getModuleName()) && moduleEventI.getAction().equals( moduleEventJ.getAction())) { if (moduleValueSimiliar(moduleEventI, moduleEventJ)) { dateI = moduleEventI.getDate(); dateJ = moduleEventJ.getDate(); minutesI = dateI.getHours() * 60 + dateI.getMinutes(); minutesJ = dateJ.getHours() * 60 + dateJ.getMinutes(); if (Math.abs(minutesI - minutesJ) < timeDifference - && dateI.getYear() == dateJ.getYear() - && dateI.getMonth() == dateJ.getMonth()) { + && dateI.getDate() != dateJ.getDate()) { // add one to the count for this // create a new moduleEvent based off one of the two // compared ModuleEvent moduleEventSuggest = moduleEventJ; // now set the time closest to a 15 minute interval eventSuggestDate = new Date(); fifteenMinIntervals = Math .round((minutesJ + minutesI) / 2 / 15); Calendar cal = Calendar.getInstance(); // get // calendar // instance cal.setTime(eventSuggestDate); // set cal to date cal.set(Calendar.HOUR_OF_DAY, 0); // set hour to // midnight cal.set(Calendar.MINUTE, fifteenMinIntervals * 15); // set // minute // in // hour cal.set(Calendar.SECOND, 0); // set second in minute cal.set(Calendar.MILLISECOND, 0); // set millis in // second eventSuggestDate = cal.getTime(); moduleEventSuggest.setDate(eventSuggestDate); // add the object to the list addModuleEventToSuggested(moduleEventSuggest); } } } } } } private void addModuleEventToSuggested(ModuleEvent moduleEventSuggest) { for (int i = 0; i < moduleEventsSuggested.size(); i++) { if (moduleEventSuggest .compareEventsForSuggest(moduleEventsSuggested.get(i))) { moduleEventsSuggested.get(i).incrementOccuranceCount(); return; } } // if not found in the list already add it moduleEventsSuggested.add(moduleEventSuggest); } private boolean moduleValueSimiliar(ModuleEvent moduleEventI, ModuleEvent moduleEventJ) { // if we are in here we can assume that the types are equal if (moduleEventI.getModuleType().equals("Dimmer")) { // values are allowed to have some wiggle room // ie dimmer level of 99 is close enough to value of 95 to be // considered equal if (Math.abs(Integer.parseInt(moduleEventI.getValue()) - Integer.parseInt(moduleEventJ.getValue())) < 9) { // assume close enough return true; } } if (moduleEventI.getModuleType().equals("Door Buzzer")) { if (moduleEventI.getValue().equals(moduleEventJ.getValue())) { return true; } } return false; } private void setUpSpinners() { dateSpinner = (Spinner) findViewById(R.id.dateRangeSpinner); ArrayAdapter<CharSequence> dateAdapter = ArrayAdapter .createFromResource(this, R.array.dateRange_array, android.R.layout.simple_spinner_item); dateAdapter .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); dateSpinner.setAdapter(dateAdapter); // now do the module spinner moduleSpinner = (Spinner) findViewById(R.id.moduleTypeSpinner); ArrayAdapter<CharSequence> moduleAdapter = ArrayAdapter .createFromResource(this, R.array.moduleType_array, android.R.layout.simple_spinner_item); moduleAdapter .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); moduleSpinner.setAdapter(moduleAdapter); // now do the type spinner typeSpinner = (Spinner) findViewById(R.id.typeSpinner); ArrayAdapter<CharSequence> typeAdapter = ArrayAdapter .createFromResource(this, R.array.eventType_array, android.R.layout.simple_spinner_item); typeAdapter .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); typeSpinner.setAdapter(typeAdapter); } private void displayMessageList(String message) { moduleEventsList.clear(); moduleEventsList.add(message); // create list lv = getListView(); ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, R.layout.list_text_style2, moduleEventsList); lv.setAdapter(arrayAdapter); } public String padMinutesToString(Long minutes){ if (minutes <10) return "0" + minutes; else return Long.toString(minutes); } private void updateScheduledEventListView() { // done search for re-enable the submit button submitButton.setEnabled(true); suggestButton.setEnabled(true); String tempString; // clear old list moduleEventsList.clear(); for (int i = 0; i < scheduledModuleEvents.size(); i++) { tempString = ""; ScheduledModuleEvent mySchedEvent = scheduledModuleEvents.get(i); if (scheduledModuleEvents.get(i).getRecur()){ //means reoccuring if (mySchedEvent.getMon()) tempString += "Mon "; if (mySchedEvent.getTue()) tempString += "Tue "; if (mySchedEvent.getWed()) tempString += "Wed "; if (mySchedEvent.getThu()) tempString += "Thu "; if (mySchedEvent.getFri()) tempString += "Fri "; if (mySchedEvent.getSat()) tempString += "Sat "; if (mySchedEvent.getSun()) tempString += "Sun "; tempString += " " + mySchedEvent.getHour() + ":" + padMinutesToString(mySchedEvent.getMinute()); } else{ //means its a once time tempString += mySchedEvent.getSchedDate(); tempString += " "; } tempString += " " + mySchedEvent.getModuleName(); tempString += " " + mySchedEvent.getValue(); // boolean displayEvent = // checkToAddEvent(scheduledModuleEvents.get(i) // .getDate(), scheduledModuleEvents.get(i).getModuleType()); // if (displayEvent) { moduleEventsList.add(tempString); // } } ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, R.layout.list_text_style2, moduleEventsList); lv.setAdapter(arrayAdapter); } private void updateEventListView() { // done search for re-enable the submit button submitButton.setEnabled(true); suggestButton.setEnabled(true); String tempString; // clear old list moduleEventsList.clear(); // create list of strings based on event info for (int i = 0; i < moduleEvents.size(); i++) { tempString = moduleEvents.get(i).getDate().toLocaleString(); tempString += " " + moduleEvents.get(i).getModuleName(); tempString += " " + moduleEvents.get(i).getModuleType(); tempString += " " + moduleEvents.get(i).getValue(); boolean displayEvent = checkToAddEvent(moduleEvents.get(i) .getDate(), moduleEvents.get(i).getModuleType()); if (displayEvent) { moduleEventsList.add(tempString); } } ArrayAdapter<String> arrayAdapter2 = // new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, // BarActivity.alertsList); new ArrayAdapter<String>(this, R.layout.list_text_style2, moduleEventsList); lv.setAdapter(arrayAdapter2); } private boolean checkToAddEvent(Date date, String moduleType) { String moduleSpinnerValue = moduleSpinner.getSelectedItem().toString(); String dateSpinnerValue = dateSpinner.getSelectedItem().toString(); // start with getting the date now Date currentDate = new Date(); // subtract from current date based on selection Calendar cal = Calendar.getInstance(); cal.setTime(currentDate); if (dateSpinnerValue.equals("Past Day")) { cal.add(Calendar.DATE, -1); } if (dateSpinnerValue.equals("Past Week")) { cal.add(Calendar.DATE, -7); } if (dateSpinnerValue.equals("Past 30 Days")) { cal.add(Calendar.DATE, -30); } if (dateSpinnerValue.equals("Past 60 Days")) { cal.add(Calendar.DATE, -60); } if (dateSpinnerValue.equals("Past 90 Days")) { cal.add(Calendar.DATE, -90); } if (!cal.getTime().before(date)) { return false; } // see if the type is matched if (!moduleType.equals(moduleSpinnerValue) && !moduleSpinnerValue.equals("All")) { return false; } return true; } private void getLogInfo(final boolean display, final boolean suggested) { new AsyncTask<Void, Void, List<ModuleEvent>>() { @SuppressWarnings("unused") String foundModuleEvents; @Override protected List<ModuleEvent> doInBackground(Void... arg0) { ModulesRequestFactory requestFactory = Util.getRequestFactory( mContext, ModulesRequestFactory.class); final ModuleEventFetchRequest request = (ModuleEventFetchRequest) requestFactory .moduleEventFetchRequest(); Log.i(TAG, "Sending request to server"); request.getModuleEvents().fire( new Receiver<List<ModuleEventProxy>>() { @Override public void onFailure(ServerFailure error) { // do nothing, no modules found foundModuleEvents = "There was an error!"; } @Override public void onSuccess(List<ModuleEventProxy> arg0) { foundModuleEvents = "The module events found were: "; for (int i = 0; i < arg0.size(); i++) { // create temporary module infro // proxy, tmi ModuleEventProxy tmi = arg0.get(i); moduleEvents.add(new ModuleEvent(tmi .getModuleName(), tmi .getModuleType(), tmi.getUser(), tmi.getAction(), tmi.getDate(), tmi .getValue())); } if (moduleEvents.isEmpty()) foundModuleEvents = "No module events were found!"; } }); return moduleEvents; } protected void onPostExecute(List<ModuleEvent> result) { // if events found that match update the shown list if (!moduleEvents.isEmpty() && display) { updateEventListView(); } if (!moduleEvents.isEmpty() && suggested) { // now calculate profiles based on the found events // @Todo might need a thread stop until all events are // returned. calculateSuggestedProfiles(); // now that all counts are calculated, show any above the // threshold displaySuggestedProfiles(); } } }.execute(); } protected void getScheduledInfo() { new AsyncTask<Void, Void, List<ScheduledModuleEvent>>() { @SuppressWarnings("unused") String foundModuleEvents; @Override protected List<ScheduledModuleEvent> doInBackground(Void... arg0) { ModulesRequestFactory requestFactory = Util.getRequestFactory( mContext, ModulesRequestFactory.class); final ScheduledModuleEventFetchRequest request = (ScheduledModuleEventFetchRequest) requestFactory .scheduledModuleEventFetchRequest(); Log.i(TAG, "Sending request to server"); request.getScheduledEvents().fire( new Receiver<List<ScheduledModuleEventProxy>>() { @Override public void onFailure(ServerFailure error) { // do nothing, no modules found foundModuleEvents = "There was an error!"; } @Override public void onSuccess( List<ScheduledModuleEventProxy> arg0) { foundModuleEvents = "The module events found were: "; for (int i = 0; i < arg0.size(); i++) { // create temporary module infro // proxy, tmi ScheduledModuleEventProxy tmi = arg0.get(i); scheduledModuleEvents .add(new ScheduledModuleEvent(tmi .getModuleName(), tmi.getModuleType(),tmi .getDate(), tmi .getSchedDate(), tmi .getMon(), tmi.getTue(), tmi.getWed(), tmi.getThu(), tmi.getFri(), tmi.getSat(), tmi.getSun(), tmi .getActive(), tmi .getRecur(), tmi .getMinute(), tmi .getHour(), tmi .getDay(), tmi .getMonth(), tmi .getYear(), tmi .getTimeOffset(), tmi.getValue(), tmi.getAction())); } if (scheduledModuleEvents.isEmpty()) foundModuleEvents = "No scheduled module events were found!"; } }); return scheduledModuleEvents; } protected void onPostExecute(List<ScheduledModuleEvent> result) { // if events found that match update the shown list updateScheduledEventListView(); } }.execute(); } } diff --git a/src/com/capstonecontrol/PowerManagementActivity.java b/src/com/capstonecontrol/PowerManagementActivity.java index 8cf9e56..0ea2f21 100644 --- a/src/com/capstonecontrol/PowerManagementActivity.java +++ b/src/com/capstonecontrol/PowerManagementActivity.java @@ -1,246 +1,247 @@ package com.capstonecontrol; import java.util.ArrayList; import java.util.Date; import java.util.List; import com.capstonecontrol.client.ModulesRequestFactory; import com.capstonecontrol.client.ModulesRequestFactory.PowerDataFetchService; import com.capstonecontrol.shared.PowerDataProxy; import com.google.web.bindery.requestfactory.shared.Receiver; import com.google.web.bindery.requestfactory.shared.ServerFailure; import com.jjoe64.graphview.GraphView; import com.jjoe64.graphview.GraphView.GraphViewData; import com.jjoe64.graphview.GraphView.GraphViewSeries; import com.jjoe64.graphview.LineGraphView; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.os.StrictMode; import android.os.StrictMode.ThreadPolicy; import android.util.Log; import android.view.View; import android.view.Window; import android.view.View.OnClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.Spinner; public class PowerManagementActivity extends BarListActivity { private Context mContext = this; private static final String TAG = "LogsActivity"; public static List<PowerData> powerDataArray = new ArrayList<PowerData>(); public static List<PowerData> matchingPowerDataArray = new ArrayList<PowerData>(); public static List<ModuleEvent> moduleEventsSuggested = new ArrayList<ModuleEvent>(); public static ArrayList<String> moduleEventsList = new ArrayList<String>(); public static List<ScheduledModuleEvent> scheduledModuleEvents = new ArrayList<ScheduledModuleEvent>(); private Button oneButton, sevenButton; private ListView lv; Spinner dateSpinner, moduleSpinner, typeSpinner; public static boolean oneDay; private float averageWatts, usedkWHr; @Override public void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_NO_TITLE); super.onCreate(savedInstanceState); this.setContentView(R.layout.power_management); // @TODO REMOVE BELOW AND PUT AND POST STATEMENT IN ITS OWN THREAD ThreadPolicy tp = ThreadPolicy.LAX; StrictMode.setThreadPolicy(tp); // enable bar enableBar(); // enable POST capabilities enablePOST(); // handle spinners // set up submit button setUpSubmitButtons(); + displayMessageList("Select time period to view info."); } private void setUpSubmitButtons() { this.oneButton = (Button) this.findViewById(R.id.oneDayButton); this.oneButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { // first disable the button oneDay = true; oneButton.setEnabled(false); sevenButton.setEnabled(false); // clear previous request powerDataArray.clear(); scheduledModuleEvents.clear(); // now get the new info if (powerDataArray.isEmpty()) { getPowerDataInfo(true, 1); } displayMessageList("Downloading data, may take a minute or two..."); } }); this.sevenButton = (Button) this.findViewById(R.id.sevenDayButton); this.sevenButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { oneDay = false; // first disable the button oneButton.setEnabled(false); sevenButton.setEnabled(false); // clear previous request powerDataArray.clear(); scheduledModuleEvents.clear(); // now get the new info if (powerDataArray.isEmpty()) { getPowerDataInfo(true, 7); } displayMessageList("Downloading data, may take a minute or two..."); } }); } private void displayMessageList(String message) { moduleEventsList.clear(); moduleEventsList.add(message); // create list lv = getListView(); ArrayAdapter<String> arrayAdapter = // new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, // BarActivity.alertsList); new ArrayAdapter<String>(this, R.layout.list_text_style2, moduleEventsList); lv.setAdapter(arrayAdapter); } private void showGraph() { // create graphview GraphViewData[] wattData = new GraphView.GraphViewData[matchingPowerDataArray .size()]; for (int i = 0; i < matchingPowerDataArray.size(); i++) { wattData[i] = new GraphView.GraphViewData(i, Double.parseDouble(matchingPowerDataArray.get(i).getData())); } GraphViewSeries wattDataSeries = new GraphViewSeries(wattData); GraphView graphView = new LineGraphView(this // context , "Watts vs Time" // heading ); graphView.addSeries(wattDataSeries); // data if (oneDay) { graphView.setHorizontalLabels(new String[] { "24 hrs ago", "16 hrs ago", "8 hrs ago", "now" }); } else { graphView.setHorizontalLabels(new String[] { "7 days ago", "6", "5", "4", "3", "2", "1 day ago", "now" }); } LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayoutGraph); layout.removeAllViews(); layout.addView(graphView); } private void getPowerDataInfo(final boolean display, final int days) { new AsyncTask<Void, Void, List<PowerData>>() { @Override protected List<PowerData> doInBackground(Void... arg0) { ModulesRequestFactory requestFactory = Util.getRequestFactory( mContext, ModulesRequestFactory.class); final PowerDataFetchService request = (PowerDataFetchService) requestFactory .powerDataFetchRequest(); Log.i(TAG, "Sending request to server"); request.getPowerData().fire( new Receiver<List<PowerDataProxy>>() { @Override public void onFailure(ServerFailure error) { // do nothing, no modules found int failurestop = 4; } @Override public void onSuccess(List<PowerDataProxy> arg0) { for (int i = 0; i < arg0.size(); i++) { // create temporary module infro // proxy, tmi PowerDataProxy tmi = arg0.get(i); powerDataArray.add(new PowerData(tmi .getModuleName(), tmi.getData(), tmi.getUser(), tmi.getDate())); } } }); return powerDataArray; } protected void onPostExecute(List<PowerData> result) { pullOutMatchingByTime(); calculateAverageWatts(); calculatekWHrUsage(); displayCalculations(); showGraph(); oneButton.setEnabled(true); sevenButton.setEnabled(true); } }.execute(); } protected void displayCalculations() { moduleEventsList.clear(); moduleEventsList.add("Average Watt Reading: " + averageWatts); moduleEventsList.add("Total kWHr used: " + usedkWHr); // create list lv = getListView(); ArrayAdapter<String> arrayAdapter = // new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, // BarActivity.alertsList); new ArrayAdapter<String>(this, R.layout.list_text_style2, moduleEventsList); lv.setAdapter(arrayAdapter); } protected void pullOutMatchingByTime() { int secondsToCompare = 0; matchingPowerDataArray.clear(); PowerData myPowerData; Date currentDate = new Date(); if (oneDay == true) { // only save data with in one day secondsToCompare = 86400; } else { // save data up to seven days ago secondsToCompare = 604800; } // pull out data for (int i = 0; i < PowerManagementActivity.powerDataArray.size(); i++) { myPowerData = PowerManagementActivity.powerDataArray.get(i); int test = (int) ((currentDate.getTime() - myPowerData.getDate() .getTime()) / 1000); if (test < secondsToCompare) { matchingPowerDataArray.add(myPowerData); } } } protected void calculatekWHrUsage() { usedkWHr = 0; usedkWHr = (float) ((averageWatts / 1000) * (2.2 * matchingPowerDataArray .size() / 60)); } protected void calculateAverageWatts() { averageWatts = 0; int totalWatts = 0; for (int i = 0; i < matchingPowerDataArray.size(); i++) { totalWatts = totalWatts + Integer.parseInt(matchingPowerDataArray.get(i).getData()); } averageWatts = totalWatts / matchingPowerDataArray.size(); } }
false
false
null
null
diff --git a/src/main/java/com/authdb/util/Config.java b/src/main/java/com/authdb/util/Config.java index 695ce39..ccfd62e 100644 --- a/src/main/java/com/authdb/util/Config.java +++ b/src/main/java/com/authdb/util/Config.java @@ -1,352 +1,352 @@ /** (C) Copyright 2011 CraftFire <[email protected]> Contex <[email protected]>, Wulfspider <[email protected]> This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/3.0/ or send a letter to Creative Commons, 171 Second Street, Suite 300, San Francisco, California, 94105, USA. **/ package com.authdb.util; import java.io.File; import org.bukkit.util.config.Configuration; //import com.ensifera.animosity.craftirc.CraftIRC; public class Config { public static boolean database_ison, authdb_enabled = true; public static boolean has_badcharacters; public static boolean hasForumBoard,capitalization; public static boolean hasBackpack = false, hasBukkitContrib = false, hasSpout = false, hasBuildr = false; public static boolean onlineMode = true; public static boolean database_keepalive; public static String database_type, database_username,database_password,database_port,database_host,database_database,dbDb; public static boolean autoupdate_enable,debug_enable,usagestats_enabled,logging_enabled; public static String language, logformat; public static String script_name,script_version,script_salt,script_tableprefix; public static boolean script_updatestatus; public static String custom_table,custom_userfield,custom_passfield,custom_encryption,custom_emailfield; public static boolean custom_enabled,custom_autocreate,custom_salt, custom_emailrequired; public static boolean register_enabled,register_force; public static String register_delay_length,register_delay_time,register_timeout_length,register_timeout_time,register_show_length,register_show_time; public static int register_delay,register_timeout,register_show; public static boolean login_enabled; public static String login_method,login_tries,login_action,login_delay_length,login_delay_time,login_timeout_length,login_timeout_time,login_show_length,login_show_time; public static int login_delay,login_timeout,login_show; public static boolean link_enabled,link_rename; public static boolean unlink_enabled,unlink_rename; public static String username_minimum,username_maximum; public static String password_minimum,password_maximum; public static boolean session_protect, session_enabled; public static String session_time,session_thelength,session_start; public static int session_length; public static boolean guests_commands,guests_movement,guests_inventory,guests_drop,guests_pickup,guests_health,guests_mobdamage,guests_interact,guests_build,guests_destroy,guests_chat,guests_mobtargeting,guests_pvp; public static boolean protection_notify, protection_freeze; public static int protection_notify_delay, protection_freeze_delay; public static String protection_notify_delay_time, protection_notify_delay_length, protection_freeze_delay_time, protection_freeze_delay_length; public static String filter_action,filter_username,filter_password,filter_whitelist=""; public static boolean geoip_enabled; public static boolean CraftIRC_enabled; public static String CraftIRC_tag,CraftIRC_prefix; public static boolean CraftIRC_messages_enabled,CraftIRC_messages_welcome_enabled,CraftIRC_messages_register_enabled,CraftIRC_messages_unregister_enabled,CraftIRC_messages_login_enabled,CraftIRC_messages_email_enabled,CraftIRC_messages_username_enabled,CraftIRC_messages_password_enabled,CraftIRC_messages_idle_enabled; public static String commands_register,commands_link,commands_unlink,commands_login,commands_logout,commands_setspawn,commands_reload; public static String aliases_register,aliases_link,aliases_unlink,aliases_login,aliases_logout,aliases_setspawn,aliases_reload; public static Configuration template = null; public Config(String config, String directory, String filename) { template = new Configuration(new File(directory, filename)); template.load(); if (config.equalsIgnoreCase("basic")) { language = getConfigString("plugin.language", "English"); autoupdate_enable = getConfigBoolean("plugin.autoupdate", true); debug_enable = getConfigBoolean("plugin.debugmode", false); usagestats_enabled = getConfigBoolean("plugin.usagestats", true); logformat = getConfigString("plugin.logformat", "yyyy-MM-dd"); logging_enabled = getConfigBoolean("plugin.logging", true); database_type = getConfigString("database.type", "mysql"); database_username = getConfigString("database.username", "root"); database_password = getConfigString("database.password", ""); database_port = getConfigString("database.port", "3306"); database_host = getConfigString("database.host", "localhost"); database_database = getConfigString("database.name", "forum"); database_keepalive = getConfigBoolean("database.keepalive", false); dbDb = "jdbc:mysql://" + database_host + ":" + database_port + "/" + database_database; script_name = getConfigString("script.name", "phpbb").toLowerCase(); script_version = getConfigString("script.version", "3.0.8"); script_tableprefix = getConfigString("script.tableprefix", ""); script_updatestatus = getConfigBoolean("script.updatestatus", true); script_salt = getConfigString("script.salt", ""); } else if (config.equalsIgnoreCase("advanced")) { custom_enabled = getConfigBoolean("customdb.enabled", false); custom_autocreate = getConfigBoolean("customdb.autocreate", true); custom_emailrequired = getConfigBoolean("customdb.emailrequired", false); custom_table = getConfigString("customdb.table", "authdb_users"); custom_userfield = getConfigString("customdb.userfield", "username"); custom_passfield = getConfigString("customdb.passfield", "password"); custom_emailfield = getConfigString("customdb.emailfield", "email"); custom_encryption = getConfigString("customdb.encryption", "md5").toLowerCase(); register_enabled = getConfigBoolean("register.enabled", true); register_force = getConfigBoolean("register.force", true); register_delay_length = Util.split(getConfigString("register.delay", "4 seconds"), " ")[0]; register_delay_time = Util.split(getConfigString("register.delay", "4 seconds"), " ")[1]; register_delay = Util.toTicks(register_delay_time,register_delay_length); register_show_length = Util.split(getConfigString("register.show", "10 seconds"), " ")[0]; register_show_time = Util.split(getConfigString("register.show", "10 seconds"), " ")[1]; register_show = Util.toSeconds(register_show_time,register_show_length); register_timeout_length = Util.split(getConfigString("register.timeout", "3 minutes"), " ")[0]; register_timeout_time = Util.split(getConfigString("register.timeout", "3 minutes"), " ")[1]; register_timeout = Util.toTicks(register_timeout_time,register_timeout_length); login_method = getConfigString("login.method", "prompt"); login_tries = getConfigString("login.tries", "3"); login_action = Util.getAction(getConfigString("filter.action", "kick").toLowerCase()); login_delay_length = Util.split(getConfigString("login.delay", "4 seconds"), " ")[0]; login_delay_time = Util.split(getConfigString("login.delay", "4 seconds"), " ")[1]; login_delay = Util.toTicks(login_delay_time,login_delay_length); login_show_length = Util.split(getConfigString("login.show", "10 seconds"), " ")[0]; login_show_time = Util.split(getConfigString("login.show", "10 seconds"), " ")[1]; login_show = Util.toSeconds(login_show_time,login_show_length); login_timeout_length = Util.split(getConfigString("login.timeout", "3 minutes"), " ")[0]; login_timeout_time = Util.split(getConfigString("login.timeout", "3 minutes"), " ")[1]; login_timeout = Util.toTicks(login_timeout_time,login_timeout_length); link_enabled = getConfigBoolean("link.enabled", true); link_rename = getConfigBoolean("link.rename", true); unlink_enabled = getConfigBoolean("unlink.enabled", true); unlink_rename = getConfigBoolean("unlink.rename", true); username_minimum = getConfigString("username.minimum", "3"); username_maximum = getConfigString("username.maximum", "16"); password_minimum = getConfigString("password.minimum", "6"); password_maximum = getConfigString("password.maximum", "16"); session_enabled = getConfigBoolean("session.enabled", false); session_protect = getConfigBoolean("session.protect", true); session_thelength = Util.split(getConfigString("session.length", "1 hour"), " ")[0]; session_time = Util.split(getConfigString("session.length", "1 hour"), " ")[1]; session_length = Util.toSeconds(session_time,session_thelength); session_start = Util.checkSessionStart(getConfigString("session.start", "login")); guests_commands = getConfigBoolean("guest.commands", false); guests_movement = getConfigBoolean("guest.movement", false); guests_inventory = getConfigBoolean("guest.inventory", false); guests_drop = getConfigBoolean("guest.drop", false); guests_pickup = getConfigBoolean("guest.pickup", false); guests_health = getConfigBoolean("guest.health", false); guests_mobdamage = getConfigBoolean("guest.mobdamage", false); guests_interact = getConfigBoolean("guest.interactions", false); guests_build = getConfigBoolean("guest.building", false); guests_destroy = getConfigBoolean("guest.destruction", false); guests_chat = getConfigBoolean("guest.chat", false); guests_mobtargeting = getConfigBoolean("guest.mobtargeting", false); guests_pvp = getConfigBoolean("guest.pvp", false); - protection_freeze = getConfigBoolean("protection.freeze", true); + protection_freeze = getConfigBoolean("protection.freeze.enabled", true); protection_freeze_delay_length = Util.split(getConfigString("protection.freeze.delay", "2 seconds"), " ")[0]; protection_freeze_delay_time = Util.split(getConfigString("protection.freeze.delay", "2 seconds"), " ")[1]; protection_freeze_delay = Util.toSeconds(protection_freeze_delay_time, protection_freeze_delay_length); - protection_notify = getConfigBoolean("protection.notify", true); + protection_notify = getConfigBoolean("protection.notify.enabled", true); protection_notify_delay_length = Util.split(getConfigString("protection.notify.delay", "3 seconds"), " ")[0]; protection_notify_delay_time = Util.split(getConfigString("protection.notify.delay", "3 seconds"), " ")[1]; protection_notify_delay = Util.toSeconds(protection_notify_delay_time, protection_notify_delay_length); filter_action = Util.getAction(getConfigString("filter.action", "kick").toLowerCase()); filter_username = getConfigString("filter.username", "`~!@#$%^&*()-= + {[]}|\\:;\"<,>.?/"); filter_password = getConfigString("filter.password", "&"); filter_whitelist= getConfigString("filter.whitelist", ""); } else if (config.equalsIgnoreCase("plugins")) { CraftIRC_enabled = getConfigBoolean("CraftIRC.enabled", true); CraftIRC_tag = getConfigString("CraftIRC.tag", "admin"); CraftIRC_prefix = getConfigString("CraftIRC.prefix", "%b%%green%[{PLUGIN}]%k%%b%"); /* CraftIRC_messages_enabled = getConfigBoolean("CraftIRC.messages.enabled", true); CraftIRC_messages_welcome_enabled = getConfigBoolean("CraftIRC.messages.welcome", true); CraftIRC_messages_register_enabled = getConfigBoolean("CraftIRC.messages.register", true); CraftIRC_messages_unregister_enabled = getConfigBoolean("CraftIRC.messages.unregister", true); CraftIRC_messages_login_enabled = getConfigBoolean("CraftIRC.messages.login", true); CraftIRC_messages_email_enabled = getConfigBoolean("CraftIRC.messages.email", true); CraftIRC_messages_username_enabled = getConfigBoolean("CraftIRC.messages.username", true); CraftIRC_messages_password_enabled = getConfigBoolean("CraftIRC.messages.password", true); CraftIRC_messages_idle_enabled = getConfigBoolean("CraftIRC.messages.idle", true); */ } else if (config.equalsIgnoreCase("messages")) { Messages.time_millisecond = Config.getConfigString("Core.time.millisecond.", "millisecond"); Messages.time_milliseconds = Config.getConfigString("Core.time.milliseconds", "milliseconds"); Messages.time_second = Config.getConfigString("Core.time.second.", "second"); Messages.time_seconds = Config.getConfigString("Core.time.seconds", "seconds"); Messages.time_minute = Config.getConfigString("Core.time.minute.", "minute"); Messages.time_minutes = Config.getConfigString("Core.time.minutes", "minutes"); Messages.time_hour = Config.getConfigString("Core.time.hour.", "hour"); Messages.time_hours = Config.getConfigString("Core.time.hours", "hours"); Messages.time_day = Config.getConfigString("Core.time.day", "day"); Messages.time_days = Config.getConfigString("Core.time.days", "days"); Messages.AuthDB_message_reload_success = Config.getConfigString("Core.reload.success", "AuthDB has successfully reloaded!"); Messages.AuthDB_message_database_failure = Config.getConfigString("Core.database.failure", "{RED}database connection failed! Access is denied! Contact admin."); Messages.AuthDB_message_register_welcome = (String)Config.getConfigString("Core.register.welcome", "{YELLOW}Welcome {WHITE}guest{YELLOW}! Please use {REGISTERCMD} password email"); Messages.AuthDB_message_register_success = Config.getConfigString("Core.register.success", "{RED}You have been registered!"); Messages.AuthDB_message_register_failure = Config.getConfigString("Core.register.failure", "{RED}Registration failed!"); Messages.AuthDB_message_register_offline = Config.getConfigString("Core.register.offline", "{RED}Database is unavailable. Unable to verify password!"); Messages.AuthDB_message_register_exists = Config.getConfigString("Core.register.exists", "{RED}You are already registered!"); Messages.AuthDB_message_register_disabled = Config.getConfigString("Core.register.disabled", "{RED}Registration not allowed!"); Messages.AuthDB_message_register_usage = Config.getConfigString("Core.register.usage", "{RED}Correct usage is: /register password email"); Messages.AuthDB_message_register_timeout = Config.getConfigString("Core.register.timeout", "Kicked because you failed to register within {REGISTERTIMEOUT}."); Messages.AuthDB_message_unregister_success = Config.getConfigString("Core.unregister.success", "{BRIGHTGREEN}Unregistered successfully!"); Messages.AuthDB_message_unregister_failure = Config.getConfigString("Core.unregister.failure", "{RED}An error occurred while unregistering!"); Messages.AuthDB_message_unregister_usage = Config.getConfigString("Core.unregister.usage", "{RED}Correct usage is: /unregister password"); Messages.AuthDB_message_logout_success = Config.getConfigString("Core.logout.success", "Successfully logged out!"); Messages.AuthDB_message_logout_failure = Config.getConfigString("Core.logout.failure", "You are not logged in!"); Messages.AuthDB_message_logout_admin = Config.getConfigString("Core.logout.admin", "You have been logged out by an admin."); Messages.AuthDB_message_logout_admin_success = Config.getConfigString("Core.logout.adminsuccess", "Successfully logged out player, {PLAYER}."); Messages.AuthDB_message_logout_admin_failure = Config.getConfigString("Core.logout.adminfailure", "You cannot logout player, {PLAYER}! That player is not logged in"); Messages.AuthDB_message_logout_admin_notfound = Config.getConfigString("Core.logout.adminnotfound", "Could not find player, {PLAYER}! Please try again."); Messages.AuthDB_message_logout_usage = Config.getConfigString("Core.logout.usage", "{YELLOW}Correct usage is: {WHITE}{LOGOUTCMD}"); Messages.AuthDB_message_login_normal = Config.getConfigString("Core.login.normal", "{YELLOW}Welcome back {WHITE}{PLAYER}{YELLOW}! Please use /login password"); Messages.AuthDB_message_login_prompt = Config.getConfigString("Core.login.prompt", "{WHITE}Welcome {TEAL}{PLAYER}{WHITE}! Please enter your password:"); Messages.AuthDB_message_login_success = Config.getConfigString("Core.login.success", "{BRIGHTGREEN}Password accepted. Welcome!"); Messages.AuthDB_message_login_failure = Config.getConfigString("Core.login.failure", "{RED}Password incorrect, please try again."); Messages.AuthDB_message_login_offline = Config.getConfigString("Core.login.offline", "{RED}Database is unavailable. Unable to verify password!"); Messages.AuthDB_message_login_authorized = Config.getConfigString("Core.login.authorized", "{BRIGHTGREEN}You are already logged in!"); Messages.AuthDB_message_login_notregistered = Config.getConfigString("Core.login.notregistered", "{RED}You are not registred yet!"); Messages.AuthDB_message_login_timeout = Config.getConfigString("Core.login.timeout", "Kicked because you failed to login within {LOGINTIMEOUT}."); Messages.AuthDB_message_login_admin = Config.getConfigString("Core.login.admin", "You have been logged in by an admin."); Messages.AuthDB_message_login_admin_success = Config.getConfigString("Core.login.admin.success", "Successfully logged in player, {PLAYER}."); Messages.AuthDB_message_login_admin_failure = Config.getConfigString("Core.login.adminfailure", "You cannot login player {PLAYER}! That player is already logged in."); Messages.AuthDB_message_login_admin_notfound = Config.getConfigString("Core.login.adminnotfound", "Could not find player, {PLAYER}! Please try again."); Messages.AuthDB_message_login_usage = Config.getConfigString("Core.login.usage", "{RED}Correct usage is: /login password"); Messages.AuthDB_message_link_welcome = (String)Config.getConfigString("Core.link.welcome", "or {LINKCMD} otherusername password"); Messages.AuthDB_message_link_success = Config.getConfigString("Core.link.success", "{BRIGHTGREEN}You have successfully linked!. You are now logged in"); Messages.AuthDB_message_link_failure = Config.getConfigString("Core.link.failure", "{RED}Error while linking!"); Messages.AuthDB_message_link_exists = Config.getConfigString("Core.link.exists", "{RED}You are already linked to a username!"); Messages.AuthDB_message_link_duplicate = Config.getConfigString("Core.link.duplicate", "{RED}Username is already linked to another player!"); Messages.AuthDB_message_link_registred = Config.getConfigString("Core.link.registred", "{RED}You cannot link as this username is already registered!"); Messages.AuthDB_message_link_invaliduser = Config.getConfigString("Core.link.invaliduser", "{RED}You cannot link with yourself!"); Messages.AuthDB_message_link_usage = Config.getConfigString("Core.link.usage", "{RED}Correct usage is: /link otherusername password"); Messages.AuthDB_message_unlink_success = Config.getConfigString("Core.unlink.success", "{BRIGHTGREEN}You have successfully unlinked!"); Messages.AuthDB_message_unlink_failure = Config.getConfigString("Core.unlink.failure", "{RED}Error while unlinking!"); Messages.AuthDB_message_unlink_nonexist = Config.getConfigString("Core.unlink.nonexist", "{RED}You do not have a linked username!"); Messages.AuthDB_message_unlink_invaliduser = Config.getConfigString("Core.unlink.invaliduser", "{RED}Invalid linked username!"); Messages.AuthDB_message_unlink_invalidpass = Config.getConfigString("Core.unlink.invalidpass", "{RED}Invalid linked password!"); Messages.AuthDB_message_unlink_usage = Config.getConfigString("Core.unlink.usage", "{RED}Correct usage is: /unlink otherusername password"); Messages.AuthDB_message_email_required = Config.getConfigString("Core.email.required", "{RED}Email required for registration!"); Messages.AuthDB_message_email_invalid = Config.getConfigString("Core.email.invalid", "{RED}Invalid email! Please try again!"); Messages.AuthDB_message_email_badcharacters = Config.getConfigString("Core.email.badcharacters", "{RED}Email contains bad characters! {BADCHARACTERS}!"); Messages.AuthDB_message_filter_renamed = Config.getConfigString("Core.filter.renamed", "{RED}{PLAYER} renamed to {PLAYERNEW} due to bad characters: {USERBADCHARACTERS}."); Messages.AuthDB_message_filter_username = Config.getConfigString("Core.filter.username", "{RED}Username contains bad characters: {USERBADCHARACTERS}!"); Messages.AuthDB_message_filter_password = Config.getConfigString("Core.filter.password", "{RED}Password contains bad characters: {PASSBADCHARACTERS}!"); Messages.AuthDB_message_filter_whitelist = Config.getConfigString("Core.filter.whitelist", "{BRIGHTGREEN}{PLAYER} is on the filter {WHITE}whitelist{BRIGHTGREEN}, bypassing restrictions!"); Messages.AuthDB_message_username_minimum = Config.getConfigString("Core.username.minimum", "{RED}Your username does not meet the minimum requirement of {USERMIN} characters!"); Messages.AuthDB_message_username_maximum = Config.getConfigString("Core.username.maximum", "{RED}Your username does not meet the maximum requirement of {USERMAX} characters!"); Messages.AuthDB_message_password_minimum = Config.getConfigString("Core.password.minimum", "{RED}Your password does not meet the minimum requirement of {PASSMIN} characters!"); Messages.AuthDB_message_password_maximum = Config.getConfigString("Core.password.maximum", "{RED}Your password does not meet the maximum requirement of {PASSMAX} characters!"); Messages.AuthDB_message_password_success = Config.getConfigString("Core.password.success", "{BRIGHTGREEN}Password changed successfully!"); Messages.AuthDB_message_password_failure = Config.getConfigString("Core.password.failure", "{RED}Error! Password change failed!"); Messages.AuthDB_message_password_notregistered = Config.getConfigString("Core.password.notregistered", "{RED}Register first!"); Messages.AuthDB_message_password_usage = Config.getConfigString("Core.password.usage", "{RED}Correct usage is: /password oldpassword password"); Messages.AuthDB_message_session_valid = Config.getConfigString("Core.session.valid", "{BRIGHTGREEN}Hey, I remember you! You are logged in!"); Messages.AuthDB_message_session_protected = Config.getConfigString("Core.session.protected", "{RED}Sorry, a player with that name is already logged in on this server."); Messages.AuthDB_message_protection_denied = Config.getConfigString("Core.protection.denied", "You do not have permission to use that command."); Messages.AuthDB_message_protection_notauthorized = Config.getConfigString("Core.protection.notauthorized", "{RED}You are not authorized to do that!"); Messages.CraftIRC_message_status_join = Config.getConfigString("Plugins.CraftIRC.status.join", "{PLAYER} has joined the server."); Messages.CraftIRC_message_status_quit = Config.getConfigString("Plugins.CraftIRC.status.quit", "{PLAYER} has quit the server."); Messages.CraftIRC_message_register_success = Config.getConfigString("Plugins.CraftIRC.register.success", "{PLAYER} just registered successfully!"); Messages.CraftIRC_message_register_failure = Config.getConfigString("Plugins.CraftIRC.register.failure", "{PLAYER} had some errors while registering!"); Messages.CraftIRC_message_register_registered = Config.getConfigString("Plugins.CraftIRC.register.registered", "{PLAYER} had a lapse in memory and tried to register again."); Messages.CraftIRC_message_password_success = Config.getConfigString("Plugins.CraftIRC.password.success", "{PLAYER} logged in successfully!"); Messages.CraftIRC_message_password_failure = Config.getConfigString("Plugins.CraftIRC.password.failure", "{PLAYER} tried to login with the wrong password!"); Messages.CraftIRC_message_idle_kicked = Config.getConfigString("Plugins.CraftIRC.idle.kicked", "{PLAYER} was kicked due to bad characters in username!"); Messages.CraftIRC_message_idle_whitelist = Config.getConfigString("Plugins.CraftIRC.idle.whitelist", "{PLAYER} is on the on bad characters whitelist, bypassing restictions!"); Messages.CraftIRC_message_filter_renamed = Config.getConfigString("Plugins.CraftIRC.filter.renamed", "{PLAYER} renamed to {PLAYERNEW} due to bad characters."); Messages.CraftIRC_message_filter_kicked = Config.getConfigString("Plugins.CraftIRC.filter.kicked", "{PLAYER} was kicked due to bad characters in username!"); Messages.CraftIRC_message_filter_whitelist = Config.getConfigString("Plugins.CraftIRC.filter.whitelist", "{PLAYER} is on the on bad characters whitelist, bypassing restictions!"); } else if (config.equalsIgnoreCase("commands")) { commands_register = Config.getConfigString("Core.commands.register", "/register"); commands_link = Config.getConfigString("Core.commands.link", "/link"); commands_unlink = Config.getConfigString("Core.commands.unlink", "/unlink"); commands_login = Config.getConfigString("Core.commands.login", "/login"); commands_logout = Config.getConfigString("Core.commands.logout", "/logout"); commands_setspawn = Config.getConfigString("Core.commands.setspawn", "/authdb setspawn"); commands_reload = Config.getConfigString("Core.commands.reload", "/authdb reload"); aliases_register = Config.getConfigString("Core.aliases.register", "/r"); aliases_link = Config.getConfigString("Core.aliases.link", "/li"); aliases_unlink = Config.getConfigString("Core.aliases.unlink", "/ul"); aliases_login = Config.getConfigString("Core.aliases.login", "/l"); aliases_logout = Config.getConfigString("Core.aliases.logout", "/lo"); aliases_setspawn = Config.getConfigString("Core.aliases.setspawn", "/s"); aliases_reload = Config.getConfigString("Core.aliases.reload", "/ar"); } } public static String getConfigString(String key, String defaultvalue) { return template.getString(key, defaultvalue); } public static boolean getConfigBoolean(String key, boolean defaultvalue) { return template.getBoolean(key, defaultvalue); } public void deleteConfigValue(String key) { template.removeProperty(key); } public String raw(String key, String line) { return template.getString(key, line); } public void save(String key, String line) { template.setProperty(key, line); } }
false
true
public Config(String config, String directory, String filename) { template = new Configuration(new File(directory, filename)); template.load(); if (config.equalsIgnoreCase("basic")) { language = getConfigString("plugin.language", "English"); autoupdate_enable = getConfigBoolean("plugin.autoupdate", true); debug_enable = getConfigBoolean("plugin.debugmode", false); usagestats_enabled = getConfigBoolean("plugin.usagestats", true); logformat = getConfigString("plugin.logformat", "yyyy-MM-dd"); logging_enabled = getConfigBoolean("plugin.logging", true); database_type = getConfigString("database.type", "mysql"); database_username = getConfigString("database.username", "root"); database_password = getConfigString("database.password", ""); database_port = getConfigString("database.port", "3306"); database_host = getConfigString("database.host", "localhost"); database_database = getConfigString("database.name", "forum"); database_keepalive = getConfigBoolean("database.keepalive", false); dbDb = "jdbc:mysql://" + database_host + ":" + database_port + "/" + database_database; script_name = getConfigString("script.name", "phpbb").toLowerCase(); script_version = getConfigString("script.version", "3.0.8"); script_tableprefix = getConfigString("script.tableprefix", ""); script_updatestatus = getConfigBoolean("script.updatestatus", true); script_salt = getConfigString("script.salt", ""); } else if (config.equalsIgnoreCase("advanced")) { custom_enabled = getConfigBoolean("customdb.enabled", false); custom_autocreate = getConfigBoolean("customdb.autocreate", true); custom_emailrequired = getConfigBoolean("customdb.emailrequired", false); custom_table = getConfigString("customdb.table", "authdb_users"); custom_userfield = getConfigString("customdb.userfield", "username"); custom_passfield = getConfigString("customdb.passfield", "password"); custom_emailfield = getConfigString("customdb.emailfield", "email"); custom_encryption = getConfigString("customdb.encryption", "md5").toLowerCase(); register_enabled = getConfigBoolean("register.enabled", true); register_force = getConfigBoolean("register.force", true); register_delay_length = Util.split(getConfigString("register.delay", "4 seconds"), " ")[0]; register_delay_time = Util.split(getConfigString("register.delay", "4 seconds"), " ")[1]; register_delay = Util.toTicks(register_delay_time,register_delay_length); register_show_length = Util.split(getConfigString("register.show", "10 seconds"), " ")[0]; register_show_time = Util.split(getConfigString("register.show", "10 seconds"), " ")[1]; register_show = Util.toSeconds(register_show_time,register_show_length); register_timeout_length = Util.split(getConfigString("register.timeout", "3 minutes"), " ")[0]; register_timeout_time = Util.split(getConfigString("register.timeout", "3 minutes"), " ")[1]; register_timeout = Util.toTicks(register_timeout_time,register_timeout_length); login_method = getConfigString("login.method", "prompt"); login_tries = getConfigString("login.tries", "3"); login_action = Util.getAction(getConfigString("filter.action", "kick").toLowerCase()); login_delay_length = Util.split(getConfigString("login.delay", "4 seconds"), " ")[0]; login_delay_time = Util.split(getConfigString("login.delay", "4 seconds"), " ")[1]; login_delay = Util.toTicks(login_delay_time,login_delay_length); login_show_length = Util.split(getConfigString("login.show", "10 seconds"), " ")[0]; login_show_time = Util.split(getConfigString("login.show", "10 seconds"), " ")[1]; login_show = Util.toSeconds(login_show_time,login_show_length); login_timeout_length = Util.split(getConfigString("login.timeout", "3 minutes"), " ")[0]; login_timeout_time = Util.split(getConfigString("login.timeout", "3 minutes"), " ")[1]; login_timeout = Util.toTicks(login_timeout_time,login_timeout_length); link_enabled = getConfigBoolean("link.enabled", true); link_rename = getConfigBoolean("link.rename", true); unlink_enabled = getConfigBoolean("unlink.enabled", true); unlink_rename = getConfigBoolean("unlink.rename", true); username_minimum = getConfigString("username.minimum", "3"); username_maximum = getConfigString("username.maximum", "16"); password_minimum = getConfigString("password.minimum", "6"); password_maximum = getConfigString("password.maximum", "16"); session_enabled = getConfigBoolean("session.enabled", false); session_protect = getConfigBoolean("session.protect", true); session_thelength = Util.split(getConfigString("session.length", "1 hour"), " ")[0]; session_time = Util.split(getConfigString("session.length", "1 hour"), " ")[1]; session_length = Util.toSeconds(session_time,session_thelength); session_start = Util.checkSessionStart(getConfigString("session.start", "login")); guests_commands = getConfigBoolean("guest.commands", false); guests_movement = getConfigBoolean("guest.movement", false); guests_inventory = getConfigBoolean("guest.inventory", false); guests_drop = getConfigBoolean("guest.drop", false); guests_pickup = getConfigBoolean("guest.pickup", false); guests_health = getConfigBoolean("guest.health", false); guests_mobdamage = getConfigBoolean("guest.mobdamage", false); guests_interact = getConfigBoolean("guest.interactions", false); guests_build = getConfigBoolean("guest.building", false); guests_destroy = getConfigBoolean("guest.destruction", false); guests_chat = getConfigBoolean("guest.chat", false); guests_mobtargeting = getConfigBoolean("guest.mobtargeting", false); guests_pvp = getConfigBoolean("guest.pvp", false); protection_freeze = getConfigBoolean("protection.freeze", true); protection_freeze_delay_length = Util.split(getConfigString("protection.freeze.delay", "2 seconds"), " ")[0]; protection_freeze_delay_time = Util.split(getConfigString("protection.freeze.delay", "2 seconds"), " ")[1]; protection_freeze_delay = Util.toSeconds(protection_freeze_delay_time, protection_freeze_delay_length); protection_notify = getConfigBoolean("protection.notify", true); protection_notify_delay_length = Util.split(getConfigString("protection.notify.delay", "3 seconds"), " ")[0]; protection_notify_delay_time = Util.split(getConfigString("protection.notify.delay", "3 seconds"), " ")[1]; protection_notify_delay = Util.toSeconds(protection_notify_delay_time, protection_notify_delay_length); filter_action = Util.getAction(getConfigString("filter.action", "kick").toLowerCase()); filter_username = getConfigString("filter.username", "`~!@#$%^&*()-= + {[]}|\\:;\"<,>.?/"); filter_password = getConfigString("filter.password", "&"); filter_whitelist= getConfigString("filter.whitelist", ""); } else if (config.equalsIgnoreCase("plugins")) { CraftIRC_enabled = getConfigBoolean("CraftIRC.enabled", true); CraftIRC_tag = getConfigString("CraftIRC.tag", "admin"); CraftIRC_prefix = getConfigString("CraftIRC.prefix", "%b%%green%[{PLUGIN}]%k%%b%"); /* CraftIRC_messages_enabled = getConfigBoolean("CraftIRC.messages.enabled", true); CraftIRC_messages_welcome_enabled = getConfigBoolean("CraftIRC.messages.welcome", true); CraftIRC_messages_register_enabled = getConfigBoolean("CraftIRC.messages.register", true); CraftIRC_messages_unregister_enabled = getConfigBoolean("CraftIRC.messages.unregister", true); CraftIRC_messages_login_enabled = getConfigBoolean("CraftIRC.messages.login", true); CraftIRC_messages_email_enabled = getConfigBoolean("CraftIRC.messages.email", true); CraftIRC_messages_username_enabled = getConfigBoolean("CraftIRC.messages.username", true); CraftIRC_messages_password_enabled = getConfigBoolean("CraftIRC.messages.password", true); CraftIRC_messages_idle_enabled = getConfigBoolean("CraftIRC.messages.idle", true); */ } else if (config.equalsIgnoreCase("messages")) { Messages.time_millisecond = Config.getConfigString("Core.time.millisecond.", "millisecond"); Messages.time_milliseconds = Config.getConfigString("Core.time.milliseconds", "milliseconds"); Messages.time_second = Config.getConfigString("Core.time.second.", "second"); Messages.time_seconds = Config.getConfigString("Core.time.seconds", "seconds"); Messages.time_minute = Config.getConfigString("Core.time.minute.", "minute"); Messages.time_minutes = Config.getConfigString("Core.time.minutes", "minutes"); Messages.time_hour = Config.getConfigString("Core.time.hour.", "hour"); Messages.time_hours = Config.getConfigString("Core.time.hours", "hours"); Messages.time_day = Config.getConfigString("Core.time.day", "day"); Messages.time_days = Config.getConfigString("Core.time.days", "days"); Messages.AuthDB_message_reload_success = Config.getConfigString("Core.reload.success", "AuthDB has successfully reloaded!"); Messages.AuthDB_message_database_failure = Config.getConfigString("Core.database.failure", "{RED}database connection failed! Access is denied! Contact admin."); Messages.AuthDB_message_register_welcome = (String)Config.getConfigString("Core.register.welcome", "{YELLOW}Welcome {WHITE}guest{YELLOW}! Please use {REGISTERCMD} password email"); Messages.AuthDB_message_register_success = Config.getConfigString("Core.register.success", "{RED}You have been registered!"); Messages.AuthDB_message_register_failure = Config.getConfigString("Core.register.failure", "{RED}Registration failed!"); Messages.AuthDB_message_register_offline = Config.getConfigString("Core.register.offline", "{RED}Database is unavailable. Unable to verify password!"); Messages.AuthDB_message_register_exists = Config.getConfigString("Core.register.exists", "{RED}You are already registered!"); Messages.AuthDB_message_register_disabled = Config.getConfigString("Core.register.disabled", "{RED}Registration not allowed!"); Messages.AuthDB_message_register_usage = Config.getConfigString("Core.register.usage", "{RED}Correct usage is: /register password email"); Messages.AuthDB_message_register_timeout = Config.getConfigString("Core.register.timeout", "Kicked because you failed to register within {REGISTERTIMEOUT}."); Messages.AuthDB_message_unregister_success = Config.getConfigString("Core.unregister.success", "{BRIGHTGREEN}Unregistered successfully!"); Messages.AuthDB_message_unregister_failure = Config.getConfigString("Core.unregister.failure", "{RED}An error occurred while unregistering!"); Messages.AuthDB_message_unregister_usage = Config.getConfigString("Core.unregister.usage", "{RED}Correct usage is: /unregister password"); Messages.AuthDB_message_logout_success = Config.getConfigString("Core.logout.success", "Successfully logged out!"); Messages.AuthDB_message_logout_failure = Config.getConfigString("Core.logout.failure", "You are not logged in!"); Messages.AuthDB_message_logout_admin = Config.getConfigString("Core.logout.admin", "You have been logged out by an admin."); Messages.AuthDB_message_logout_admin_success = Config.getConfigString("Core.logout.adminsuccess", "Successfully logged out player, {PLAYER}."); Messages.AuthDB_message_logout_admin_failure = Config.getConfigString("Core.logout.adminfailure", "You cannot logout player, {PLAYER}! That player is not logged in"); Messages.AuthDB_message_logout_admin_notfound = Config.getConfigString("Core.logout.adminnotfound", "Could not find player, {PLAYER}! Please try again."); Messages.AuthDB_message_logout_usage = Config.getConfigString("Core.logout.usage", "{YELLOW}Correct usage is: {WHITE}{LOGOUTCMD}"); Messages.AuthDB_message_login_normal = Config.getConfigString("Core.login.normal", "{YELLOW}Welcome back {WHITE}{PLAYER}{YELLOW}! Please use /login password"); Messages.AuthDB_message_login_prompt = Config.getConfigString("Core.login.prompt", "{WHITE}Welcome {TEAL}{PLAYER}{WHITE}! Please enter your password:"); Messages.AuthDB_message_login_success = Config.getConfigString("Core.login.success", "{BRIGHTGREEN}Password accepted. Welcome!"); Messages.AuthDB_message_login_failure = Config.getConfigString("Core.login.failure", "{RED}Password incorrect, please try again."); Messages.AuthDB_message_login_offline = Config.getConfigString("Core.login.offline", "{RED}Database is unavailable. Unable to verify password!"); Messages.AuthDB_message_login_authorized = Config.getConfigString("Core.login.authorized", "{BRIGHTGREEN}You are already logged in!"); Messages.AuthDB_message_login_notregistered = Config.getConfigString("Core.login.notregistered", "{RED}You are not registred yet!"); Messages.AuthDB_message_login_timeout = Config.getConfigString("Core.login.timeout", "Kicked because you failed to login within {LOGINTIMEOUT}."); Messages.AuthDB_message_login_admin = Config.getConfigString("Core.login.admin", "You have been logged in by an admin."); Messages.AuthDB_message_login_admin_success = Config.getConfigString("Core.login.admin.success", "Successfully logged in player, {PLAYER}."); Messages.AuthDB_message_login_admin_failure = Config.getConfigString("Core.login.adminfailure", "You cannot login player {PLAYER}! That player is already logged in."); Messages.AuthDB_message_login_admin_notfound = Config.getConfigString("Core.login.adminnotfound", "Could not find player, {PLAYER}! Please try again."); Messages.AuthDB_message_login_usage = Config.getConfigString("Core.login.usage", "{RED}Correct usage is: /login password"); Messages.AuthDB_message_link_welcome = (String)Config.getConfigString("Core.link.welcome", "or {LINKCMD} otherusername password"); Messages.AuthDB_message_link_success = Config.getConfigString("Core.link.success", "{BRIGHTGREEN}You have successfully linked!. You are now logged in"); Messages.AuthDB_message_link_failure = Config.getConfigString("Core.link.failure", "{RED}Error while linking!"); Messages.AuthDB_message_link_exists = Config.getConfigString("Core.link.exists", "{RED}You are already linked to a username!"); Messages.AuthDB_message_link_duplicate = Config.getConfigString("Core.link.duplicate", "{RED}Username is already linked to another player!"); Messages.AuthDB_message_link_registred = Config.getConfigString("Core.link.registred", "{RED}You cannot link as this username is already registered!"); Messages.AuthDB_message_link_invaliduser = Config.getConfigString("Core.link.invaliduser", "{RED}You cannot link with yourself!"); Messages.AuthDB_message_link_usage = Config.getConfigString("Core.link.usage", "{RED}Correct usage is: /link otherusername password"); Messages.AuthDB_message_unlink_success = Config.getConfigString("Core.unlink.success", "{BRIGHTGREEN}You have successfully unlinked!"); Messages.AuthDB_message_unlink_failure = Config.getConfigString("Core.unlink.failure", "{RED}Error while unlinking!"); Messages.AuthDB_message_unlink_nonexist = Config.getConfigString("Core.unlink.nonexist", "{RED}You do not have a linked username!"); Messages.AuthDB_message_unlink_invaliduser = Config.getConfigString("Core.unlink.invaliduser", "{RED}Invalid linked username!"); Messages.AuthDB_message_unlink_invalidpass = Config.getConfigString("Core.unlink.invalidpass", "{RED}Invalid linked password!"); Messages.AuthDB_message_unlink_usage = Config.getConfigString("Core.unlink.usage", "{RED}Correct usage is: /unlink otherusername password"); Messages.AuthDB_message_email_required = Config.getConfigString("Core.email.required", "{RED}Email required for registration!"); Messages.AuthDB_message_email_invalid = Config.getConfigString("Core.email.invalid", "{RED}Invalid email! Please try again!"); Messages.AuthDB_message_email_badcharacters = Config.getConfigString("Core.email.badcharacters", "{RED}Email contains bad characters! {BADCHARACTERS}!"); Messages.AuthDB_message_filter_renamed = Config.getConfigString("Core.filter.renamed", "{RED}{PLAYER} renamed to {PLAYERNEW} due to bad characters: {USERBADCHARACTERS}."); Messages.AuthDB_message_filter_username = Config.getConfigString("Core.filter.username", "{RED}Username contains bad characters: {USERBADCHARACTERS}!"); Messages.AuthDB_message_filter_password = Config.getConfigString("Core.filter.password", "{RED}Password contains bad characters: {PASSBADCHARACTERS}!"); Messages.AuthDB_message_filter_whitelist = Config.getConfigString("Core.filter.whitelist", "{BRIGHTGREEN}{PLAYER} is on the filter {WHITE}whitelist{BRIGHTGREEN}, bypassing restrictions!"); Messages.AuthDB_message_username_minimum = Config.getConfigString("Core.username.minimum", "{RED}Your username does not meet the minimum requirement of {USERMIN} characters!"); Messages.AuthDB_message_username_maximum = Config.getConfigString("Core.username.maximum", "{RED}Your username does not meet the maximum requirement of {USERMAX} characters!"); Messages.AuthDB_message_password_minimum = Config.getConfigString("Core.password.minimum", "{RED}Your password does not meet the minimum requirement of {PASSMIN} characters!"); Messages.AuthDB_message_password_maximum = Config.getConfigString("Core.password.maximum", "{RED}Your password does not meet the maximum requirement of {PASSMAX} characters!"); Messages.AuthDB_message_password_success = Config.getConfigString("Core.password.success", "{BRIGHTGREEN}Password changed successfully!"); Messages.AuthDB_message_password_failure = Config.getConfigString("Core.password.failure", "{RED}Error! Password change failed!"); Messages.AuthDB_message_password_notregistered = Config.getConfigString("Core.password.notregistered", "{RED}Register first!"); Messages.AuthDB_message_password_usage = Config.getConfigString("Core.password.usage", "{RED}Correct usage is: /password oldpassword password"); Messages.AuthDB_message_session_valid = Config.getConfigString("Core.session.valid", "{BRIGHTGREEN}Hey, I remember you! You are logged in!"); Messages.AuthDB_message_session_protected = Config.getConfigString("Core.session.protected", "{RED}Sorry, a player with that name is already logged in on this server."); Messages.AuthDB_message_protection_denied = Config.getConfigString("Core.protection.denied", "You do not have permission to use that command."); Messages.AuthDB_message_protection_notauthorized = Config.getConfigString("Core.protection.notauthorized", "{RED}You are not authorized to do that!"); Messages.CraftIRC_message_status_join = Config.getConfigString("Plugins.CraftIRC.status.join", "{PLAYER} has joined the server."); Messages.CraftIRC_message_status_quit = Config.getConfigString("Plugins.CraftIRC.status.quit", "{PLAYER} has quit the server."); Messages.CraftIRC_message_register_success = Config.getConfigString("Plugins.CraftIRC.register.success", "{PLAYER} just registered successfully!"); Messages.CraftIRC_message_register_failure = Config.getConfigString("Plugins.CraftIRC.register.failure", "{PLAYER} had some errors while registering!"); Messages.CraftIRC_message_register_registered = Config.getConfigString("Plugins.CraftIRC.register.registered", "{PLAYER} had a lapse in memory and tried to register again."); Messages.CraftIRC_message_password_success = Config.getConfigString("Plugins.CraftIRC.password.success", "{PLAYER} logged in successfully!"); Messages.CraftIRC_message_password_failure = Config.getConfigString("Plugins.CraftIRC.password.failure", "{PLAYER} tried to login with the wrong password!"); Messages.CraftIRC_message_idle_kicked = Config.getConfigString("Plugins.CraftIRC.idle.kicked", "{PLAYER} was kicked due to bad characters in username!"); Messages.CraftIRC_message_idle_whitelist = Config.getConfigString("Plugins.CraftIRC.idle.whitelist", "{PLAYER} is on the on bad characters whitelist, bypassing restictions!"); Messages.CraftIRC_message_filter_renamed = Config.getConfigString("Plugins.CraftIRC.filter.renamed", "{PLAYER} renamed to {PLAYERNEW} due to bad characters."); Messages.CraftIRC_message_filter_kicked = Config.getConfigString("Plugins.CraftIRC.filter.kicked", "{PLAYER} was kicked due to bad characters in username!"); Messages.CraftIRC_message_filter_whitelist = Config.getConfigString("Plugins.CraftIRC.filter.whitelist", "{PLAYER} is on the on bad characters whitelist, bypassing restictions!"); } else if (config.equalsIgnoreCase("commands")) { commands_register = Config.getConfigString("Core.commands.register", "/register"); commands_link = Config.getConfigString("Core.commands.link", "/link"); commands_unlink = Config.getConfigString("Core.commands.unlink", "/unlink"); commands_login = Config.getConfigString("Core.commands.login", "/login"); commands_logout = Config.getConfigString("Core.commands.logout", "/logout"); commands_setspawn = Config.getConfigString("Core.commands.setspawn", "/authdb setspawn"); commands_reload = Config.getConfigString("Core.commands.reload", "/authdb reload"); aliases_register = Config.getConfigString("Core.aliases.register", "/r"); aliases_link = Config.getConfigString("Core.aliases.link", "/li"); aliases_unlink = Config.getConfigString("Core.aliases.unlink", "/ul"); aliases_login = Config.getConfigString("Core.aliases.login", "/l"); aliases_logout = Config.getConfigString("Core.aliases.logout", "/lo"); aliases_setspawn = Config.getConfigString("Core.aliases.setspawn", "/s"); aliases_reload = Config.getConfigString("Core.aliases.reload", "/ar"); } }
public Config(String config, String directory, String filename) { template = new Configuration(new File(directory, filename)); template.load(); if (config.equalsIgnoreCase("basic")) { language = getConfigString("plugin.language", "English"); autoupdate_enable = getConfigBoolean("plugin.autoupdate", true); debug_enable = getConfigBoolean("plugin.debugmode", false); usagestats_enabled = getConfigBoolean("plugin.usagestats", true); logformat = getConfigString("plugin.logformat", "yyyy-MM-dd"); logging_enabled = getConfigBoolean("plugin.logging", true); database_type = getConfigString("database.type", "mysql"); database_username = getConfigString("database.username", "root"); database_password = getConfigString("database.password", ""); database_port = getConfigString("database.port", "3306"); database_host = getConfigString("database.host", "localhost"); database_database = getConfigString("database.name", "forum"); database_keepalive = getConfigBoolean("database.keepalive", false); dbDb = "jdbc:mysql://" + database_host + ":" + database_port + "/" + database_database; script_name = getConfigString("script.name", "phpbb").toLowerCase(); script_version = getConfigString("script.version", "3.0.8"); script_tableprefix = getConfigString("script.tableprefix", ""); script_updatestatus = getConfigBoolean("script.updatestatus", true); script_salt = getConfigString("script.salt", ""); } else if (config.equalsIgnoreCase("advanced")) { custom_enabled = getConfigBoolean("customdb.enabled", false); custom_autocreate = getConfigBoolean("customdb.autocreate", true); custom_emailrequired = getConfigBoolean("customdb.emailrequired", false); custom_table = getConfigString("customdb.table", "authdb_users"); custom_userfield = getConfigString("customdb.userfield", "username"); custom_passfield = getConfigString("customdb.passfield", "password"); custom_emailfield = getConfigString("customdb.emailfield", "email"); custom_encryption = getConfigString("customdb.encryption", "md5").toLowerCase(); register_enabled = getConfigBoolean("register.enabled", true); register_force = getConfigBoolean("register.force", true); register_delay_length = Util.split(getConfigString("register.delay", "4 seconds"), " ")[0]; register_delay_time = Util.split(getConfigString("register.delay", "4 seconds"), " ")[1]; register_delay = Util.toTicks(register_delay_time,register_delay_length); register_show_length = Util.split(getConfigString("register.show", "10 seconds"), " ")[0]; register_show_time = Util.split(getConfigString("register.show", "10 seconds"), " ")[1]; register_show = Util.toSeconds(register_show_time,register_show_length); register_timeout_length = Util.split(getConfigString("register.timeout", "3 minutes"), " ")[0]; register_timeout_time = Util.split(getConfigString("register.timeout", "3 minutes"), " ")[1]; register_timeout = Util.toTicks(register_timeout_time,register_timeout_length); login_method = getConfigString("login.method", "prompt"); login_tries = getConfigString("login.tries", "3"); login_action = Util.getAction(getConfigString("filter.action", "kick").toLowerCase()); login_delay_length = Util.split(getConfigString("login.delay", "4 seconds"), " ")[0]; login_delay_time = Util.split(getConfigString("login.delay", "4 seconds"), " ")[1]; login_delay = Util.toTicks(login_delay_time,login_delay_length); login_show_length = Util.split(getConfigString("login.show", "10 seconds"), " ")[0]; login_show_time = Util.split(getConfigString("login.show", "10 seconds"), " ")[1]; login_show = Util.toSeconds(login_show_time,login_show_length); login_timeout_length = Util.split(getConfigString("login.timeout", "3 minutes"), " ")[0]; login_timeout_time = Util.split(getConfigString("login.timeout", "3 minutes"), " ")[1]; login_timeout = Util.toTicks(login_timeout_time,login_timeout_length); link_enabled = getConfigBoolean("link.enabled", true); link_rename = getConfigBoolean("link.rename", true); unlink_enabled = getConfigBoolean("unlink.enabled", true); unlink_rename = getConfigBoolean("unlink.rename", true); username_minimum = getConfigString("username.minimum", "3"); username_maximum = getConfigString("username.maximum", "16"); password_minimum = getConfigString("password.minimum", "6"); password_maximum = getConfigString("password.maximum", "16"); session_enabled = getConfigBoolean("session.enabled", false); session_protect = getConfigBoolean("session.protect", true); session_thelength = Util.split(getConfigString("session.length", "1 hour"), " ")[0]; session_time = Util.split(getConfigString("session.length", "1 hour"), " ")[1]; session_length = Util.toSeconds(session_time,session_thelength); session_start = Util.checkSessionStart(getConfigString("session.start", "login")); guests_commands = getConfigBoolean("guest.commands", false); guests_movement = getConfigBoolean("guest.movement", false); guests_inventory = getConfigBoolean("guest.inventory", false); guests_drop = getConfigBoolean("guest.drop", false); guests_pickup = getConfigBoolean("guest.pickup", false); guests_health = getConfigBoolean("guest.health", false); guests_mobdamage = getConfigBoolean("guest.mobdamage", false); guests_interact = getConfigBoolean("guest.interactions", false); guests_build = getConfigBoolean("guest.building", false); guests_destroy = getConfigBoolean("guest.destruction", false); guests_chat = getConfigBoolean("guest.chat", false); guests_mobtargeting = getConfigBoolean("guest.mobtargeting", false); guests_pvp = getConfigBoolean("guest.pvp", false); protection_freeze = getConfigBoolean("protection.freeze.enabled", true); protection_freeze_delay_length = Util.split(getConfigString("protection.freeze.delay", "2 seconds"), " ")[0]; protection_freeze_delay_time = Util.split(getConfigString("protection.freeze.delay", "2 seconds"), " ")[1]; protection_freeze_delay = Util.toSeconds(protection_freeze_delay_time, protection_freeze_delay_length); protection_notify = getConfigBoolean("protection.notify.enabled", true); protection_notify_delay_length = Util.split(getConfigString("protection.notify.delay", "3 seconds"), " ")[0]; protection_notify_delay_time = Util.split(getConfigString("protection.notify.delay", "3 seconds"), " ")[1]; protection_notify_delay = Util.toSeconds(protection_notify_delay_time, protection_notify_delay_length); filter_action = Util.getAction(getConfigString("filter.action", "kick").toLowerCase()); filter_username = getConfigString("filter.username", "`~!@#$%^&*()-= + {[]}|\\:;\"<,>.?/"); filter_password = getConfigString("filter.password", "&"); filter_whitelist= getConfigString("filter.whitelist", ""); } else if (config.equalsIgnoreCase("plugins")) { CraftIRC_enabled = getConfigBoolean("CraftIRC.enabled", true); CraftIRC_tag = getConfigString("CraftIRC.tag", "admin"); CraftIRC_prefix = getConfigString("CraftIRC.prefix", "%b%%green%[{PLUGIN}]%k%%b%"); /* CraftIRC_messages_enabled = getConfigBoolean("CraftIRC.messages.enabled", true); CraftIRC_messages_welcome_enabled = getConfigBoolean("CraftIRC.messages.welcome", true); CraftIRC_messages_register_enabled = getConfigBoolean("CraftIRC.messages.register", true); CraftIRC_messages_unregister_enabled = getConfigBoolean("CraftIRC.messages.unregister", true); CraftIRC_messages_login_enabled = getConfigBoolean("CraftIRC.messages.login", true); CraftIRC_messages_email_enabled = getConfigBoolean("CraftIRC.messages.email", true); CraftIRC_messages_username_enabled = getConfigBoolean("CraftIRC.messages.username", true); CraftIRC_messages_password_enabled = getConfigBoolean("CraftIRC.messages.password", true); CraftIRC_messages_idle_enabled = getConfigBoolean("CraftIRC.messages.idle", true); */ } else if (config.equalsIgnoreCase("messages")) { Messages.time_millisecond = Config.getConfigString("Core.time.millisecond.", "millisecond"); Messages.time_milliseconds = Config.getConfigString("Core.time.milliseconds", "milliseconds"); Messages.time_second = Config.getConfigString("Core.time.second.", "second"); Messages.time_seconds = Config.getConfigString("Core.time.seconds", "seconds"); Messages.time_minute = Config.getConfigString("Core.time.minute.", "minute"); Messages.time_minutes = Config.getConfigString("Core.time.minutes", "minutes"); Messages.time_hour = Config.getConfigString("Core.time.hour.", "hour"); Messages.time_hours = Config.getConfigString("Core.time.hours", "hours"); Messages.time_day = Config.getConfigString("Core.time.day", "day"); Messages.time_days = Config.getConfigString("Core.time.days", "days"); Messages.AuthDB_message_reload_success = Config.getConfigString("Core.reload.success", "AuthDB has successfully reloaded!"); Messages.AuthDB_message_database_failure = Config.getConfigString("Core.database.failure", "{RED}database connection failed! Access is denied! Contact admin."); Messages.AuthDB_message_register_welcome = (String)Config.getConfigString("Core.register.welcome", "{YELLOW}Welcome {WHITE}guest{YELLOW}! Please use {REGISTERCMD} password email"); Messages.AuthDB_message_register_success = Config.getConfigString("Core.register.success", "{RED}You have been registered!"); Messages.AuthDB_message_register_failure = Config.getConfigString("Core.register.failure", "{RED}Registration failed!"); Messages.AuthDB_message_register_offline = Config.getConfigString("Core.register.offline", "{RED}Database is unavailable. Unable to verify password!"); Messages.AuthDB_message_register_exists = Config.getConfigString("Core.register.exists", "{RED}You are already registered!"); Messages.AuthDB_message_register_disabled = Config.getConfigString("Core.register.disabled", "{RED}Registration not allowed!"); Messages.AuthDB_message_register_usage = Config.getConfigString("Core.register.usage", "{RED}Correct usage is: /register password email"); Messages.AuthDB_message_register_timeout = Config.getConfigString("Core.register.timeout", "Kicked because you failed to register within {REGISTERTIMEOUT}."); Messages.AuthDB_message_unregister_success = Config.getConfigString("Core.unregister.success", "{BRIGHTGREEN}Unregistered successfully!"); Messages.AuthDB_message_unregister_failure = Config.getConfigString("Core.unregister.failure", "{RED}An error occurred while unregistering!"); Messages.AuthDB_message_unregister_usage = Config.getConfigString("Core.unregister.usage", "{RED}Correct usage is: /unregister password"); Messages.AuthDB_message_logout_success = Config.getConfigString("Core.logout.success", "Successfully logged out!"); Messages.AuthDB_message_logout_failure = Config.getConfigString("Core.logout.failure", "You are not logged in!"); Messages.AuthDB_message_logout_admin = Config.getConfigString("Core.logout.admin", "You have been logged out by an admin."); Messages.AuthDB_message_logout_admin_success = Config.getConfigString("Core.logout.adminsuccess", "Successfully logged out player, {PLAYER}."); Messages.AuthDB_message_logout_admin_failure = Config.getConfigString("Core.logout.adminfailure", "You cannot logout player, {PLAYER}! That player is not logged in"); Messages.AuthDB_message_logout_admin_notfound = Config.getConfigString("Core.logout.adminnotfound", "Could not find player, {PLAYER}! Please try again."); Messages.AuthDB_message_logout_usage = Config.getConfigString("Core.logout.usage", "{YELLOW}Correct usage is: {WHITE}{LOGOUTCMD}"); Messages.AuthDB_message_login_normal = Config.getConfigString("Core.login.normal", "{YELLOW}Welcome back {WHITE}{PLAYER}{YELLOW}! Please use /login password"); Messages.AuthDB_message_login_prompt = Config.getConfigString("Core.login.prompt", "{WHITE}Welcome {TEAL}{PLAYER}{WHITE}! Please enter your password:"); Messages.AuthDB_message_login_success = Config.getConfigString("Core.login.success", "{BRIGHTGREEN}Password accepted. Welcome!"); Messages.AuthDB_message_login_failure = Config.getConfigString("Core.login.failure", "{RED}Password incorrect, please try again."); Messages.AuthDB_message_login_offline = Config.getConfigString("Core.login.offline", "{RED}Database is unavailable. Unable to verify password!"); Messages.AuthDB_message_login_authorized = Config.getConfigString("Core.login.authorized", "{BRIGHTGREEN}You are already logged in!"); Messages.AuthDB_message_login_notregistered = Config.getConfigString("Core.login.notregistered", "{RED}You are not registred yet!"); Messages.AuthDB_message_login_timeout = Config.getConfigString("Core.login.timeout", "Kicked because you failed to login within {LOGINTIMEOUT}."); Messages.AuthDB_message_login_admin = Config.getConfigString("Core.login.admin", "You have been logged in by an admin."); Messages.AuthDB_message_login_admin_success = Config.getConfigString("Core.login.admin.success", "Successfully logged in player, {PLAYER}."); Messages.AuthDB_message_login_admin_failure = Config.getConfigString("Core.login.adminfailure", "You cannot login player {PLAYER}! That player is already logged in."); Messages.AuthDB_message_login_admin_notfound = Config.getConfigString("Core.login.adminnotfound", "Could not find player, {PLAYER}! Please try again."); Messages.AuthDB_message_login_usage = Config.getConfigString("Core.login.usage", "{RED}Correct usage is: /login password"); Messages.AuthDB_message_link_welcome = (String)Config.getConfigString("Core.link.welcome", "or {LINKCMD} otherusername password"); Messages.AuthDB_message_link_success = Config.getConfigString("Core.link.success", "{BRIGHTGREEN}You have successfully linked!. You are now logged in"); Messages.AuthDB_message_link_failure = Config.getConfigString("Core.link.failure", "{RED}Error while linking!"); Messages.AuthDB_message_link_exists = Config.getConfigString("Core.link.exists", "{RED}You are already linked to a username!"); Messages.AuthDB_message_link_duplicate = Config.getConfigString("Core.link.duplicate", "{RED}Username is already linked to another player!"); Messages.AuthDB_message_link_registred = Config.getConfigString("Core.link.registred", "{RED}You cannot link as this username is already registered!"); Messages.AuthDB_message_link_invaliduser = Config.getConfigString("Core.link.invaliduser", "{RED}You cannot link with yourself!"); Messages.AuthDB_message_link_usage = Config.getConfigString("Core.link.usage", "{RED}Correct usage is: /link otherusername password"); Messages.AuthDB_message_unlink_success = Config.getConfigString("Core.unlink.success", "{BRIGHTGREEN}You have successfully unlinked!"); Messages.AuthDB_message_unlink_failure = Config.getConfigString("Core.unlink.failure", "{RED}Error while unlinking!"); Messages.AuthDB_message_unlink_nonexist = Config.getConfigString("Core.unlink.nonexist", "{RED}You do not have a linked username!"); Messages.AuthDB_message_unlink_invaliduser = Config.getConfigString("Core.unlink.invaliduser", "{RED}Invalid linked username!"); Messages.AuthDB_message_unlink_invalidpass = Config.getConfigString("Core.unlink.invalidpass", "{RED}Invalid linked password!"); Messages.AuthDB_message_unlink_usage = Config.getConfigString("Core.unlink.usage", "{RED}Correct usage is: /unlink otherusername password"); Messages.AuthDB_message_email_required = Config.getConfigString("Core.email.required", "{RED}Email required for registration!"); Messages.AuthDB_message_email_invalid = Config.getConfigString("Core.email.invalid", "{RED}Invalid email! Please try again!"); Messages.AuthDB_message_email_badcharacters = Config.getConfigString("Core.email.badcharacters", "{RED}Email contains bad characters! {BADCHARACTERS}!"); Messages.AuthDB_message_filter_renamed = Config.getConfigString("Core.filter.renamed", "{RED}{PLAYER} renamed to {PLAYERNEW} due to bad characters: {USERBADCHARACTERS}."); Messages.AuthDB_message_filter_username = Config.getConfigString("Core.filter.username", "{RED}Username contains bad characters: {USERBADCHARACTERS}!"); Messages.AuthDB_message_filter_password = Config.getConfigString("Core.filter.password", "{RED}Password contains bad characters: {PASSBADCHARACTERS}!"); Messages.AuthDB_message_filter_whitelist = Config.getConfigString("Core.filter.whitelist", "{BRIGHTGREEN}{PLAYER} is on the filter {WHITE}whitelist{BRIGHTGREEN}, bypassing restrictions!"); Messages.AuthDB_message_username_minimum = Config.getConfigString("Core.username.minimum", "{RED}Your username does not meet the minimum requirement of {USERMIN} characters!"); Messages.AuthDB_message_username_maximum = Config.getConfigString("Core.username.maximum", "{RED}Your username does not meet the maximum requirement of {USERMAX} characters!"); Messages.AuthDB_message_password_minimum = Config.getConfigString("Core.password.minimum", "{RED}Your password does not meet the minimum requirement of {PASSMIN} characters!"); Messages.AuthDB_message_password_maximum = Config.getConfigString("Core.password.maximum", "{RED}Your password does not meet the maximum requirement of {PASSMAX} characters!"); Messages.AuthDB_message_password_success = Config.getConfigString("Core.password.success", "{BRIGHTGREEN}Password changed successfully!"); Messages.AuthDB_message_password_failure = Config.getConfigString("Core.password.failure", "{RED}Error! Password change failed!"); Messages.AuthDB_message_password_notregistered = Config.getConfigString("Core.password.notregistered", "{RED}Register first!"); Messages.AuthDB_message_password_usage = Config.getConfigString("Core.password.usage", "{RED}Correct usage is: /password oldpassword password"); Messages.AuthDB_message_session_valid = Config.getConfigString("Core.session.valid", "{BRIGHTGREEN}Hey, I remember you! You are logged in!"); Messages.AuthDB_message_session_protected = Config.getConfigString("Core.session.protected", "{RED}Sorry, a player with that name is already logged in on this server."); Messages.AuthDB_message_protection_denied = Config.getConfigString("Core.protection.denied", "You do not have permission to use that command."); Messages.AuthDB_message_protection_notauthorized = Config.getConfigString("Core.protection.notauthorized", "{RED}You are not authorized to do that!"); Messages.CraftIRC_message_status_join = Config.getConfigString("Plugins.CraftIRC.status.join", "{PLAYER} has joined the server."); Messages.CraftIRC_message_status_quit = Config.getConfigString("Plugins.CraftIRC.status.quit", "{PLAYER} has quit the server."); Messages.CraftIRC_message_register_success = Config.getConfigString("Plugins.CraftIRC.register.success", "{PLAYER} just registered successfully!"); Messages.CraftIRC_message_register_failure = Config.getConfigString("Plugins.CraftIRC.register.failure", "{PLAYER} had some errors while registering!"); Messages.CraftIRC_message_register_registered = Config.getConfigString("Plugins.CraftIRC.register.registered", "{PLAYER} had a lapse in memory and tried to register again."); Messages.CraftIRC_message_password_success = Config.getConfigString("Plugins.CraftIRC.password.success", "{PLAYER} logged in successfully!"); Messages.CraftIRC_message_password_failure = Config.getConfigString("Plugins.CraftIRC.password.failure", "{PLAYER} tried to login with the wrong password!"); Messages.CraftIRC_message_idle_kicked = Config.getConfigString("Plugins.CraftIRC.idle.kicked", "{PLAYER} was kicked due to bad characters in username!"); Messages.CraftIRC_message_idle_whitelist = Config.getConfigString("Plugins.CraftIRC.idle.whitelist", "{PLAYER} is on the on bad characters whitelist, bypassing restictions!"); Messages.CraftIRC_message_filter_renamed = Config.getConfigString("Plugins.CraftIRC.filter.renamed", "{PLAYER} renamed to {PLAYERNEW} due to bad characters."); Messages.CraftIRC_message_filter_kicked = Config.getConfigString("Plugins.CraftIRC.filter.kicked", "{PLAYER} was kicked due to bad characters in username!"); Messages.CraftIRC_message_filter_whitelist = Config.getConfigString("Plugins.CraftIRC.filter.whitelist", "{PLAYER} is on the on bad characters whitelist, bypassing restictions!"); } else if (config.equalsIgnoreCase("commands")) { commands_register = Config.getConfigString("Core.commands.register", "/register"); commands_link = Config.getConfigString("Core.commands.link", "/link"); commands_unlink = Config.getConfigString("Core.commands.unlink", "/unlink"); commands_login = Config.getConfigString("Core.commands.login", "/login"); commands_logout = Config.getConfigString("Core.commands.logout", "/logout"); commands_setspawn = Config.getConfigString("Core.commands.setspawn", "/authdb setspawn"); commands_reload = Config.getConfigString("Core.commands.reload", "/authdb reload"); aliases_register = Config.getConfigString("Core.aliases.register", "/r"); aliases_link = Config.getConfigString("Core.aliases.link", "/li"); aliases_unlink = Config.getConfigString("Core.aliases.unlink", "/ul"); aliases_login = Config.getConfigString("Core.aliases.login", "/l"); aliases_logout = Config.getConfigString("Core.aliases.logout", "/lo"); aliases_setspawn = Config.getConfigString("Core.aliases.setspawn", "/s"); aliases_reload = Config.getConfigString("Core.aliases.reload", "/ar"); } }
diff --git a/Pigeon/trunk/src/pigeon/About.java b/Pigeon/trunk/src/pigeon/About.java index af734c6..75ede55 100644 --- a/Pigeon/trunk/src/pigeon/About.java +++ b/Pigeon/trunk/src/pigeon/About.java @@ -1,90 +1,93 @@ /* Copyright (C) 2005, 2006, 2007 Paul Richards. 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 pigeon; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; -import java.io.Reader; +import java.io.PrintWriter; +import java.io.StringWriter; /** Provides access to the public information about the program. */ public final class About { public static final String VERSION = "0.3" + " (build " + getBuildId() + ")"; public static final String TITLE = "RacePoint v" + VERSION; public static final String CREDITS = "Created by Paul Richards <[email protected]>."; // NonCreatable private About() { } /** Attempt to read the Subversion ID from the BuildID.txt file inside the Jar file. Returns "unknown" if this cannot be found. */ public static String getBuildId() { InputStream in = ClassLoader.getSystemResourceAsStream("BuildID.txt"); try { if (in != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String buildId = reader.readLine(); if (buildId != null) { return buildId; } } } catch (IOException e) { } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } } return "unknown"; } /** Returns a copy of the license. */ public static String getLicense() { - StringBuffer result = new StringBuffer(); - result.println("Copyright (C) 2005, 2006, 2007 Paul Richards."); - result.println(); - result.println("This program is free software: you can redistribute it and/or modify"); - result.println("it under the terms of the GNU General Public License as published by"); - result.println("the Free Software Foundation, either version 3 of the License, or"); - result.println("(at your option) any later version."); - result.println(); - result.println("This program is distributed in the hope that it will be useful,"); - result.println("but WITHOUT ANY WARRANTY; without even the implied warranty of"); - result.println("MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the"); - result.println("GNU General Public License for more details."); - result.println(); - result.println("You should have received a copy of the GNU General Public License"); - result.println("along with this program. If not, see <http://www.gnu.org/licenses/>."); - return result.toString(); + StringWriter string = new StringWriter(); + PrintWriter writer = new PrintWriter(string); + writer.println("Copyright (C) 2005, 2006, 2007 Paul Richards."); + writer.println(); + writer.println("This program is free software: you can redistribute it and/or modify"); + writer.println("it under the terms of the GNU General Public License as published by"); + writer.println("the Free Software Foundation, either version 3 of the License, or"); + writer.println("(at your option) any later version."); + writer.println(); + writer.println("This program is distributed in the hope that it will be useful,"); + writer.println("but WITHOUT ANY WARRANTY; without even the implied warranty of"); + writer.println("MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the"); + writer.println("GNU General Public License for more details."); + writer.println(); + writer.println("You should have received a copy of the GNU General Public License"); + writer.println("along with this program. If not, see <http://www.gnu.org/licenses/>."); + writer.close(); + return string.toString(); } }
false
false
null
null
diff --git a/src/main/java/net/dandielo/citizens/traders_v3/utils/ItemUtils.java b/src/main/java/net/dandielo/citizens/traders_v3/utils/ItemUtils.java index cd91586..ffe547a 100644 --- a/src/main/java/net/dandielo/citizens/traders_v3/utils/ItemUtils.java +++ b/src/main/java/net/dandielo/citizens/traders_v3/utils/ItemUtils.java @@ -1,69 +1,69 @@ package net.dandielo.citizens.traders_v3.utils; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; import net.dandielo.citizens.traders_v3.bankers.tabs.BankItem; import net.dandielo.citizens.traders_v3.traders.stock.StockItem; @SuppressWarnings("deprecation") public class ItemUtils { //durability check public static boolean itemHasDurability(ItemStack item) { int id = item.getTypeId(); return ( id >= 256 && id <= 259 ) || id == 261 || ( id >= 267 && id <= 279 ) || ( id >= 283 && id <= 286 ) || ( id >= 290 && id <= 294 ) || ( id >= 298 && id <= 317 ) || id == 398;// ? true : false ); } public static StockItem createStockItem(ItemStack vItem) { ItemStack clone = vItem.clone(); //creating a clean item StockItem sItem = new StockItem(clone); //getting data out of it (by force ;>) sItem.factorize(clone); //returning the item return sItem; } public static StockItem createAbstractStockItem(ItemStack vItem) { ItemStack clone = vItem.clone(); //creating a clean item StockItem sItem = new StockItem(clone); //set the item as abstract sItem.addFlag(".abstract"); //getting data out of it (by force ;>) sItem.factorize(clone); //returning the item return sItem; } //create ItemStack public static ItemStack createItemStack(String data) { String[] d = data.split(":", 2); Material mat = Material.getMaterial(d[0].toUpperCase()); if ( mat == null ) mat = Material.getMaterial(Integer.parseInt(d[0])); if ( d.length > 1 ) - return new ItemStack(mat, 1, Byte.parseByte(d[1])); + return new ItemStack(mat, 1, Short.parseShort(d[1])); else return new ItemStack(mat); } public static BankItem createBankItem(ItemStack vItem) { //creating a clean item BankItem bItem = new BankItem(vItem); //getting data out of it (by force ;>) bItem.factorize(vItem); //returning the item return bItem; } } diff --git a/src/main/java/net/dandielo/citizens/traders_v3/utils/items/attributes/Potion.java b/src/main/java/net/dandielo/citizens/traders_v3/utils/items/attributes/Potion.java index fd540d7..e3aa1e3 100644 --- a/src/main/java/net/dandielo/citizens/traders_v3/utils/items/attributes/Potion.java +++ b/src/main/java/net/dandielo/citizens/traders_v3/utils/items/attributes/Potion.java @@ -1,110 +1,110 @@ package net.dandielo.citizens.traders_v3.utils.items.attributes; import java.util.ArrayList; import java.util.List; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.PotionMeta; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import net.dandielo.citizens.traders_v3.core.exceptions.InvalidItemException; import net.dandielo.citizens.traders_v3.core.exceptions.attributes.AttributeInvalidValueException; import net.dandielo.citizens.traders_v3.core.exceptions.attributes.AttributeValueNotFoundException; import net.dandielo.citizens.traders_v3.utils.items.Attribute; import net.dandielo.citizens.traders_v3.utils.items.ItemAttr; @Attribute(name="Potion", key="pt", priority = 5) public class Potion extends ItemAttr { /** * List of all potion effect for this potion item */ private List<PotionEffect> effects = new ArrayList<PotionEffect>(); /** * Potion attribute constructor, default values * @param key */ public Potion(String key) { super(key); } @Override public void onLoad(String data) throws AttributeInvalidValueException { String[] savedEffects = data.split(","); for ( String savedEffect : savedEffects ) { String[] effectData = savedEffect.split("/"); PotionEffect effect = new PotionEffect( - PotionEffectType.getById(Integer.parseInt(effectData[0])), + PotionEffectType.getByName(effectData[0]), Integer.parseInt(effectData[1]), Integer.parseInt(effectData[2]), Boolean.parseBoolean(effectData[3])); effects.add(effect); } } @Override public String onSave() { String result = ""; //save each potion effect with a comma separated for ( PotionEffect e : effects ) - result += "," + e.getType().getId() + "/" + e.getDuration() + "/" + e.getAmplifier() + "/" + e.isAmbient(); + result += "," + e.getType().getName() + "/" + e.getDuration() + "/" + e.getAmplifier() + "/" + e.isAmbient(); return result.substring(1); } @Override public void onAssign(ItemStack item) throws InvalidItemException { if ( !item.getType().equals(Material.POTION) ) throw new InvalidItemException(); PotionMeta meta = (PotionMeta) item.getItemMeta(); for ( PotionEffect effect : effects ) meta.addCustomEffect(effect, false); //set the main effect meta.setMainEffect(effects.get(0).getType()); item.setItemMeta(meta); } @Override public void onFactorize(ItemStack item) throws AttributeValueNotFoundException { if ( !item.hasItemMeta() || !item.getType().equals(Material.POTION) ) throw new AttributeValueNotFoundException(); PotionMeta meta = (PotionMeta) item.getItemMeta(); if ( !meta.hasCustomEffects() ) throw new AttributeValueNotFoundException(); effects = meta.getCustomEffects(); } @Override public boolean equalsStrong(ItemAttr attr) { if ( ((Potion)attr).effects.size() != effects.size() ) return false; boolean equals = true; for ( PotionEffect effect : ((Potion)attr).effects ) equals = equals ? effects.contains(effect) : equals; return equals; } @Override public boolean equalsWeak(ItemAttr attr) { return equalsStrong(attr); } }
false
false
null
null
diff --git a/src/main/com/griefcraft/lwc/LWC.java b/src/main/com/griefcraft/lwc/LWC.java index 0ea65bf4..3bc28dfc 100644 --- a/src/main/com/griefcraft/lwc/LWC.java +++ b/src/main/com/griefcraft/lwc/LWC.java @@ -1,1481 +1,1487 @@ package com.griefcraft.lwc; import com.firestar.mcbans.mcbans; import com.griefcraft.cache.CacheSet; import com.griefcraft.logging.Logger; import com.griefcraft.migration.ConfigPost300; import com.griefcraft.migration.MySQLPost200; import com.griefcraft.model.AccessRight; import com.griefcraft.model.Protection; import com.griefcraft.model.ProtectionTypes; import com.griefcraft.modules.admin.*; import com.griefcraft.modules.create.CreateModule; import com.griefcraft.modules.destroy.DestroyModule; import com.griefcraft.modules.flag.FlagModule; import com.griefcraft.modules.free.FreeModule; import com.griefcraft.modules.info.InfoModule; import com.griefcraft.modules.limits.LimitsModule; import com.griefcraft.modules.lists.ListsModule; import com.griefcraft.modules.menu.MenuModule; import com.griefcraft.modules.modes.DropTransferModule; import com.griefcraft.modules.modes.MagnetModule; import com.griefcraft.modules.modes.PersistModule; import com.griefcraft.modules.modify.ModifyModule; import com.griefcraft.modules.owners.OwnersModule; import com.griefcraft.modules.redstone.RedstoneModule; import com.griefcraft.modules.unlock.UnlockModule; import com.griefcraft.modules.worldguard.WorldGuardModule; import com.griefcraft.scripting.Module; import com.griefcraft.scripting.Module.Result; import com.griefcraft.scripting.ModuleLoader; import com.griefcraft.scripting.ModuleLoader.Event; import com.griefcraft.sql.Database; import com.griefcraft.sql.MemDB; import com.griefcraft.sql.PhysDB; import com.griefcraft.util.Colors; import com.griefcraft.util.Performance; import com.griefcraft.util.StringUtils; import com.griefcraft.util.config.Configuration; import com.nijiko.permissions.PermissionHandler; import com.nijikokun.bukkit.Permissions.Permissions; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.block.BlockState; import org.bukkit.block.ContainerBlock; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.Plugin; import java.security.MessageDigest; import java.util.*; public class LWC { /** * The current instance of LWC (( should only be one ! if 2 are someone made, the first takes precedence )) */ private static LWC instance; /** * If LWC is currently enabled */ public static boolean ENABLED = false; /** * Core LWC configuration */ private Configuration configuration; /** * The module loader */ private ModuleLoader moduleLoader; /** * Logging instance */ private Logger logger = Logger.getLogger("LWC"); /** * The set of caches */ private CacheSet caches; /** * Memory database instance */ private MemDB memoryDatabase; /** * Physical database instance */ private PhysDB physicalDatabase; /** * Plugin instance */ private LWCPlugin plugin; /** * Checks for updates that need to be pushed to the sql database */ private UpdateThread updateThread; /** * Permissions plugin */ private PermissionHandler permissions; public LWC(LWCPlugin plugin) { this.plugin = plugin; if (instance == null) { instance = this; } configuration = Configuration.load("core.yml"); caches = new CacheSet(); } /** * Get the currently loaded LWC instance * * @return */ public static LWC getInstance() { return instance; } /** * @return the module loader */ public ModuleLoader getModuleLoader() { return moduleLoader; } /** * @return the caches */ public CacheSet getCaches() { return caches; } /** * Remove all modes if the player is not in persistent mode * * @param player */ public void removeModes(Player player) { if (notInPersistentMode(player.getName())) { memoryDatabase.unregisterAllActions(player.getName()); } } /** * Deposit items into an inventory chest * Works with double chests. * * @param block * @param itemStack * @return remaining items (if any) */ public Map<Integer, ItemStack> depositItems(Block block, ItemStack itemStack) { BlockState blockState = null; if ((blockState = block.getState()) != null && (blockState instanceof ContainerBlock)) { Block doubleChestBlock = findAdjacentBlock(block, Material.CHEST); ContainerBlock containerBlock = (ContainerBlock) blockState; Map<Integer, ItemStack> remaining = containerBlock.getInventory().addItem(itemStack); // we have remainders, deal with it if (remaining.size() > 0) { int key = remaining.keySet().iterator().next(); ItemStack remainingItemStack = remaining.get(key); // is it a double chest ????? if (doubleChestBlock != null) { ContainerBlock containerBlock2 = (ContainerBlock) doubleChestBlock.getState(); remaining = containerBlock2.getInventory().addItem(remainingItemStack); } // recheck remaining in the event of double chest being used if (remaining.size() > 0) { return remaining; } } } return new HashMap<Integer, ItemStack>(); } /** * Check if a player has the ability to access a protection * * @param player * @param block * @return */ public boolean canAccessProtection(Player player, Block block) { Protection protection = findProtection(block); if (protection != null) { return canAccessProtection(player, protection); } return false; } /** * Check if a player has the ability to access a protection * * @param player * @param x * @param y * @param z * @return */ public boolean canAccessProtection(Player player, int x, int y, int z) { return canAccessProtection(player, physicalDatabase.loadProtection(player.getWorld().getName(), x, y, z)); } /** * Check if a player has the ability to access a protection * * @param player * @param protection * @return */ public boolean canAccessProtection(Player player, Protection protection) { if (protection == null || player == null) { return true; } // call the canAccessProtection hook Result canAccess = moduleLoader.dispatchEvent(Event.ACCESS_PROTECTION, player, protection); if (canAccess != Result.DEFAULT) { return canAccess == Result.ALLOW; } if (isAdmin(player)) { return true; } if (isMod(player)) { Player protectionOwner = plugin.getServer().getPlayer(protection.getOwner()); if (protectionOwner == null) { return true; } if (!isAdmin(protectionOwner)) { return true; } } String playerName = player.getName(); switch (protection.getType()) { case ProtectionTypes.PUBLIC: return true; case ProtectionTypes.PASSWORD: return memoryDatabase.hasAccess(player.getName(), protection); case ProtectionTypes.PRIVATE: if (playerName.equalsIgnoreCase(protection.getOwner())) { return true; } if (protection.getAccess(AccessRight.PLAYER, playerName) >= 0) { return true; } if (permissions != null) { // TODO: Replace with getGroupProperName sometime, but only supported by Permissions 3.00+ String groupName = permissions.getGroup(player.getWorld().getName(), playerName); if (protection.getAccess(AccessRight.GROUP, groupName) >= 0) { return true; } } return false; default: return false; } } /** * Check if a player has the ability to administrate a protection * * @param player * @param block * @return */ public boolean canAdminProtection(Player player, Block block) { Protection protection = findProtection(block); if (protection != null) { return canAdminProtection(player, protection); } return false; } /** * Check if a player has the ability to administrate a protection * * @param player * @param protection * @return */ public boolean canAdminProtection(Player player, Protection protection) { if (protection == null || player == null) { return true; } // call the canAccessProtection hook Result canAdmin = moduleLoader.dispatchEvent(Event.ADMIN_PROTECTION, player, protection); if (canAdmin != Result.DEFAULT) { return canAdmin == Result.ALLOW; } if (isAdmin(player)) { return true; } String playerName = player.getName(); switch (protection.getType()) { case ProtectionTypes.PUBLIC: return player.getName().equalsIgnoreCase(protection.getOwner()); case ProtectionTypes.PASSWORD: return player.getName().equalsIgnoreCase(protection.getOwner()) && memoryDatabase.hasAccess(player.getName(), protection); case ProtectionTypes.PRIVATE: if (playerName.equalsIgnoreCase(protection.getOwner())) { return true; } if (protection.getAccess(AccessRight.PLAYER, playerName) == 1) { return true; } if (permissions != null) { // TODO: Replace with getGroupProperName sometime, but only supported by Permissions 3.00+ String groupName = permissions.getGroup(player.getWorld().getName(), playerName); if (protection.getAccess(AccessRight.GROUP, groupName) == 1) { return true; } } return false; default: return false; } } /** * Free some memory (LWC was disabled) */ public void destruct() { log("Freeing " + Database.DefaultType); if (physicalDatabase != null) { physicalDatabase.dispose(); } if (memoryDatabase != null) { memoryDatabase.dispose(); } if (updateThread != null) { updateThread.stop(); updateThread = null; } physicalDatabase = null; memoryDatabase = null; } /** * Encrypt a string using SHA1 * * @param plaintext * @return */ public String encrypt(String plaintext) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); md.update(plaintext.getBytes("UTF-8")); final byte[] raw = md.digest(); return byteArray2Hex(raw); } catch (final Exception e) { } return ""; } /** * Enforce access to a protection block * * @param player * @param block * @return true if the player was granted access */ public boolean enforceAccess(Player player, Block block) { if (block == null) { return true; } Protection protection = findProtection(block); boolean hasAccess = canAccessProtection(player, protection); // boolean canAdmin = canAdminProtection(player, protection); if (protection == null) { return true; } // support for old protection dbs that do not contain the block id if (protection.getBlockId() == 0) { protection.setBlockId(block.getTypeId()); protection.save(); } // multi-world, update old protections if (protection.getWorld() == null || protection.getWorld().isEmpty()) { protection.setWorld(block.getWorld().getName()); protection.save(); } if (configuration.getBoolean("core.showNotices", true)) { boolean isOwner = protection.isOwner(player); boolean showMyNotices = configuration.getBoolean("core.showMyNotices", true); if (isAdmin(player) || isMod(player) || (isOwner && showMyNotices)) { String owner = protection.getOwner(); // replace your username with "you" if you own the protection if (owner.equals(player.getName())) { owner = "you"; } sendLocale(player, "protection.general.notice.protected", "type", getLocale(protection.typeToString().toLowerCase()), "block", materialToString(block), "owner", owner); } } switch (protection.getType()) { case ProtectionTypes.PASSWORD: if (!hasAccess) { getMemoryDatabase().unregisterUnlock(player.getName()); getMemoryDatabase().registerUnlock(player.getName(), protection.getId()); sendLocale(player, "protection.general.locked.password", "block", materialToString(block)); } break; case ProtectionTypes.PRIVATE: if (!hasAccess) { sendLocale(player, "protection.general.locked.private", "block", materialToString(block)); } break; case ProtectionTypes.TRAP_KICK: if (!hasAccess) { player.kickPlayer(protection.getData()); log(player.getName() + " triggered the kick trap: " + protection.toString()); } break; case ProtectionTypes.TRAP_BAN: if (!hasAccess) { Plugin mcbansPlugin; /* * See if we have mcbans */ if ((mcbansPlugin = plugin.getServer().getPluginManager().getPlugin("MCBans")) != null) { mcbans mcbans = (mcbans) mcbansPlugin; /* * good good, ban them */ mcbans.mcb_handler.ban(player.getName(), "LWC", protection.getData(), ""); } log(player.getName() + " triggered the ban trap: " + protection.toString()); } break; } return hasAccess; } /** * Find a block that is adjacent to another block given a Material * * @param block * @param material * @param ignore * @return */ public Block findAdjacentBlock(Block block, Material material, Block... ignore) { BlockFace[] faces = new BlockFace[]{BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST}; List<Block> ignoreList = Arrays.asList(ignore); for (BlockFace face : faces) { Block adjacentBlock = block.getFace(face); if (adjacentBlock.getType() == material && !ignoreList.contains(adjacentBlock)) { return adjacentBlock; } } return null; } /** * Look for a double chest adjacent to a block * * @param block * @return */ public Block findAdjacentDoubleChest(Block block) { Block adjacentBlock = null; Block lastBlock = null; List<Block> attempts = new ArrayList<Block>(5); attempts.add(block); int found = 0; for (int attempt = 0; attempt < 4; attempt++) { Block[] attemptsArray = attempts.toArray(new Block[attempts.size()]); if ((adjacentBlock = findAdjacentBlock(block, Material.CHEST, attemptsArray)) != null) { if (findAdjacentBlock(adjacentBlock, Material.CHEST, block) != null) { return adjacentBlock; } found++; lastBlock = adjacentBlock; attempts.add(adjacentBlock); } } if (found > 1) { return lastBlock; } return null; } /** * Find a protection linked to the block * * @param block * @return */ public Protection findProtection(Block block) { return findProtection(block.getWorld(), block.getX(), block.getY(), block.getZ()); } /** * Find a protection linked to the block at [x, y, z] * * @param x * @param y * @param z * @return */ public Protection findProtection(World world, int x, int y, int z) { if (world == null) { return null; } Block block = world.getBlockAt(x, y, z); if (block == null) { return null; } // get the possible protections for the selected block List<Block> protections = getProtectionSet(world, x, y, z); // loop through and check for protected blocks for (Block protectableBlock : protections) { Protection protection = physicalDatabase.loadProtection(world.getName(), protectableBlock.getX(), protectableBlock.getY(), protectableBlock.getZ()); if (protection != null) { return protection; } } return null; } /** * Get the locale value for a given key * * @param key * @param args * @return */ public String getLocale(String key, Object... args) { key = key.replaceAll(" ", "_"); if (!plugin.getLocale().containsKey(key)) { return "UNKNOWN_LOCALE_" + key; } Map<String, Object> bind = parseBinds(args); String value = plugin.getLocale().getString(key); // apply colors for (String colorKey : Colors.localeColors.keySet()) { String color = Colors.localeColors.get(colorKey); if (value.contains(colorKey)) { value = value.replaceAll(colorKey, color); } } // apply binds for (String bindKey : bind.keySet()) { Object object = bind.get(bindKey); value = value.replaceAll("%" + bindKey + "%", object.toString()); } return value; } /** * @return memory database object */ public MemDB getMemoryDatabase() { return memoryDatabase; } /** * @return the permissions */ public PermissionHandler getPermissions() { return permissions; } /** * @return physical database object */ public PhysDB getPhysicalDatabase() { return physicalDatabase; } /** * @return the plugin class */ public LWCPlugin getPlugin() { return plugin; } /** * Useful for getting double chests * * @param x the x coordinate * @param y the y coordinate * @param z the z coordinate * @return the Chest[] array of chests */ public List<Block> getProtectionSet(World world, int x, int y, int z) { List<Block> entities = new ArrayList<Block>(2); Block baseBlock = world.getBlockAt(x, y, z); /* * First check the block they clicked */ entities = _validateBlock(entities, baseBlock, true); int dev = -1; boolean isXDir = true; while (true) { Block block = world.getBlockAt(x + (isXDir ? dev : 0), y, z + (isXDir ? 0 : dev)); entities = _validateBlock(entities, block); if (dev == 1) { if (isXDir) { isXDir = false; dev = -1; continue; } else { break; } } dev = 1; } return entities; } /** * @return the update thread */ public UpdateThread getUpdateThread() { return updateThread; } /** * @return the plugin version */ public double getVersion() { return Double.parseDouble(plugin.getDescription().getVersion()); } /** * Check if a player is an LWC admin -- Console defaults to *YES* * * @param sender * @return */ public boolean isAdmin(CommandSender sender) { if (sender instanceof Player) { return isAdmin((Player) sender); } return true; } /** * @return the configuration object */ public Configuration getConfiguration() { return configuration; } /** * Check if a player has either access to lwc.admin or the specified node * * @param sender * @param node * @return */ public boolean hasAdminPermission(CommandSender sender, String node) { return hasPermission(sender, node, "lwc.admin"); } /** * Check if a player has either access to lwc.protect or the specified node * * @param sender * @param node * @return */ public boolean hasPlayerPermission(CommandSender sender, String node) { return hasPermission(sender, node, "lwc.protect"); } /** * Check a player for a node, using a fallback as a default (e.g lwc.protect) * * @param sender * @param node * @param fallback * @return */ public boolean hasPermission(CommandSender sender, String node, String... fallback) { if (!(sender instanceof Player)) { return true; } Player player = (Player) sender; boolean hasNode = hasPermission(player, node); if (!hasNode) { for (String temp : fallback) { if (hasPermission(player, temp)) { return true; } } } return hasNode; } /** * Check if a player has a permissions node * * @param player * @param node * @return */ public boolean hasPermission(Player player, String node) { if (permissions != null) { return permissions.permission(player, node); } return true; } /** * Check if a player can do admin functions on LWC * * @param player the player to check * @return true if the player is an LWC admin */ public boolean isAdmin(Player player) { if (player.isOp()) { if (configuration.getBoolean("core.opIsLWCAdmin", true)) { return true; } } - return hasPermission(player, "lwc.admin"); + if(permissions != null) { + if (permissions.has(player, "lwc.admin")) { + return true; + } + } + + return false; } /** * Check if a player can do mod functions on LWC * * @param player the player to check * @return true if the player is an LWC mod */ public boolean isMod(Player player) { if (permissions != null) { if (permissions.has(player, "lwc.mod")) { return true; } } return false; } /** * Check if a mode is enabled * * @param mode * @return */ public boolean isModeEnabled(String mode) { return configuration.getBoolean("modes." + mode + ".enabled", true); } /** * Check if a mode is whitelisted for a player * * @param mode * @return */ public boolean isModeWhitelisted(Player player, String mode) { if (permissions == null) { return false; } return permissions.permission(player, "lwc.mode." + mode); } /** * Check a block to see if it is protectable * * @param block * @return */ public boolean isProtectable(Block block) { return isProtectable(block.getType()); } public boolean isProtectable(Material material) { return Boolean.parseBoolean(resolveProtectionConfiguration(material, "enabled")); } /** * Load sqlite (done only when LWC is loaded so memory isn't used unnecessarily) */ public void load() { configuration = Configuration.load("core.yml"); moduleLoader = new ModuleLoader(); registerCoreModules(); // check for upgrade before everything else ConfigPost300.checkConfigConversion(this); plugin.loadDatabase(); Performance.init(); if (LWCInfo.DEVELOPMENT) { log("Development mode is ON"); } physicalDatabase = new PhysDB(); memoryDatabase = new MemDB(); updateThread = new UpdateThread(this); Plugin permissionsPlugin = resolvePlugin("Permissions"); if (permissionsPlugin != null) { permissions = ((Permissions) permissionsPlugin).getHandler(); logger.log("Using Permissions API..."); } log("Loading " + Database.DefaultType); try { physicalDatabase.connect(); memoryDatabase.connect(); physicalDatabase.load(); memoryDatabase.load(); Logger.getLogger(Database.DefaultType.toString()).log("Using: " + StringUtils.capitalizeFirstLetter(physicalDatabase.getConnection().getMetaData().getDriverVersion())); } catch (Exception e) { e.printStackTrace(); } // check any major conversions MySQLPost200.checkDatabaseConversion(this); // precache lots of protections physicalDatabase.precache(); // tell all modules we're loaded moduleLoader.loadAll(); } /** * Register the core modules for LWC */ private void registerCoreModules() { // core registerModule(new LimitsModule()); registerModule(new CreateModule()); registerModule(new ModifyModule()); registerModule(new DestroyModule()); registerModule(new FreeModule()); registerModule(new InfoModule()); registerModule(new MenuModule()); registerModule(new UnlockModule()); registerModule(new OwnersModule()); // admin commands registerModule(new BaseAdminModule()); registerModule(new AdminCache()); registerModule(new AdminCleanup()); registerModule(new AdminClear()); registerModule(new AdminConfig()); registerModule(new AdminConvert()); registerModule(new AdminFind()); registerModule(new AdminFlush()); registerModule(new AdminForceOwner()); registerModule(new AdminLocale()); registerModule(new AdminPurge()); registerModule(new AdminReload()); registerModule(new AdminRemove()); registerModule(new AdminReport()); registerModule(new AdminUpdate()); registerModule(new AdminVersion()); registerModule(new AdminView()); registerModule(new AdminDebug()); // flags registerModule(new FlagModule()); registerModule(new RedstoneModule()); // modes registerModule(new PersistModule()); registerModule(new DropTransferModule()); registerModule(new MagnetModule()); // non-core modules but are included with LWC anyway registerModule(new ListsModule()); registerModule(new WorldGuardModule()); } /** * Register a module * * @param module */ private void registerModule(Module module) { moduleLoader.registerModule(plugin, module); } /** * Get a plugin by the name and if it is disabled, enable the plugin * * @param name * @return */ private Plugin resolvePlugin(String name) { Plugin temp = plugin.getServer().getPluginManager().getPlugin(name); if (temp == null) { return null; } if (!temp.isEnabled()) { plugin.getServer().getPluginManager().enablePlugin(temp); } return temp; } /** * Merge inventories into one * * @param blocks * @return */ public ItemStack[] mergeInventories(List<Block> blocks) { ItemStack[] stacks = new ItemStack[54]; int index = 0; try { for (Block block : blocks) { if (!(block.getState() instanceof ContainerBlock)) { continue; } ContainerBlock containerBlock = (ContainerBlock) block.getState(); Inventory inventory = containerBlock.getInventory(); /* * Add all the items from this inventory */ for (ItemStack stack : inventory.getContents()) { stacks[index] = stack; index++; } } } catch (Exception e) { return mergeInventories(blocks); } return stacks; } /** * Return if the player is in persistent mode * * @param player the player to check * @return true if the player is NOT in persistent mode */ public boolean notInPersistentMode(String player) { return !memoryDatabase.hasMode(player, "persist"); } /** * Send the full help to a player * * @param sender the player to send to */ public void sendFullHelp(CommandSender sender) { boolean isPlayer = (sender instanceof Player); String menuStyle = "advanced"; // default for console if (isPlayer) { menuStyle = physicalDatabase.getMenuStyle(((Player) sender).getName()).toLowerCase(); } if (menuStyle.equals("advanced")) { sendLocale(sender, "help.advanced"); } else { sendLocale(sender, "help.basic"); } if (isAdmin(sender)) { sender.sendMessage(""); sender.sendMessage(Colors.Red + "/lwc admin - Administration"); } } /** * Send a locale to a player or console * * @param sender * @param key * @param args */ public void sendLocale(CommandSender sender, String key, Object... args) { String message = getLocale(key, args); String menuStyle = null; // null unless required! if (message == null) { sender.sendMessage(Colors.Red + "LWC: " + Colors.White + "Undefined locale: \"" + Colors.Gray + key + Colors.White + "\""); return; } String[] aliasvars = new String[]{"cprivate", "cpublic", "cpassword", "cmodify", "cunlock", "cinfo", "cremove"}; // apply command name modification depending on menu style for (String alias : aliasvars) { String replace = "%" + alias + "%"; if (!message.contains(replace)) { continue; } if (menuStyle == null) { menuStyle = (sender instanceof Player) ? physicalDatabase.getMenuStyle(((Player) sender).getName()) : "advanced"; } String localeName = alias + "." + menuStyle; message = message.replace(replace, getLocale(localeName)); } // split the lines for (String line : message.split("\\n")) { if (line.isEmpty()) { line = " "; } sender.sendMessage(line); } } /** * Send the simple usage of a command * * @param player * @param command */ public void sendSimpleUsage(CommandSender player, String command) { // player.sendMessage(Colors.Red + "Usage:" + Colors.Gold + " " + // command); sendLocale(player, "help.simpleusage", "command", command); } /** * Ensure a chest/furnace is protectable where it's at * * @param entities * @param block * @return */ private List<Block> _validateBlock(List<Block> entities, Block block) { return _validateBlock(entities, block, false); } /** * Ensure a chest/furnace is protectable where it's at * * @param block * @param block * @param isBaseBlock * @return */ private List<Block> _validateBlock(List<Block> entities, Block block, boolean isBaseBlock) { if (block == null) { return entities; } if (entities.size() > 2) { return entities; } Material type = block.getType(); Block up = block.getFace(BlockFace.UP); if (entities.size() == 1) { Block other = entities.get(0); switch (other.getTypeId()) { /* * Furnace */ case 61: case 62: return entities; /* * Dispensers */ case 23: return entities; /* * Sign */ case 63: case 68: return entities; /* * Chest */ case 54: if (type != Material.CHEST) { return entities; } break; /* * Wooden door */ case 64: if (type != Material.WOODEN_DOOR) { return entities; } break; /* * Iron door */ case 71: if (type != Material.IRON_DOOR_BLOCK) { return entities; } break; } if (!entities.contains(block)) { entities.add(block); } } else if (isProtectable(block) && isBaseBlock && !isComplexBlock(block)) { entities.add(block); } else if (isBaseBlock && (up.getType() == Material.WOODEN_DOOR || up.getType() == Material.IRON_DOOR_BLOCK || type == Material.WOODEN_DOOR || type == Material.IRON_DOOR_BLOCK)) { /* * check if they're clicking the block under the door */ if (type != Material.WOODEN_DOOR && type != Material.IRON_DOOR_BLOCK) { entities.clear(); entities.add(block); // block under the door entities.add(block.getFace(BlockFace.UP)); // bottom half entities.add(block.getWorld().getBlockAt(block.getX(), block.getY() + 2, block.getZ())); // top // half } else { entities.clear(); if (up.getType() == Material.WOODEN_DOOR || up.getType() == Material.IRON_DOOR_BLOCK) { entities.add(block); // bottom half entities.add(up); // top half } else { entities.add(block.getFace(BlockFace.DOWN)); // bottom half entities.add(block); // top half } } } else if (isBaseBlock && (up.getType() == Material.SIGN_POST || up.getType() == Material.WALL_SIGN || type == Material.SIGN_POST || type == Material.WALL_SIGN)) { /* * If it's a wall sign, also protect the wall it's attached to! */ if (entities.size() == 0) { /* * Check if we're clicking on the sign itself, otherwise it's the block above it */ if (type == Material.SIGN_POST || type == Material.WALL_SIGN) { entities.add(block); } else { entities.add(up); } } } else if (isBaseBlock && (type == Material.FURNACE || type == Material.DISPENSER || type == Material.JUKEBOX)) { // protections that are just 1 block if (entities.size() == 0) { entities.add(block); } return entities; } else if (!isProtectable(block) && entities.size() == 0) { /* * Look for a ronery wall sign */ Block face = null; // this shortens it quite a bit, just put the possible faces into an // array BlockFace[] faces = new BlockFace[]{BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST}; /* * Match wall signs to the wall it's attached to */ for (BlockFace blockFace : faces) { if ((face = block.getFace(blockFace)) != null) { if (face.getType() == Material.WALL_SIGN) { byte direction = face.getData(); /* * Protect the wall the wall sign is attached to */ switch (direction) { case 0x02: // east if (blockFace == BlockFace.EAST) { entities.add(face); } break; case 0x03: // west if (blockFace == BlockFace.WEST) { entities.add(face); } break; case 0x04: // north if (blockFace == BlockFace.NORTH) { entities.add(face); } break; case 0x05: // south if (blockFace == BlockFace.SOUTH) { entities.add(face); } break; } } } } } return entities; } /** * Convert a byte array to hex * * @param hash the hash to convert * @return the converted hash */ private String byteArray2Hex(byte[] hash) { final Formatter formatter = new Formatter(); for (final byte b : hash) { formatter.format("%02x", b); } return formatter.toString(); } /** * Check if a block is more than just protectable blocks (i.e signs, doors) * * @param block * @return */ private boolean isComplexBlock(Block block) { switch (block.getTypeId()) { case 63: // sign post case 64: // wood door case 68: // wall sign case 71: // iron door return true; } return false; } /** * Log a string * * @param str */ private void log(String str) { logger.log(str); } /** * Convert an even-lengthed argument array to a map containing String keys i.e parseBinds("Test", null, "Test2", obj) = Map().put("test", null).put("test2", obj) * * @param args * @return */ private Map<String, Object> parseBinds(Object... args) { Map<String, Object> bind = new HashMap<String, Object>(); if (args == null || args.length < 2) { return bind; } int size = args.length; for (int index = 0; index < args.length; index += 2) { if ((index + 2) > size) { break; } String key = args[index].toString(); Object object = args[index + 1]; bind.put(key, object); } return bind; } /** * Get a string representation of a block's material * * @param block * @return */ public static String materialToString(Block block) { return materialToString(block.getType()); } /** * Get a string representation of a block type * * @param id * @return */ public static String materialToString(int id) { return materialToString(Material.getMaterial(id)); } /** * Get a string representation of a block material * * @param material * @return */ public static String materialToString(Material material) { if (material != null) { return StringUtils.capitalizeFirstLetter(material.toString().replaceAll("_", " ")); } return ""; } /** * Get the appropriate config value for the block (protections.block.node) * * @param material * @param node * @return */ public String resolveProtectionConfiguration(Material material, String node) { List<String> names = new ArrayList<String>(); String materialName = material.toString().toLowerCase(); // add the name & the block id names.add(materialName); names.add(material.getId() + ""); // check for the trimmed variant String trimmedName = materialName.replaceAll("block", ""); if (trimmedName.endsWith("_")) { trimmedName = trimmedName.substring(0, trimmedName.length() - 1); } if (!trimmedName.equals(materialName)) { names.add(trimmedName); } String value = configuration.getString("protections." + node); for (String name : names) { if (name.contains("sign")) { name = "sign"; } String temp = configuration.getString("protections.blocks." + name + "." + node); if (temp != null && !temp.isEmpty()) { value = temp; } } return value; } }
true
false
null
null
diff --git a/src/test/java/gr/dsigned/atom/parser/AtomParserTest.java b/src/test/java/gr/dsigned/atom/parser/AtomParserTest.java index cb1869c..38b3cef 100644 --- a/src/test/java/gr/dsigned/atom/parser/AtomParserTest.java +++ b/src/test/java/gr/dsigned/atom/parser/AtomParserTest.java @@ -1,32 +1,32 @@ package gr.dsigned.atom.parser; import gr.dsigned.atom.domain.Feed; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import junit.framework.TestCase; import org.xmlpull.v1.XmlPullParserException; public class AtomParserTest extends TestCase { public void testParse() throws XmlPullParserException, IOException { AtomParser parser = new AtomParser(); URL url = new URL("http://feeds.huffingtonpost.com/huffingtonpost/raw_feed"); Feed feed = parser.parse(url.openConnection().getInputStream()); assertNotNull(feed); assertTrue(feed.getEntries().size() > 0); } public void testParseFile() throws XmlPullParserException, IOException { AtomParser parser = new AtomParser(); - InputStream in = new FileInputStream(new File("/home/nk/workspace2/atom/src/test/java/gr/dsigned/atom/parser/AtomTestFeed.xml")); + InputStream in = this.getClass().getResource("AtomTestFeed.xml").openStream(); Feed feed = parser.parse(in); assertNotNull(feed); assertTrue(feed.getEntries().size() > 0); } }
true
false
null
null
diff --git a/src/main/java/tk/manf/serialisation/handler/flatfile/YAMLSerialisationHandler.java b/src/main/java/tk/manf/serialisation/handler/flatfile/YAMLSerialisationHandler.java index cc760b9..0ba7483 100644 --- a/src/main/java/tk/manf/serialisation/handler/flatfile/YAMLSerialisationHandler.java +++ b/src/main/java/tk/manf/serialisation/handler/flatfile/YAMLSerialisationHandler.java @@ -1,214 +1,224 @@ package tk.manf.serialisation.handler.flatfile; import java.io.File; import java.io.IOException; +import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import tk.manf.serialisation.SerialisationException; import tk.manf.serialisation.annotations.InitiationConstructor; import tk.manf.serialisation.annotations.Parameter; import tk.manf.serialisation.annotations.Property; import tk.manf.serialisation.annotations.Unit; import tk.manf.serialisation.handler.SerialisationHandler; /** * YAML Serialisation Handler for Bukkits FileConfiguration * * @author Björn 'manf' Heinrichs */ public class YAMLSerialisationHandler implements SerialisationHandler { /** * Configuration Cache */ private static HashMap<String, FileConfiguration> cache; /** * Inintialises a new YAMLSerialisationHandler with capacity * @param opacity the initial capacity. */ public YAMLSerialisationHandler(int capacity) { cache = new HashMap<String, FileConfiguration>(capacity); } /** * Saves given Unit to Memory * * @param unit Unit * @param folder DataFolder of Plugin * @param id id of Unit for non static Units * * @throws IOException */ public void save(Unit unit, File folder, String id) throws IOException { FileConfiguration config = loadConfig(unit, folder, id); File f = new File(folder, unit.name()); f.getParentFile().mkdirs(); if (!unit.isStatic()) { f = new File(f, id); } config.save(f); cache.remove(unit.isStatic() ? unit.name() : unit.name() + "-" + id); } /** * Saves current Value to Key in the Cache * * @param unit Unit * @param folder DataFolde of Plugin * @param id ID of Plugin * @param key Key * @param value Value to save */ public void save(Unit unit, File folder, String id, String key, Object value) { FileConfiguration config = loadConfig(unit, folder, id); config.set(key, value); cacheConfig(unit, id, config); } /** * Loads current Units from Memory * * @param c Class of Unit * @param unit Unit * @param dataFolder dataFolder of Plugin * * @return all Units * * @throws SerialisationException if no Object was initiated, caused without an InitiationConstructor or if an InstantiationException is thrown. * @throws InvocationTargetException if an Error in the Construcor of the Object occured * @throws IllegalAccessException if any access is denied */ public <T> List<T> load(Class<T> c, Unit unit, File folder) throws SerialisationException, InvocationTargetException, IllegalAccessException { List<T> tmp; if (unit.isStatic()) { tmp = new ArrayList<T>(1); tmp.add(toObject(c, loadConfig(unit, folder, null))); } else { final File saves = new File(folder, unit.name()); saves.mkdirs(); tmp = new ArrayList<T>(saves.listFiles().length); for (File f : saves.listFiles()) { - tmp.add(toObject(c, loadConfig(folder, f.getName(), unit.name()))); + tmp.add(toObject(c, loadConfig(unit, folder, f.getName()))); } } return tmp; } /** * Loads the Config * <p/> * @param folder DataFolder of Plugin * @param id id of Unit * @param name Name of Unit * <p/> * @return Configuration */ private static FileConfiguration loadConfig(Unit unit, File folder, String id) { if (unit.isStatic()) { return loadConfig(folder, unit.name(), unit.name()); } return loadConfig(new File(folder, unit.name()), unit.name() + "-" + id, id); } /** * Loads given Config from Cache or File * <p/> * @param folder DataFolder of Plugin * @param id id of Unit * @param name Name of Unit * <p/> * @return Configuration * * @throws IllegalArgumentException if no Configuration could be loaded */ private static FileConfiguration loadConfig(File folder, String id, String name) { if (cache.containsKey(id)) { return cache.get(id); } return YamlConfiguration.loadConfiguration(new File(folder, name)); } /** * Saves Configurations in Cache * <p/> * @param Unit unit * @param id id of Unit * @param config Configuration that saved current Values of Object */ private static void cacheConfig(Unit unit, String id, FileConfiguration config) { if (unit.isStatic()) { cacheConfig(unit.name(), config); } else { cacheConfig(unit.name() + "-" + id, config); } } /** * Saves Config in Cache * <p/> * @param id id of Unit * @param config Configuration that saved current Values of Object */ private static void cacheConfig(String id, FileConfiguration config) { if (cache.containsKey(id)) { return; } cache.put(id, config); } /** * Returns an Object of given Class based on Configuration * * @param c Class of the Object * @param config Configuration that saved all Values of Object * * @return Object of given Class * * @throws IllegalAccessException if any access is denied * @throws InvocationTargetException if an Error in the Construcor of the Object occured * @throws SerialisationException if no Object was initiated, caused without an InitiationConstructor or if an InstantiationException is thrown */ private static <T> T toObject(Class<T> c, FileConfiguration config) throws SerialisationException, InvocationTargetException, IllegalAccessException { T o = null; try { for (Constructor<?> constr : c.getConstructors()) { if (constr.getAnnotation(InitiationConstructor.class) == null) { continue; } final List<Object> params = new ArrayList<Object>(constr.getParameterTypes().length); + int i = 0; for (Class<?> type : constr.getParameterTypes()) { - Parameter param = type.getAnnotation(Parameter.class); + Annotation[] annotations = constr.getParameterAnnotations()[i]; + Parameter param = null; + for(Annotation a:annotations) { + if(a.annotationType() == Parameter.class) { + param = (Parameter) a; + break; + } + } if (param == null) { params.add(type.isPrimitive() ? type.newInstance() : null); continue; } params.add(type.cast(config.get(param.name()))); + i++; } o = c.cast(constr.newInstance(params.toArray(new Object[params.size()]))); } } catch (InstantiationException ex) { throw new SerialisationException(ex.getLocalizedMessage()); } catch (IllegalArgumentException ex) { //Should not be thrown } if (o == null) { throw new SerialisationException("No Object initiated"); } for (Field f : c.getDeclaredFields()) { if (f.isAccessible()) { Property prop = f.getAnnotation(Property.class); if (prop == null) { continue; } f.set(o, config.get(prop.name().length() == 0 ? f.getName() : prop.name())); } } return o; } } \ No newline at end of file
false
false
null
null
diff --git a/src/org/mozilla/javascript/ImporterTopLevel.java b/src/org/mozilla/javascript/ImporterTopLevel.java index 0301d34d..af173828 100644 --- a/src/org/mozilla/javascript/ImporterTopLevel.java +++ b/src/org/mozilla/javascript/ImporterTopLevel.java @@ -1,177 +1,188 @@ /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * The contents of this file are subject to the Netscape 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/NPL/ * * 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 Netscape are * Copyright (C) 1999 Netscape Communications Corporation. All * Rights Reserved. * * Contributor(s): * Norris Boyd * Matthias Radestock * * Alternatively, the contents of this file may be used under the * terms of the GNU Public License (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 NPL, indicate your decision by * deleting the provisions above and replace 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 NPL or the GPL. */ // API class package org.mozilla.javascript; /** * Class ImporterTopLevel * * This class defines a ScriptableObject that can be instantiated * as a top-level ("global") object to provide functionality similar * to Java's "import" statement. * <p> * This class can be used to create a top-level scope using the following code: * <pre> * Scriptable scope = new ImporterTopLevel(cx); * </pre> * Then JavaScript code will have access to the following methods: * <ul> * <li>importClass - will "import" a class by making its unqualified name * available as a property of the top-level scope * <li>importPackage - will "import" all the classes of the package by * searching for unqualified names as classes qualified * by the given package. * </ul> * The following code from the shell illustrates this use: * <pre> * js> importClass(java.io.File) * js> f = new File('help.txt') * help.txt * js> importPackage(java.util) * js> v = new Vector() * [] * * @author Norris Boyd */ public class ImporterTopLevel extends ScriptableObject { /** * @deprecated */ public ImporterTopLevel() { init(); } public ImporterTopLevel(Context cx) { cx.initStandardObjects(this); init(); } private void init() { String[] names = { "importClass", "importPackage" }; try { this.defineFunctionProperties(names, ImporterTopLevel.class, ScriptableObject.DONTENUM); } catch (PropertyException e) { throw new Error(); // should never happen } } public String getClassName() { return "global"; } + public boolean has(String name, Scriptable start) { + return super.has(name, start) + || getPackageProperty(name, start) != NOT_FOUND; + } + public Object get(String name, Scriptable start) { Object result = super.get(name, start); if (result != NOT_FOUND) return result; + result = getPackageProperty(name, start); + return result; + } + + private Object getPackageProperty(String name, Scriptable start) { + Object result= NOT_FOUND; if (name.equals("_packages_")) return result; Object plist = ScriptableObject.getProperty(start,"_packages_"); if (plist == NOT_FOUND) return result; Object[] elements; Context cx = Context.enter(); try { elements = cx.getElements((Scriptable)plist); } finally { Context.exit(); } for (int i=0; i < elements.length; i++) { NativeJavaPackage p = (NativeJavaPackage) elements[i]; Object v = p.getPkgProperty(name, start, false); if (v != null && !(v instanceof NativeJavaPackage)) { if (result == NOT_FOUND) { result = v; } else { throw Context.reportRuntimeError2( "msg.ambig.import", result.toString(), v.toString()); } } } return result; } public static void importClass(Context cx, Scriptable thisObj, Object[] args, Function funObj) { for (int i=0; i<args.length; i++) { Object cl = args[i]; if (!(cl instanceof NativeJavaClass)) { throw Context.reportRuntimeError1( "msg.not.class", Context.toString(cl)); } String s = ((NativeJavaClass) cl).getClassObject().getName(); String n = s.substring(s.lastIndexOf('.')+1); Object val = thisObj.get(n, thisObj); if (val != NOT_FOUND && val != cl) { throw Context.reportRuntimeError1("msg.prop.defined", n); } //thisObj.defineProperty(n, cl, DONTENUM); thisObj.put(n,thisObj,cl); } } public static void importPackage(Context cx, Scriptable thisObj, Object[] args, Function funObj) { Scriptable importedPackages; Object plist = thisObj.get("_packages_", thisObj); if (plist == NOT_FOUND) { importedPackages = cx.newArray(thisObj,0); thisObj.put("_packages_", thisObj, importedPackages); } else { importedPackages = (Scriptable)plist; } for (int i=0; i<args.length; i++) { Object pkg = args[i]; if (!(pkg instanceof NativeJavaPackage)) { throw Context.reportRuntimeError1( "msg.not.pkg", Context.toString(pkg)); } Object[] elements = cx.getElements(importedPackages); for (int j=0; j < elements.length; j++) { if (pkg == elements[j]) { pkg = null; break; } } if (pkg != null) importedPackages.put(elements.length,importedPackages,pkg); } } } diff --git a/src/org/mozilla/javascript/NativeJavaPackage.java b/src/org/mozilla/javascript/NativeJavaPackage.java index e5317116..210347f6 100644 --- a/src/org/mozilla/javascript/NativeJavaPackage.java +++ b/src/org/mozilla/javascript/NativeJavaPackage.java @@ -1,291 +1,295 @@ /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * The contents of this file are subject to the Netscape 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/NPL/ * * 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 Netscape are * Copyright (C) 1997-1999 Netscape Communications Corporation. All * Rights Reserved. * * Contributor(s): * Norris Boyd * Frank Mitchell * Mike Shaver * * Alternatively, the contents of this file may be used under the * terms of the GNU Public License (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 NPL, indicate your decision by * deleting the provisions above and replace 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 NPL or the GPL. */ package org.mozilla.javascript; import java.lang.reflect.*; /** * This class reflects Java packages into the JavaScript environment. We * lazily reflect classes and subpackages, and use a caching/sharing * system to ensure that members reflected into one JavaPackage appear * in all other references to the same package (as with Packages.java.lang * and java.lang). * * @author Mike Shaver * @see NativeJavaArray * @see NativeJavaObject * @see NativeJavaClass */ public class NativeJavaPackage extends ScriptableObject { // we know these are packages so we can skip the class check // note that this is ok even if the package isn't present. static final String[] commonPackages = { "java.lang", "java.lang.reflect", "java.io", "java.math", "java.util", "java.util.zip", "java.text", "java.text.resources", "java.applet", }; public static class TopLevelPackage extends NativeJavaPackage implements Function { public TopLevelPackage() { super(""); } public Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args) throws JavaScriptException { return construct(cx, scope, args); } public Scriptable construct(Context cx, Scriptable scope, Object[] args) throws JavaScriptException { ClassLoader loader = getClassLoaderFromArgs(args); if (loader == null) { Context.reportRuntimeError0("msg.not.classloader"); return null; } return new NativeJavaPackage("", loader); } private ClassLoader getClassLoaderFromArgs(Object[] args) { if (args.length < 1) { return null; } Object arg = args[0]; if (arg instanceof Wrapper) { arg = ((Wrapper)arg).unwrap(); } if (!(arg instanceof ClassLoader)) { return null; } return (ClassLoader) arg; } } public static Scriptable init(Scriptable scope) throws PropertyException { NativeJavaPackage packages = new NativeJavaPackage.TopLevelPackage(); packages.setPrototype(getObjectPrototype(scope)); packages.setParentScope(scope); // We want to get a real alias, and not a distinct JavaPackage // with the same packageName, so that we share classes and packages // that are underneath. NativeJavaPackage javaAlias = (NativeJavaPackage)packages.get("java", packages); // It's safe to downcast here since initStandardObjects takes // a ScriptableObject. ScriptableObject global = (ScriptableObject) scope; global.defineProperty("Packages", packages, ScriptableObject.DONTENUM); global.defineProperty("java", javaAlias, ScriptableObject.DONTENUM); for (int i = 0; i < commonPackages.length; i++) packages.forcePackage(commonPackages[i]); Method[] m = FunctionObject.findMethods(NativeJavaPackage.class, "jsFunction_getClass"); FunctionObject f = new FunctionObject("getClass", m[0], global); global.defineProperty("getClass", f, ScriptableObject.DONTENUM); // I think I'm supposed to return the prototype, but I don't have one. return packages; } // set up a name which is known to be a package so we don't // need to look for a class by that name void forcePackage(String name) { NativeJavaPackage pkg; int end = name.indexOf('.'); if (end == -1) end = name.length(); String id = name.substring(0, end); Object cached = super.get(id, this); if (cached != null && cached instanceof NativeJavaPackage) { pkg = (NativeJavaPackage) cached; } else { String newPackage = packageName.length() == 0 ? id : packageName + "." + id; pkg = new NativeJavaPackage(newPackage, classLoader); pkg.setParentScope(this); pkg.setPrototype(this.prototype); super.put(id, this, pkg); } if (end < name.length()) pkg.forcePackage(name.substring(end+1)); } public NativeJavaPackage(String packageName) { this.packageName = packageName; } public NativeJavaPackage(String packageName, ClassLoader classLoader) { this.packageName = packageName; this.classLoader = classLoader; } public String getClassName() { return "JavaPackage"; } - public boolean has(String id, int index, Scriptable start) { + public boolean has(String id, Scriptable start) { return true; } + public boolean has(int index, Scriptable start) { + return false; + } + public void put(String id, Scriptable start, Object value) { // Can't add properties to Java packages. Sorry. } public void put(int index, Scriptable start, Object value) { throw Context.reportRuntimeError0("msg.pkg.int"); } public Object get(String id, Scriptable start) { return getPkgProperty(id, start, true); } public Object get(int index, Scriptable start) { return NOT_FOUND; } synchronized Object getPkgProperty(String name, Scriptable start, boolean createPkg) { Object cached = super.get(name, start); if (cached != NOT_FOUND) return cached; String newPackage = packageName.length() == 0 ? name : packageName + '.' + name; Context cx = Context.getContext(); ClassShutter shutter = cx.getClassShutter(); Scriptable newValue = null; if (shutter == null || shutter.visibleToScripts(newPackage)) { Class cl = findClass(classLoader, newPackage); if (cl != null) { newValue = new NativeJavaClass(getTopLevelScope(this), cl); newValue.setParentScope(this); newValue.setPrototype(this.prototype); } } if (newValue == null && createPkg) { NativeJavaPackage pkg = new NativeJavaPackage(newPackage, classLoader); pkg.setParentScope(this); pkg.setPrototype(this.prototype); newValue = pkg; } if (newValue != null) { // Make it available for fast lookup and sharing of // lazily-reflected constructors and static members. super.put(name, start, newValue); } return newValue; } public Object getDefaultValue(Class ignored) { return toString(); } public String toString() { return "[JavaPackage " + packageName + "]"; } public static Scriptable jsFunction_getClass(Context cx, Scriptable thisObj, Object[] args, Function funObj) { if (args.length > 0 && args[0] instanceof Wrapper) { Scriptable result = getTopLevelScope(thisObj); Class cl = ((Wrapper) args[0]).unwrap().getClass(); // Evaluate the class name by getting successive properties of // the string to find the appropriate NativeJavaClass object String name = "Packages." + cl.getName(); int offset = 0; for (;;) { int index = name.indexOf('.', offset); String propName = index == -1 ? name.substring(offset) : name.substring(offset, index); Object prop = result.get(propName, result); if (!(prop instanceof Scriptable)) break; // fall through to error result = (Scriptable) prop; if (index == -1) return result; offset = index+1; } } throw Context.reportRuntimeError( Context.getMessage0("msg.not.java.obj")); } private static Class findClass(ClassLoader loader, String className) { Class cl = null; if (loader != null) { try { cl = loader.loadClass(className); } catch (ClassNotFoundException ex) { } catch (SecurityException ex) { } } else { try { cl = Class.forName(className); } catch (ClassNotFoundException ex) { } catch (SecurityException ex) { } } return cl; } private String packageName; private ClassLoader classLoader; }
false
false
null
null
diff --git a/src/ogo/spec/game/lobby/GameRun.java b/src/ogo/spec/game/lobby/GameRun.java index 1608ce0..0c26720 100644 --- a/src/ogo/spec/game/lobby/GameRun.java +++ b/src/ogo/spec/game/lobby/GameRun.java @@ -1,332 +1,332 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ogo.spec.game.lobby; import ogo.spec.game.multiplayer.GameProto.Token; import ogo.spec.game.multiplayer.client.TokenChangeListener; import ogo.spec.game.model.Game; import ogo.spec.game.model.Tile; import ogo.spec.game.model.Change; import ogo.spec.game.graphics.view.GUI; import java.util.PriorityQueue; import java.util.LinkedList; import java.util.List; /** * Main game class. */ public class GameRun implements TokenChangeListener { protected long lastMessage = -1; protected int counter = 0; protected int playerId; // the ID of the player behind this computer protected Game game; protected long lastTick = 0; protected long nextLastTick = 0; /** * Run the game. */ public GameRun(Game game, int playerId) { this.game = game; this.playerId = playerId; startGraphics(); } /** * Start the graphics. */ void startGraphics() { new GUI(game, game.getPlayer(playerId)); // TODO: replace null reference with player object } // other methods // network methods // These methods run in the network thread /** * Create a Token.Change from a Change object. * * @param change The change from the token * * @return The new change */ Token.Change createTokenChangeFromChange(Change change) { Token.Change.Builder newChange = Token.Change.newBuilder(); switch (change.type) { case MOVE_CREATURE: newChange.setType(Token.ChangeType.MOVE_CREATURE); newChange.setX(change.x); newChange.setY(change.y); break; case HEALTH: newChange.setType(Token.ChangeType.HEALTH); newChange.setNewValue(change.newValue); break; case ENERGY: newChange.setType(Token.ChangeType.ENERGY); newChange.setNewValue(change.newValue); break; case ATTACKING_CREATURE: newChange.setType(Token.ChangeType.ATTACKING_CREATURE); //newChange.newValue = game.getCreature(change.getOtherCreatureId()); break; } newChange.setTick(change.tick); // TODO: get the player from the game newChange.setPlayerId(change.playerId); newChange.setCreatureId(change.creatureId); return newChange.build(); } /** * Create a Change from a Token.Change object. * * @param change The change from the token * * @return The new change */ Change createChangeFromTokenChange(Token.Change change) { Change newChange = new Change(); switch (change.getType()) { case MOVE_CREATURE: newChange.type = Change.ChangeType.MOVE_CREATURE; newChange.x = change.getX(); newChange.y = change.getY(); break; case HEALTH: newChange.type = Change.ChangeType.HEALTH; newChange.newValue = change.getNewValue(); break; case ENERGY: newChange.type = Change.ChangeType.ENERGY; newChange.newValue = change.getNewValue(); break; case ATTACKING_CREATURE: newChange.type = Change.ChangeType.ATTACKING_CREATURE; break; } newChange.tick = change.getTick(); // TODO: get the player from the game newChange.player = game.getPlayer(change.getPlayerId()); newChange.playerId = change.getPlayerId(); newChange.creature = game.getCreature(change.getCreatureId()); newChange.creatureId = change.getCreatureId(); return newChange; } /** * Obtain the queue from the game state. * * @return Game state changes queue */ LinkedList<Change> getGameChanges() { LinkedList<Change> changes = new LinkedList<Change>(); Change change; while ((change = game.poll()) != null) { changes.add(change); } /* if (changes.size() > 0) { System.err.println("CHANGES YAY!!!!! " + changes.size()); } */ return changes; } /** * Obtain the queue from the token. * * @param token Token to obtain changes from * * @return Token changes queue */ LinkedList<Change> getTokenChanges(Token.Builder token) { LinkedList<Change> changes = new LinkedList<Change>(); List<Token.Change> tokenChanges = token.getMessageList(); for (Token.Change change : tokenChanges) { if (change.getTick() > lastTick) { changes.add(createChangeFromTokenChange(change)); } } if (changes.size() > 0) { System.err.println("RECEIVED " + changes.size() + " changes"); for (Change ch : changes) { System.err.print("- "); switch (ch.type) { case MOVE_CREATURE: - System.err.println("move (" + ch.x + ", " + ch.y + ") tick: " + ch.tick); + System.err.println("move (" + ch.x + ", " + ch.y + ") creature: " + ch.creatureId + " tick: " + ch.tick); break; case ENERGY: System.err.println("energy creature: " + ch.creatureId + " val: " + ch.newValue + " tick: " + ch.tick); break; default: System.err.println("other change (" + ch.type.name() + ") tick: " + ch.tick); break; } } } return changes; } /** * Check if two changes have a conflict. */ boolean hasConflict(Change a, Change b) { // check if the changes have a conflict return false; } /** * Roll back a change. */ void rollBack(Change a) { // undo the change } /** * Apply a change. */ void applyChange(Change a) { switch (a.type) { case MOVE_CREATURE: Tile t = game.getMap().getTile(a.y, a.x); a.creature.getPath().setNextTile(t); break; } } /** * Merge info into the token. * * This method will merge the two token chains. One from the current game * state, and one from the token sent by the previous host. The data from * the previous token should be preferred. * * @param token Token to be processed * * TODO: Implement merging */ public Token.Builder mergeInfo(Token.Builder token) { LinkedList<Change> gameChanges = getGameChanges(); LinkedList<Change> tokenChanges = getTokenChanges(token); // we will merge everything into this list PriorityQueue<Change> newChanges = new PriorityQueue<Change>(); // merge the two change lists // when we revert a change from game, also apply this to the game // state // when we add a change from token, also apply this to the game state Change gameChange; while ((gameChange = gameChanges.poll()) != null) { boolean accepted = true; for (Change tokenChange : tokenChanges) { if (hasConflict(gameChange, tokenChange)) { rollBack(gameChange); accepted = false; break; } } if (accepted) { newChanges.add(gameChange); } } // now, add the token changes while ((gameChange = tokenChanges.poll()) != null) { newChanges.add(gameChange); applyChange(gameChange); } // add stuff to the token Change ch; while ((ch = newChanges.poll()) != null) { token.addMessage(createTokenChangeFromChange(ch)); } return token; } /** * Copy the received token, and create a token builder from it. * * @return new token */ Token.Builder copyToken(Token token) { Token.Builder builder = Token.newBuilder(); builder.mergeFrom(token); return builder; } /** * Keep stats. */ void runStats() { counter++; long time = System.currentTimeMillis(); if(lastMessage == -1 || time - lastMessage > 1000){ long diff = time - lastMessage; System.out.println("TPS: " + counter + "/" + diff + " = " + 1000.0*counter/diff); lastMessage = time; counter = 0; } } /** * Called when the token has changed. * * Note that this will be called from the network layer. Which runs in a * different thread than the rest of this class. */ public Token tokenChanged(Token token) { runStats(); // first copy the token Token.Builder builder = copyToken(token); nextLastTick = game.getTick(); mergeInfo(builder); lastTick = nextLastTick; return builder.build(); } }
true
false
null
null
diff --git a/jung-graph-impl/src/main/java/edu/uci/ics/jung/graph/SetHypergraph.java b/jung-graph-impl/src/main/java/edu/uci/ics/jung/graph/SetHypergraph.java index 4bf39e5c..cd695d3b 100644 --- a/jung-graph-impl/src/main/java/edu/uci/ics/jung/graph/SetHypergraph.java +++ b/jung-graph-impl/src/main/java/edu/uci/ics/jung/graph/SetHypergraph.java @@ -1,282 +1,285 @@ /* * Created on Feb 4, 2007 * * Copyright (c) 2007, the JUNG Project and the Regents of the University * of California * All rights reserved. * * This software is open-source under the BSD license; see either * "license.txt" or * http://jung.sourceforge.net/license.txt for a description. */ package edu.uci.ics.jung.graph; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.apache.commons.collections15.Factory; import edu.uci.ics.jung.graph.util.EdgeType; /** * * * @author Joshua O'Madadhain */ public class SetHypergraph<V,H> implements Hypergraph<V,H>, MultiGraph<V,H>, Serializable { protected Map<V, Set<H>> vertices; // Map of vertices to incident hyperedge sets protected Map<H, Set<V>> edges; // Map of hyperedges to incident vertex sets /** * Returns a <code>Factory</code> which creates instances of this class. * @param <V> vertex type of the hypergraph to be created * @param <H> edge type of the hypergraph to be created * @return a <code>Factory</code> which creates instances of this class */ public static <V,H> Factory<Hypergraph<V,H>> getFactory() { return new Factory<Hypergraph<V,H>> () { public Hypergraph<V,H> create() { return new SetHypergraph<V,H>(); } }; } /** * Creates a <code>SetHypergraph</code> and initializes the internal data structures. */ public SetHypergraph() { vertices = new HashMap<V, Set<H>>(); edges = new HashMap<H, Set<V>>(); } /** * Adds <code>hyperedge</code> to this graph and connects them to the vertex collection <code>to_attach</code>. * Any vertices in <code>to_attach</code> that appear more than once will only appear once in the * incident vertex collection for <code>hyperedge</code>, that is, duplicates will be ignored. * * @see Hypergraph#addEdge(Object, Collection) */ public boolean addEdge(H hyperedge, Collection<? extends V> to_attach) { if (hyperedge == null) throw new IllegalArgumentException("input hyperedge may not be null"); if (to_attach == null) throw new IllegalArgumentException("endpoints may not be null"); if(to_attach.contains(null)) throw new IllegalArgumentException("cannot add an edge with a null endpoint"); Set<V> new_endpoints = new HashSet<V>(to_attach); if (edges.containsKey(hyperedge)) { Collection<V> attached = edges.get(hyperedge); if (!attached.equals(new_endpoints)) { throw new IllegalArgumentException("Edge " + hyperedge + " exists in this graph with endpoints " + attached); } else return false; } edges.put(hyperedge, new_endpoints); for (V v : to_attach) { // add v if it's not already in the graph addVertex(v); // associate v with hyperedge vertices.get(v).add(hyperedge); } return true; } /** * @see Hypergraph#addEdge(Object, Collection, EdgeType) */ public boolean addEdge(H hyperedge, Collection<? extends V> to_attach, EdgeType edge_type) { if (edge_type != EdgeType.UNDIRECTED) throw new IllegalArgumentException("Edge type for this " + "implementation must be EdgeType.UNDIRECTED, not " + edge_type); return addEdge(hyperedge, to_attach); } /** * @see Hypergraph#getEdgeType(Object) */ public EdgeType getEdgeType(H edge) { - return EdgeType.UNDIRECTED; + if (containsEdge(edge)) + return EdgeType.UNDIRECTED; + else + return null; } public boolean containsVertex(V vertex) { return vertices.keySet().contains(vertex); } public boolean containsEdge(H edge) { return edges.keySet().contains(edge); } public Collection<H> getEdges() { return edges.keySet(); } public Collection<V> getVertices() { return vertices.keySet(); } public int getEdgeCount() { return edges.size(); } public int getVertexCount() { return vertices.size(); } public Collection<V> getNeighbors(V vertex) { if (!containsVertex(vertex)) return null; Set<V> neighbors = new HashSet<V>(); for (H hyperedge : vertices.get(vertex)) { neighbors.addAll(edges.get(hyperedge)); } return neighbors; } public Collection<H> getIncidentEdges(V vertex) { return vertices.get(vertex); } public Collection<V> getIncidentVertices(H edge) { return edges.get(edge); } public H findEdge(V v1, V v2) { if (!containsVertex(v1) || !containsVertex(v2)) return null; for (H h : getIncidentEdges(v1)) { if (areIncident(v2, h)) return h; } return null; } public Collection<H> findEdgeSet(V v1, V v2) { if (!containsVertex(v1) || !containsVertex(v2)) return null; Collection<H> edges = new ArrayList<H>(); for (H h : getIncidentEdges(v1)) { if (areIncident(v2, h)) edges.add(h); } return Collections.unmodifiableCollection(edges); } public boolean addVertex(V vertex) { if(vertex == null) throw new IllegalArgumentException("cannot add a null vertex"); if (containsVertex(vertex)) return false; vertices.put(vertex, new HashSet<H>()); return true; } public boolean removeVertex(V vertex) { if (!containsVertex(vertex)) return false; for (H hyperedge : vertices.get(vertex)) { edges.get(hyperedge).remove(vertex); } vertices.remove(vertex); return true; } public boolean removeEdge(H hyperedge) { if (!containsEdge(hyperedge)) return false; for (V vertex : edges.get(hyperedge)) { vertices.get(vertex).remove(hyperedge); } edges.remove(hyperedge); return true; } public boolean areNeighbors(V v1, V v2) { if (!containsVertex(v1) || !containsVertex(v2)) return false; if (vertices.get(v2).isEmpty()) return false; for (H hyperedge : vertices.get(v1)) { if (edges.get(hyperedge).contains(v2)) return true; } return false; } public boolean areIncident(V vertex, H edge) { if (!containsVertex(vertex) || !containsEdge(edge)) return false; return vertices.get(vertex).contains(edge); } public int degree(V vertex) { if (!containsVertex(vertex)) return 0; return vertices.get(vertex).size(); } public int getNeighborCount(V vertex) { if (!containsVertex(vertex)) return 0; return getNeighbors(vertex).size(); } public int getIncidentCount(H edge) { if (!containsEdge(edge)) return 0; return edges.get(edge).size(); } }
true
false
null
null
diff --git a/src/main/java/com/laytonsmith/core/functions/WorldEdit.java b/src/main/java/com/laytonsmith/core/functions/WorldEdit.java index 886b96eb..135bea3e 100644 --- a/src/main/java/com/laytonsmith/core/functions/WorldEdit.java +++ b/src/main/java/com/laytonsmith/core/functions/WorldEdit.java @@ -1,1803 +1,1803 @@ package com.laytonsmith.core.functions; import com.laytonsmith.abstraction.MCCommandSender; import com.laytonsmith.abstraction.MCLocation; import com.laytonsmith.abstraction.MCPlayer; import com.laytonsmith.abstraction.MCWorld; import com.laytonsmith.abstraction.bukkit.BukkitMCCommandSender; import com.laytonsmith.abstraction.bukkit.BukkitMCLocation; import com.laytonsmith.abstraction.bukkit.BukkitMCPlayer; import com.laytonsmith.abstraction.bukkit.BukkitMCWorld; import com.laytonsmith.annotations.api; import com.laytonsmith.core.*; import com.laytonsmith.core.constructs.*; import com.laytonsmith.core.environments.CommandHelperEnvironment; import com.laytonsmith.core.environments.Environment; import com.laytonsmith.core.exceptions.CancelCommandException; import com.laytonsmith.core.exceptions.ConfigRuntimeException; import com.laytonsmith.core.functions.Exceptions.ExceptionType; import com.sk89q.worldedit.BlockVector; import com.sk89q.worldedit.BlockVector2D; import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.bukkit.BukkitUtil; import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.regions.CuboidRegionSelector; import com.sk89q.worldedit.regions.RegionSelector; import com.sk89q.worldguard.protection.ApplicableRegionSet; import com.sk89q.worldguard.protection.GlobalRegionManager; import com.sk89q.worldguard.protection.databases.RegionDBUtil; import com.sk89q.worldguard.protection.flags.DefaultFlag; import com.sk89q.worldguard.protection.flags.Flag; import com.sk89q.worldguard.protection.flags.InvalidFlagFormat; import com.sk89q.worldguard.protection.flags.RegionGroup; import com.sk89q.worldguard.protection.flags.RegionGroupFlag; import com.sk89q.worldguard.protection.managers.RegionManager; import com.sk89q.worldguard.protection.regions.GlobalProtectedRegion; import com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion; import com.sk89q.worldguard.protection.regions.ProtectedPolygonalRegion; import com.sk89q.worldguard.protection.regions.ProtectedRegion; import java.util.*; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.command.CommandSender; /** * * @author Layton */ public class WorldEdit { public static String docs() { return "Provides various methods for programmatically hooking into WorldEdit and WorldGuard"; } @api(environments=CommandHelperEnvironment.class) public static class sk_pos1 extends SKFunction { public String getName() { return "sk_pos1"; } public Integer[] numArgs() { return new Integer[]{0, 1, 2}; } public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.PlayerOfflineException, ExceptionType.CastException}; } public String docs() { return "mixed {[player], locationArray | [player]} Sets the player's point 1, or returns it if the array to set isn't specified. If" + " the location is returned, it is returned as a 4 index array:(x, y, z, world)"; } public Construct exec(Target t, Environment env, Construct... args) throws CancelCommandException, ConfigRuntimeException { MCPlayer m = null; MCLocation l = null; boolean setter = false; Static.checkPlugin("WorldEdit", t); if (env.getEnv(CommandHelperEnvironment.class).GetCommandSender() instanceof MCPlayer) { m = env.getEnv(CommandHelperEnvironment.class).GetPlayer(); } if (args.length == 2) { m = Static.GetPlayer(args[0].val(), t); l = ObjectGenerator.GetGenerator().location(args[1], m.getWorld(), t); setter = true; } else if (args.length == 1) { if (args[0] instanceof CArray) { l = ObjectGenerator.GetGenerator().location(args[0], ( m == null ? null : m.getWorld() ), t); setter = true; } else { m = Static.GetPlayer(args[0].val(), t); } } if (m == null) { throw new ConfigRuntimeException(this.getName() + " needs a player", ExceptionType.PlayerOfflineException, t); } RegionSelector sel = Static.getWorldEditPlugin(t).getSession(( (BukkitMCPlayer) m )._Player()).getRegionSelector(BukkitUtil.getLocalWorld(( (BukkitMCWorld) m.getWorld() ).__World())); if (!( sel instanceof CuboidRegionSelector )) { throw new ConfigRuntimeException("Only cuboid regions are supported with " + this.getName(), ExceptionType.PluginInternalException, t); } if (setter) { sel.selectPrimary(BukkitUtil.toVector(( (BukkitMCLocation) l )._Location())); return new CVoid(t); } else { Vector pt = ( (CuboidRegion) sel.getIncompleteRegion() ).getPos1(); if (pt == null) { throw new ConfigRuntimeException("Point in " + this.getName() + "undefined", t); } return new CArray(t, new CInt(pt.getBlockX(), t), new CInt(pt.getBlockY(), t), new CInt(pt.getBlockZ(), t), new CString(m.getWorld().getName(), t)); } } } @api(environments=CommandHelperEnvironment.class) public static class sk_pos2 extends SKFunction { public String getName() { return "sk_pos2"; } public Integer[] numArgs() { return new Integer[]{0, 1, 2}; } public String docs() { return "mixed {[player], array | [player]} Sets the player's point 2, or returns it if the array to set isn't specified"; } public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.PlayerOfflineException, ExceptionType.CastException}; } public Construct exec(Target t, Environment env, Construct... args) throws CancelCommandException, ConfigRuntimeException { MCPlayer m = null; MCLocation l = null; boolean setter = false; Static.checkPlugin("WorldEdit", t); if (env.getEnv(CommandHelperEnvironment.class).GetCommandSender() instanceof MCPlayer) { m = env.getEnv(CommandHelperEnvironment.class).GetPlayer(); } if (args.length == 2) { m = Static.GetPlayer(args[0].val(), t); l = ObjectGenerator.GetGenerator().location(args[1], m.getWorld(), t); setter = true; } else if (args.length == 1) { if (args[0] instanceof CArray) { l = ObjectGenerator.GetGenerator().location(args[0], ( m == null ? null : m.getWorld() ), t); setter = true; } else { m = Static.GetPlayer(args[0].val(), t); } } if (m == null) { throw new ConfigRuntimeException(this.getName() + " needs a player", ExceptionType.PlayerOfflineException, t); } RegionSelector sel = Static.getWorldEditPlugin(t).getSession(( (BukkitMCPlayer) m )._Player()).getRegionSelector(BukkitUtil.getLocalWorld(( (BukkitMCWorld) m.getWorld() ).__World())); if (!( sel instanceof CuboidRegionSelector )) { throw new ConfigRuntimeException("Only cuboid regions are supported with " + this.getName(), ExceptionType.PluginInternalException, t); } if (setter) { sel.selectSecondary(BukkitUtil.toVector(( (BukkitMCLocation) l )._Location())); return new CVoid(t); } else { Vector pt = ( (CuboidRegion) sel.getIncompleteRegion() ).getPos2(); if (pt == null) { throw new ConfigRuntimeException("Point in " + this.getName() + "undefined", t); } return new CArray(t, new CInt(pt.getBlockX(), t), new CInt(pt.getBlockY(), t), new CInt(pt.getBlockZ(), t), new CString(m.getWorld().getName(), t)); } } } // public static class sk_points extends SKFunction { // // public String getName() { // return "sk_points"; // } // // public Integer[] numArgs() { // return new Integer[]{0, 1, 2}; // } // // public String docs() { // return "mixed {[player], arrayOfArrays | [player]} Sets a series of points, or returns the poly selection for this player, if one is specified." // + " The array should be an array of arrays, and the arrays should be array(x, y, z)"; // } // // public ExceptionType[] thrown() { // return new ExceptionType[]{ExceptionType.PlayerOfflineException, ExceptionType.CastException}; // } // // public Construct exec(Target t, Environment env, Construct... args) throws CancelCommandException, ConfigRuntimeException { // Static.checkPlugin("WorldEdit", t); // return new CVoid(t); // } // } @api public static class sk_region_info extends SKFunction { public String getName() { return "sk_region_info"; } public Integer[] numArgs() { return new Integer[]{2}; } public String docs() { return "array {region, world} Given a region name, returns an array of information about that region." + " ---- The following information is returned:<ul>" + " <li>0 - An array of points that define this region</li>" + " <li>1 - An array of owners of this region</li>" + " <li>2 - An array of members of this region</li>" + " <li>3 - An array of arrays of this region's flags, where each array is: array(flag_name, value)</li>" + " <li>4 - This region's priority</li>" + " <li>5 - The volume of this region (in meters cubed)</li>" + "</ul>" + "If the region cannot be found, a PluginInternalException is thrown."; } public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.PluginInternalException}; } public Construct exec(Target t, Environment env, Construct... args) throws CancelCommandException, ConfigRuntimeException { try { String regionName = args[0].val(); String worldName = args[1].val(); //Fill these data structures in with the information we need List<Location> points = new ArrayList<Location>(); List<String> ownersPlayers = new ArrayList<String>(); List<String> ownersGroups = new ArrayList<String>(); List<String> membersPlayers = new ArrayList<String>(); List<String> membersGroups = new ArrayList<String>(); Map<String, String> flags = new HashMap<String, String>(); int priority = -1; float volume = -1; World world = Bukkit.getServer().getWorld(worldName); if (world == null) { throw new ConfigRuntimeException("Unknown world specified", ExceptionType.PluginInternalException, t); } RegionManager mgr = Static.getWorldGuardPlugin(t).getGlobalRegionManager().get(world); ProtectedRegion region = mgr.getRegion(regionName); if (region == null) { throw new ConfigRuntimeException("Region could not be found!", ExceptionType.PluginInternalException, t); } ownersPlayers.addAll(region.getOwners().getPlayers()); ownersGroups.addAll(region.getOwners().getGroups()); membersPlayers.addAll(region.getMembers().getPlayers()); membersGroups.addAll(region.getMembers().getGroups()); for (Map.Entry<Flag<?>, Object> ent : region.getFlags().entrySet()) { flags.put(ent.getKey().getName(), String.valueOf(ent.getValue())); } priority = region.getPriority(); volume = region.volume(); boolean first = true; if (region instanceof ProtectedPolygonalRegion) { for (BlockVector2D pt : ( (ProtectedPolygonalRegion) region ).getPoints()) { points.add(new Location(world, pt.getX(), first ? region.getMaximumPoint().getY() : region.getMinimumPoint().getY(), pt.getZ())); first = false; } } else { points.add(com.sk89q.worldguard.bukkit.BukkitUtil.toLocation(world, region.getMaximumPoint())); points.add(com.sk89q.worldguard.bukkit.BukkitUtil.toLocation(world, region.getMinimumPoint())); } CArray ret = new CArray(t); CArray pointSet = new CArray(t); for (Location l : points) { CArray point = new CArray(t); point.push(new CInt(l.getBlockX(), t)); point.push(new CInt(l.getBlockY(), t)); point.push(new CInt(l.getBlockZ(), t)); point.push(new CString(l.getWorld().getName(), t)); pointSet.push(point); } CArray ownerSet = new CArray(t); for (String owner : ownersPlayers) { ownerSet.push(new CString(owner, t)); } for (String owner : ownersGroups) { ownerSet.push(new CString("*" + owner, t)); } CArray memberSet = new CArray(t); for (String member : membersPlayers) { memberSet.push(new CString(member, t)); } for (String member : membersGroups) { memberSet.push(new CString("*" + member, t)); } CArray flagSet = new CArray(t); for (Map.Entry<String, String> flag : flags.entrySet()) { CArray fl = new CArray(t, new CString(flag.getKey(), t), new CString(flag.getValue(), t)); flagSet.push(fl); } ret.push(pointSet); ret.push(ownerSet); ret.push(memberSet); ret.push(flagSet); ret.push(new CInt(priority, t)); ret.push(new CDouble(volume, t)); return ret; } catch (NoClassDefFoundError e) { throw new ConfigRuntimeException("It does not appear as though the WorldEdit or WorldGuard plugin is loaded properly. Execution of " + this.getName() + " cannot continue.", ExceptionType.InvalidPluginException, t, e); } } } @api public static class sk_region_overlaps extends SKFunction { public String getName() { return "sk_region_overlaps"; } public Integer[] numArgs() { return new Integer[]{Integer.MAX_VALUE}; } public String docs() { return "boolean {world, region1, array(region2, [regionN...])} Returns true or false whether or not the specified regions overlap."; } public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.PluginInternalException}; } public Construct exec(Target t, Environment env, Construct... args) throws CancelCommandException, ConfigRuntimeException { String region1 = args[1].val(); List<ProtectedRegion> checkRegions = new ArrayList<ProtectedRegion>(); Static.checkPlugin("WorldGuard", t); World world = Bukkit.getServer().getWorld(args[0].val()); if (world == null) { throw new ConfigRuntimeException("Unknown world specified", ExceptionType.PluginInternalException, t); } RegionManager mgr = Static.getWorldGuardPlugin(t).getGlobalRegionManager().get(world); if (args[2] instanceof CArray) { CArray arg = (CArray) args[2]; for (int i = 0; i < arg.size(); i++) { ProtectedRegion region = mgr.getRegion(arg.get(i, t).val()); if (region == null) { throw new ConfigRuntimeException("Region " + arg.get(i, t).val() + " could not be found!", ExceptionType.PluginInternalException, t); } checkRegions.add(region); } } else { ProtectedRegion region = mgr.getRegion(args[2].val()); if (region == null) { throw new ConfigRuntimeException("Region " + args[2] + " could not be found!", ExceptionType.PluginInternalException, t); } checkRegions.add(region); } ProtectedRegion region = mgr.getRegion(region1); if (region == null) { throw new ConfigRuntimeException("Region could not be found!", ExceptionType.PluginInternalException, t); } try { if (!region.getIntersectingRegions(checkRegions).isEmpty()) { return new CBoolean(true, t); } } catch (Exception e) { } return new CBoolean(false, t); } } @api public static class sk_region_intersect extends SKFunction { public String getName() { return "sk_region_intersect"; } public Integer[] numArgs() { return new Integer[]{2, 3}; } public String docs() { return "array {world, region1, [array(region2, [regionN...])]} Returns an array of regions names which intersect with defined region." + " You can pass an array of regions to verify or omit this parameter and all regions in selected world will be checked."; } public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.PluginInternalException}; } public Construct exec(Target t, Environment env, Construct... args) throws CancelCommandException, ConfigRuntimeException { String region1 = args[1].val(); List<ProtectedRegion> checkRegions = new ArrayList<ProtectedRegion>(); List<ProtectedRegion> getRegions = new ArrayList<ProtectedRegion>(); CArray listRegions = new CArray(t); Static.checkPlugin("WorldGuard", t); World world = Bukkit.getServer().getWorld(args[0].val()); if (world == null) { throw new ConfigRuntimeException("Unknown world specified", ExceptionType.PluginInternalException, t); } RegionManager mgr = Static.getWorldGuardPlugin(t).getGlobalRegionManager().get(world); if (args.length == 2) { checkRegions.addAll(mgr.getRegions().values()); } else { if (args[2] instanceof CArray) { CArray arg = (CArray) args[2]; for (int i = 0; i < arg.size(); i++) { ProtectedRegion region = mgr.getRegion(arg.get(i, t).val()); if (region == null) { throw new ConfigRuntimeException(String.format("Region %s could not be found!", arg.get(i, t).val()), ExceptionType.PluginInternalException, t); } checkRegions.add(region); } } else { ProtectedRegion region = mgr.getRegion(args[2].val()); if (region == null) { throw new ConfigRuntimeException(String.format("Region %s could not be found!", args[2]), ExceptionType.PluginInternalException, t); } checkRegions.add(region); } } ProtectedRegion region = mgr.getRegion(region1); if (region == null) { throw new ConfigRuntimeException(String.format("Region %s could not be found!", region1), ExceptionType.PluginInternalException, t); } try { getRegions = region.getIntersectingRegions(checkRegions); if (!getRegions.isEmpty()) { for (ProtectedRegion r : getRegions) { if (args.length != 2 || !r.getId().equals(region.getId())) { listRegions.push(new CString(r.getId(), t)); } } if (listRegions.isEmpty()) { return new CArray(t); } return listRegions; } } catch (Exception e) { } return new CArray(t); } } @api public static class sk_all_regions extends SKFunction { public String getName() { return "sk_all_regions"; } public Integer[] numArgs() { return new Integer[]{0, 1}; } public String docs() { return "array {[world]} Returns all the regions in all worlds, or just the one world, if specified."; } public ExceptionType[] thrown() { return new ExceptionType[]{}; } public Construct exec(Target t, Environment env, Construct... args) throws CancelCommandException, ConfigRuntimeException { Static.checkPlugin("WorldGuard", t); List<World> checkWorlds = null; CArray arr = new CArray(t); if (args.length == 1) { World world = Bukkit.getServer().getWorld(args[0].val()); if (world != null) { checkWorlds = Arrays.asList(world); } } if (checkWorlds == null) { checkWorlds = Bukkit.getServer().getWorlds(); } GlobalRegionManager mgr = Static.getWorldGuardPlugin(t).getGlobalRegionManager(); for (World world : checkWorlds) { for (String region : mgr.get(world).getRegions().keySet()) { arr.push(new CString(region, t)); } } return arr; } } @api(environments=CommandHelperEnvironment.class) public static class sk_current_regions extends SKFunction { public String getName() { return "sk_current_regions"; } public Integer[] numArgs() { return new Integer[]{0, 1}; } public String docs() { return "mixed {[player]} Returns the list regions that player is in. If no player specified, then the current player is used." + " If region is found, an array of region names are returned, else an empty is returned"; } public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.PlayerOfflineException, ExceptionType.PluginInternalException}; } public Construct exec(Target t, Environment env, Construct... args) throws CancelCommandException, ConfigRuntimeException { Static.checkPlugin("WorldGuard", t); World world; MCPlayer m = null; if (env.getEnv(CommandHelperEnvironment.class).GetCommandSender() instanceof MCPlayer) { m = env.getEnv(CommandHelperEnvironment.class).GetPlayer(); } if (args.length == 1) { m = Static.GetPlayer(args[0].val(), t); } if (m == null) { throw new ConfigRuntimeException(this.getName() + " needs a player", ExceptionType.PlayerOfflineException, t); } world = Bukkit.getServer().getWorld(m.getWorld().getName()); RegionManager mgr = Static.getWorldGuardPlugin(t).getGlobalRegionManager().get(world); Vector pt = new Vector(m.getLocation().getBlockX(), m.getLocation().getBlockY(), m.getLocation().getBlockZ()); ApplicableRegionSet set = mgr.getApplicableRegions(pt); CArray regions = new CArray(t); List<ProtectedRegion> sortedRegions = new ArrayList<ProtectedRegion>(); for (ProtectedRegion r : set) { boolean placed = false; for (int i = 0; i < sortedRegions.size(); i++) { if (sortedRegions.get(i).volume() < r.volume()) { sortedRegions.add(i, r); placed = true; break; } } if (!placed) { sortedRegions.add(r); } } for (ProtectedRegion region : sortedRegions) { regions.push(new CString(region.getId(), t)); } if (regions.size() > 0) { return regions; } return new CArray(t); } } @api(environments=CommandHelperEnvironment.class) public static class sk_regions_at extends SKFunction { public String getName() { return "sk_regions_at"; } public Integer[] numArgs() { return new Integer[]{1}; } public String docs() { return "mixed {Locationarray} Returns a list of regions at the specified location. " + "If regions are found, an array of region names are returned, otherwise, an empty array is returned."; } public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.CastException, ExceptionType.PluginInternalException, ExceptionType.InsufficientArgumentsException}; } public Construct exec(Target t, Environment env, Construct... args) throws CancelCommandException, ConfigRuntimeException { Static.checkPlugin("WorldGuard", t); World world; if (!( args[0] instanceof CArray )) { throw new ConfigRuntimeException(this.getName() + " needs a locationarray", ExceptionType.CastException, t); } MCWorld w = null; MCCommandSender c = env.getEnv(CommandHelperEnvironment.class).GetCommandSender(); - if (c != null && !( c instanceof MCPlayer)) { + if (c instanceof MCPlayer) { w = ((MCPlayer)c).getWorld(); } MCLocation loc = ObjectGenerator.GetGenerator().location(args[0], w, t); if (loc.getWorld() == null) { throw new ConfigRuntimeException(this.getName() + " needs a world", ExceptionType.InsufficientArgumentsException, t); } world = Bukkit.getServer().getWorld(loc.getWorld().getName()); RegionManager mgr = Static.getWorldGuardPlugin(t).getGlobalRegionManager().get(world); Vector pt = new Vector(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); ApplicableRegionSet set = mgr.getApplicableRegions(pt); CArray regions = new CArray(t); List<ProtectedRegion> sortedRegions = new ArrayList<ProtectedRegion>(); for (ProtectedRegion r : set) { boolean placed = false; for (int i = 0; i < sortedRegions.size(); i++) { if (sortedRegions.get(i).volume() < r.volume()) { sortedRegions.add(i, r); placed = true; break; } } if (!placed) { sortedRegions.add(r); } } for (ProtectedRegion region : sortedRegions) { regions.push(new CString(region.getId(), t)); } if (regions.size() > 0) { return regions; } return new CArray(t); } } @api public static class sk_region_volume extends SKFunction { public String getName() { return "sk_region_volume"; } public Integer[] numArgs() { return new Integer[]{2}; } public String docs() { return "int {region, world} Returns the volume of the given region in the given world."; } public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.PluginInternalException}; } public Construct exec(Target t, Environment env, Construct... args) throws CancelCommandException, ConfigRuntimeException { Static.checkPlugin("WorldGuard", t); World world; world = Bukkit.getServer().getWorld(args[1].val()); RegionManager mgr = Static.getWorldGuardPlugin(t).getGlobalRegionManager().get(world); ProtectedRegion region = mgr.getRegion(args[0].val()); if (region == null) { throw new ConfigRuntimeException(String.format("The region (%s) does not exist in world (%s).", args[0].val(), args[1].val()), ExceptionType.PluginInternalException, t); } return new CInt(region.volume(), t); } } @api public static class sk_region_create extends SKFunction { public String getName() { return "sk_region_create"; } public Integer[] numArgs() { return new Integer[]{2, 3}; } public String docs() { return "void {[world], name, array(locationArrayPos1, locationArrayPos2, [[locationArrayPosN]...])} Create region of the given name in the given world."; } public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.InvalidWorldException, ExceptionType.PluginInternalException}; } public Construct exec(Target t, Environment env, Construct... args) throws CancelCommandException, ConfigRuntimeException { Static.checkPlugin("WorldGuard", t); World world = null; String region; if (args.length == 2) { region = args[0].val(); MCPlayer m = null; if (env.getEnv(CommandHelperEnvironment.class).GetCommandSender() instanceof MCPlayer) { m = env.getEnv(CommandHelperEnvironment.class).GetPlayer(); } if (m != null) { world = Bukkit.getServer().getWorld(m.getWorld().getName()); } } else { region = args[1].val(); world = Bukkit.getServer().getWorld(args[0].val()); } if (world == null) { throw new ConfigRuntimeException("Unknown world specified", ExceptionType.InvalidWorldException, t); } RegionManager mgr = Static.getWorldGuardPlugin(t).getGlobalRegionManager().get(world); ProtectedRegion regionExists = mgr.getRegion(region); if (regionExists != null) { throw new ConfigRuntimeException(String.format("The region (%s) already exists in world (%s)," + " and cannot be created again.", region, world.getName()), ExceptionType.PluginInternalException, t); } if (!(args[args.length - 1] instanceof CArray)) { throw new ConfigRuntimeException("Pass an array of points for a new region", ExceptionType.PluginInternalException, t); } List<BlockVector> points = new ArrayList<BlockVector>(); List<BlockVector2D> points2D = new ArrayList<BlockVector2D>(); int x = 0; int y = 0; int z = 0; int minY = 0; int maxY = 0; ProtectedRegion newRegion = null; CArray arg = (CArray) args[args.length - 1]; for (int i = 0; i < arg.size(); i++) { CArray point = (CArray)arg.get(i, t); x = Static.getInt32(point.get(0), t); y = Static.getInt32(point.get(1), t); z = Static.getInt32(point.get(2), t); if (arg.size() == 2) { points.add(new BlockVector(x, y, z)); } else { points2D.add(new BlockVector2D(x, z)); if (i == 0) { minY = maxY = y; } else { if (y < minY) { minY = y; } else if (y > maxY) { maxY = y; } } } } if (arg.size() == 2) { newRegion = new ProtectedCuboidRegion(region, points.get(0), points.get(1)); } else { newRegion = new ProtectedPolygonalRegion(region, points2D, minY, maxY); } if (newRegion == null) { throw new ConfigRuntimeException("Error while creating protected region", ExceptionType.PluginInternalException, t); } mgr.addRegion(newRegion); try { mgr.save(); } catch (Exception e) { throw new ConfigRuntimeException("Error while creating protected region", ExceptionType.PluginInternalException, t, e); } return new CVoid(t); } @Override public CHVersion since() { return CHVersion.V3_3_1; } } @api public static class sk_region_update extends SKFunction { public String getName() { return "sk_region_update"; } public Integer[] numArgs() { return new Integer[]{2, 3}; } public String docs() { return "void {[world], name, array(locationArrayPos1, locationArrayPos2, [[locationArrayPosN]...])} Updates the location of a given region to the new location. Other properties of the region, like owners, members, priority, etc are unaffected."; } public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.InvalidWorldException, ExceptionType.PluginInternalException}; } public Construct exec(Target t, Environment env, Construct... args) throws CancelCommandException, ConfigRuntimeException { Static.checkPlugin("WorldGuard", t); World world = null; String region; if (args.length == 2) { region = args[0].val(); MCPlayer m = null; if (env.getEnv(CommandHelperEnvironment.class).GetCommandSender() instanceof MCPlayer) { m = env.getEnv(CommandHelperEnvironment.class).GetPlayer(); } if (m != null) { world = Bukkit.getServer().getWorld(m.getWorld().getName()); } } else { region = args[1].val(); world = Bukkit.getServer().getWorld(args[0].val()); } if (world == null) { throw new ConfigRuntimeException("Unknown world specified", ExceptionType.InvalidWorldException, t); } RegionManager mgr = Static.getWorldGuardPlugin(t).getGlobalRegionManager().get(world); ProtectedRegion oldRegion = mgr.getRegion(region); if (oldRegion == null) { throw new ConfigRuntimeException(String.format("The region (%s) does not exist in world (%s).", region, world.getName()), ExceptionType.PluginInternalException, t); } if (!(args[args.length - 1] instanceof CArray)) { throw new ConfigRuntimeException("Pass an array of points to define a new region", ExceptionType.PluginInternalException, t); } List<BlockVector> points = new ArrayList<BlockVector>(); List<BlockVector2D> points2D = new ArrayList<BlockVector2D>(); int x = 0; int y = 0; int z = 0; int minY = 0; int maxY = 0; ProtectedRegion newRegion = null; CArray arg = (CArray) args[args.length - 1]; for (int i = 0; i < arg.size(); i++) { CArray point = (CArray)arg.get(i, t); x = Static.getInt32(point.get(0), t); y = Static.getInt32(point.get(1), t); z = Static.getInt32(point.get(2), t); if (arg.size() == 2) { points.add(new BlockVector(x, y, z)); } else { points2D.add(new BlockVector2D(x, z)); if (i == 0) { minY = maxY = y; } else { if (y < minY) { minY = y; } else if (y > maxY) { maxY = y; } } } } if (arg.size() == 2) { newRegion = new ProtectedCuboidRegion(region, points.get(0), points.get(1)); } else { newRegion = new ProtectedPolygonalRegion(region, points2D, minY, maxY); } if (newRegion == null) { throw new ConfigRuntimeException("Error while redefining protected region", ExceptionType.PluginInternalException, t); } mgr.addRegion(newRegion); newRegion.setMembers(oldRegion.getMembers()); newRegion.setOwners(oldRegion.getOwners()); newRegion.setFlags(oldRegion.getFlags()); newRegion.setPriority(oldRegion.getPriority()); try { newRegion.setParent(oldRegion.getParent()); } catch (Exception ignore) { } try { mgr.save(); } catch (Exception e) { throw new ConfigRuntimeException("Error while redefining protected region", ExceptionType.PluginInternalException, t, e); } return new CVoid(t); } @Override public CHVersion since() { return CHVersion.V3_3_1; } } @api public static class sk_region_remove extends SKFunction { public String getName() { return "sk_region_remove"; } public Integer[] numArgs() { return new Integer[]{1, 2}; } public String docs() { return "void {[world], name} Remove existed region."; } public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.InvalidWorldException, ExceptionType.PluginInternalException}; } public Construct exec(Target t, Environment env, Construct... args) throws CancelCommandException, ConfigRuntimeException { Static.checkPlugin("WorldGuard", t); World world = null; String region; if (args.length == 1) { region = args[0].val(); MCPlayer m = null; if (env.getEnv(CommandHelperEnvironment.class).GetCommandSender() instanceof MCPlayer) { m = env.getEnv(CommandHelperEnvironment.class).GetPlayer(); } if (m != null) { world = Bukkit.getServer().getWorld(m.getWorld().getName()); } } else { region = args[1].val(); world = Bukkit.getServer().getWorld(args[0].val()); } if (world == null) { throw new ConfigRuntimeException("Unknown world specified", ExceptionType.InvalidWorldException, t); } RegionManager mgr = Static.getWorldGuardPlugin(t).getGlobalRegionManager().get(world); ProtectedRegion regionExists = mgr.getRegion(region); if (regionExists == null) { throw new ConfigRuntimeException(String.format("The region (%s) does not exist in world (%s).", region, world.getName()), ExceptionType.PluginInternalException, t); } mgr.removeRegion(region); try { mgr.save(); } catch (Exception e) { throw new ConfigRuntimeException("Error while removing protected region", ExceptionType.PluginInternalException, t, e); } return new CVoid(t); } @Override public CHVersion since() { return CHVersion.V3_3_1; } } @api public static class sk_region_exists extends SKFunction { public String getName() { return "sk_region_exists"; } public Integer[] numArgs() { return new Integer[]{1, 2}; } public String docs() { return "void {[world], name} Check if a given region exists."; } public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.InvalidWorldException}; } public Construct exec(Target t, Environment env, Construct... args) throws CancelCommandException, ConfigRuntimeException { Static.checkPlugin("WorldGuard", t); World world = null; String region; if (args.length == 1) { region = args[0].val(); MCPlayer m = null; if (env.getEnv(CommandHelperEnvironment.class).GetCommandSender() instanceof MCPlayer) { m = env.getEnv(CommandHelperEnvironment.class).GetPlayer(); } if (m != null) { world = Bukkit.getServer().getWorld(m.getWorld().getName()); } } else { region = args[1].val(); world = Bukkit.getServer().getWorld(args[0].val()); } if (world == null) { throw new ConfigRuntimeException("Unknown world specified", ExceptionType.InvalidWorldException, t); } RegionManager mgr = Static.getWorldGuardPlugin(t).getGlobalRegionManager().get(world); ProtectedRegion regionExists = mgr.getRegion(region); if (regionExists != null) { return new CBoolean(true, t); } return new CBoolean(false, t); } @Override public CHVersion since() { return CHVersion.V3_3_1; } } @api public static class sk_region_addowner extends SKFunction { public String getName() { return "sk_region_addowner"; } public Integer[] numArgs() { return new Integer[]{1, 2, 3}; } public String docs() { return "void {region, [world], [owner1] | region, [world], [array(owner1, ownerN, ...)]} Add owner(s) to given region."; } public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.InvalidWorldException, ExceptionType.PluginInternalException}; } public Construct exec(Target t, Environment env, Construct... args) throws CancelCommandException, ConfigRuntimeException { Static.checkPlugin("WorldGuard", t); World world = null; MCPlayer m = null; String[] owners = null; String region = args[0].val(); if (args.length == 1) { if (env.getEnv(CommandHelperEnvironment.class).GetCommandSender() instanceof MCPlayer) { m = env.getEnv(CommandHelperEnvironment.class).GetPlayer(); } if (m != null) { world = Bukkit.getServer().getWorld(m.getWorld().getName()); owners = new String[1]; owners[0] = m.getName(); } } else if (args.length == 2) { world = Bukkit.getServer().getWorld(args[0].val()); if (env.getEnv(CommandHelperEnvironment.class).GetCommandSender() instanceof MCPlayer) { m = env.getEnv(CommandHelperEnvironment.class).GetPlayer(); } if (m != null) { owners = new String[1]; owners[0] = m.getName(); } } else { world = Bukkit.getServer().getWorld(args[1].val()); if (args[2] instanceof CArray) { CArray arg = (CArray) args[2]; owners = new String[(int)arg.size()]; for (int i = 0; i < arg.size(); i++) { owners[i] = arg.get(i, t).val(); } } else { owners = new String[1]; owners[0] = args[2].val(); } } if (world == null) { throw new ConfigRuntimeException("Unknown world specified", ExceptionType.InvalidWorldException, t); } RegionManager mgr = Static.getWorldGuardPlugin(t).getGlobalRegionManager().get(world); ProtectedRegion regionExists = mgr.getRegion(region); if (regionExists == null) { throw new ConfigRuntimeException(String.format("The region (%s) does not exist in world (%s).", region, world.getName()), ExceptionType.PluginInternalException, t); } RegionDBUtil.addToDomain(regionExists.getOwners(), owners, 0); try { mgr.save(); } catch (Exception e) { throw new ConfigRuntimeException("Error while adding owner(s) to protected region", ExceptionType.PluginInternalException, t, e); } return new CVoid(t); } @Override public CHVersion since() { return CHVersion.V3_3_1; } } @api public static class sk_region_remowner extends SKFunction { public String getName() { return "sk_region_remowner"; } public Integer[] numArgs() { return new Integer[]{1, 2, 3}; } public String docs() { return "void {region, [world], [owner1] | region, [world], [array(owner1, ownerN, ...)]} Remove owner(s) from given region."; } public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.InvalidWorldException, ExceptionType.PluginInternalException}; } public Construct exec(Target t, Environment env, Construct... args) throws CancelCommandException, ConfigRuntimeException { Static.checkPlugin("WorldGuard", t); World world = null; MCPlayer m = null; String[] owners = null; String region = args[0].val(); if (args.length == 1) { if (env.getEnv(CommandHelperEnvironment.class).GetCommandSender() instanceof MCPlayer) { m = env.getEnv(CommandHelperEnvironment.class).GetPlayer(); } if (m != null) { world = Bukkit.getServer().getWorld(m.getWorld().getName()); owners = new String[1]; owners[0] = m.getName(); } } else if (args.length == 2) { world = Bukkit.getServer().getWorld(args[0].val()); if (env.getEnv(CommandHelperEnvironment.class).GetCommandSender() instanceof MCPlayer) { m = env.getEnv(CommandHelperEnvironment.class).GetPlayer(); } if (m != null) { owners = new String[1]; owners[0] = m.getName(); } } else { world = Bukkit.getServer().getWorld(args[1].val()); if (args[2] instanceof CArray) { CArray arg = (CArray) args[2]; owners = new String[(int)arg.size()]; for (int i = 0; i < arg.size(); i++) { owners[i] = arg.get(i, t).val(); } } else { owners = new String[1]; owners[0] = args[2].val(); } } if (world == null) { throw new ConfigRuntimeException("Unknown world specified", ExceptionType.InvalidWorldException, t); } RegionManager mgr = Static.getWorldGuardPlugin(t).getGlobalRegionManager().get(world); ProtectedRegion regionExists = mgr.getRegion(region); if (regionExists == null) { throw new ConfigRuntimeException(String.format("The region (%s) does not exist in world (%s).", region, world.getName()), ExceptionType.PluginInternalException, t); } RegionDBUtil.removeFromDomain(regionExists.getOwners(), owners, 0); try { mgr.save(); } catch (Exception e) { throw new ConfigRuntimeException("Error while deleting owner(s) from protected region", ExceptionType.PluginInternalException, t, e); } return new CVoid(t); } @Override public CHVersion since() { return CHVersion.V3_3_1; } } @api public static class sk_region_addmember extends SKFunction { public String getName() { return "sk_region_addmember"; } public Integer[] numArgs() { return new Integer[]{1, 2, 3}; } public String docs() { return "void {region, [world], [member1] | region, [world], [array(member1, memberN, ...)]} Add member(s) to given region."; } public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.InvalidWorldException, ExceptionType.PluginInternalException}; } public Construct exec(Target t, Environment env, Construct... args) throws CancelCommandException, ConfigRuntimeException { Static.checkPlugin("WorldGuard", t); World world = null; MCPlayer m = null; String[] members = null; String region = args[0].val(); if (args.length == 1) { if (env.getEnv(CommandHelperEnvironment.class).GetCommandSender() instanceof MCPlayer) { m = env.getEnv(CommandHelperEnvironment.class).GetPlayer(); } if (m != null) { world = Bukkit.getServer().getWorld(m.getWorld().getName()); members = new String[1]; members[0] = m.getName(); } } else if (args.length == 2) { world = Bukkit.getServer().getWorld(args[0].val()); if (env.getEnv(CommandHelperEnvironment.class).GetCommandSender() instanceof MCPlayer) { m = env.getEnv(CommandHelperEnvironment.class).GetPlayer(); } if (m != null) { members = new String[1]; members[0] = m.getName(); } } else { world = Bukkit.getServer().getWorld(args[1].val()); if (args[2] instanceof CArray) { CArray arg = (CArray) args[2]; for (int i = 0; i < arg.size(); i++) { members = new String[(int)arg.size()]; members[i] = arg.get(i, t).val(); } } else { members = new String[1]; members[0] = args[2].val(); } } if (world == null) { throw new ConfigRuntimeException("Unknown world specified", ExceptionType.InvalidWorldException, t); } RegionManager mgr = Static.getWorldGuardPlugin(t).getGlobalRegionManager().get(world); ProtectedRegion regionExists = mgr.getRegion(region); if (regionExists == null) { throw new ConfigRuntimeException(String.format("The region (%s) does not exist in world (%s).", region, world.getName()), ExceptionType.PluginInternalException, t); } RegionDBUtil.addToDomain(regionExists.getMembers(), members, 0); try { mgr.save(); } catch (Exception e) { throw new ConfigRuntimeException("Error while adding member(s) to protected region", ExceptionType.PluginInternalException, t, e); } return new CVoid(t); } @Override public CHVersion since() { return CHVersion.V3_3_1; } } @api public static class sk_region_remmember extends SKFunction { public String getName() { return "sk_region_remmember"; } public Integer[] numArgs() { return new Integer[]{1, 2, 3}; } public String docs() { return "void {region, [world], [member1] | region, [world], [array(member1, memberN, ...)]} Remove member(s) from given region."; } public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.InvalidWorldException, ExceptionType.PluginInternalException}; } public Construct exec(Target t, Environment env, Construct... args) throws CancelCommandException, ConfigRuntimeException { Static.checkPlugin("WorldGuard", t); World world = null; MCPlayer m = null; String[] members = null; String region = args[0].val(); if (args.length == 1) { if (env.getEnv(CommandHelperEnvironment.class).GetCommandSender() instanceof MCPlayer) { m = env.getEnv(CommandHelperEnvironment.class).GetPlayer(); } if (m != null) { world = Bukkit.getServer().getWorld(m.getWorld().getName()); members = new String[1]; members[0] = m.getName(); } } else if (args.length == 2) { world = Bukkit.getServer().getWorld(args[0].val()); if (env.getEnv(CommandHelperEnvironment.class).GetCommandSender() instanceof MCPlayer) { m = env.getEnv(CommandHelperEnvironment.class).GetPlayer(); } if (m != null) { members = new String[1]; members[0] = m.getName(); } } else { world = Bukkit.getServer().getWorld(args[1].val()); if (args[2] instanceof CArray) { CArray arg = (CArray) args[2]; members = new String[(int)arg.size()]; for (int i = 0; i < arg.size(); i++) { members[i] = arg.get(i, t).val(); } } else { members = new String[1]; members[0] = args[2].val(); } } if (world == null) { throw new ConfigRuntimeException("Unknown world specified", ExceptionType.InvalidWorldException, t); } RegionManager mgr = Static.getWorldGuardPlugin(t).getGlobalRegionManager().get(world); ProtectedRegion regionExists = mgr.getRegion(region); if (regionExists == null) { throw new ConfigRuntimeException(String.format("The region (%s) does not exist in world (%s).", region, world.getName()), ExceptionType.PluginInternalException, t); } RegionDBUtil.removeFromDomain(regionExists.getMembers(), members, 0); try { mgr.save(); } catch (Exception e) { throw new ConfigRuntimeException("Error while deleting members(s) from protected region", ExceptionType.PluginInternalException, t, e); } return new CVoid(t); } @Override public CHVersion since() { return CHVersion.V3_3_1; } } @api public static class sk_region_flag extends SKFunction { public String getName() { return "sk_region_flag"; } public Integer[] numArgs() { return new Integer[]{4, 5}; } public String docs() { return "void {world, region, flagName, flagValue, [group]} Add/change/remove flag for selected region. FlagName should be any" + " supported flag from [http://wiki.sk89q.com/wiki/WorldGuard/Regions/Flags this list]. For the flagValue, use types which" + " are supported by WorldGuard. Add group argument if you want to add WorldGuard group flag (read more about group" + " flag types [http://wiki.sk89q.com/wiki/WorldGuard/Regions/Flags#Group here]). Set flagValue as null (and don't set" + " group) to delete the flag from the region."; } public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.InvalidWorldException, ExceptionType.PluginInternalException}; } public Construct exec(Target t, Environment env, Construct... args) throws CancelCommandException, ConfigRuntimeException { Static.checkPlugin("WorldGuard", t); World world = Bukkit.getServer().getWorld(args[0].val()); if (world == null) { throw new ConfigRuntimeException("Unknown world specified", ExceptionType.InvalidWorldException, t); } String regionName = args[1].val(); String flagName = args[2].val(); String flagValue = null; RegionGroup groupValue = null; if (args.length >= 4 && !(args[3] instanceof CNull) && args[3].val() != "") { flagValue = args[3].val(); } RegionManager mgr = Static.getWorldGuardPlugin(t).getGlobalRegionManager().get(world); ProtectedRegion region = mgr.getRegion(regionName); if (region == null) { if ("__global__".equalsIgnoreCase(regionName)) { region = new GlobalProtectedRegion(regionName); mgr.addRegion(region); } else { throw new ConfigRuntimeException(String.format("The region (%s) does not exist in world (%s).", regionName, world.getName()), ExceptionType.PluginInternalException, t); } } Flag<?> foundFlag = null; for (Flag<?> flag : DefaultFlag.getFlags()) { if (flag.getName().replace("-", "").equalsIgnoreCase(flagName.replace("-", ""))) { foundFlag = flag; break; } } if (foundFlag == null) { throw new ConfigRuntimeException(String.format("Unknown flag specified: (%s).", flagName), ExceptionType.PluginInternalException, t); } if (args.length == 5) { String group = args[4].val(); RegionGroupFlag groupFlag = foundFlag.getRegionGroupFlag(); if (groupFlag == null) { throw new ConfigRuntimeException(String.format("Region flag (%s) does not have a group flag.", flagName), ExceptionType.PluginInternalException, t); } try { groupValue = groupFlag.parseInput(Static.getWorldGuardPlugin(t), new BukkitMCCommandSender(env.getEnv(CommandHelperEnvironment.class).GetCommandSender())._CommandSender(), group); } catch (InvalidFlagFormat e) { throw new ConfigRuntimeException(String.format("Unknown group (%s).", group), ExceptionType.PluginInternalException, t); } } if (flagValue != null) { try { setFlag(t, region, foundFlag, new BukkitMCCommandSender(env.getEnv(CommandHelperEnvironment.class).GetCommandSender())._CommandSender(), flagValue); } catch (Exception e) { throw new ConfigRuntimeException(String.format("Unknown flag value specified: (%s).", flagValue), ExceptionType.PluginInternalException, t); } } else if (args.length < 5) { region.setFlag(foundFlag, null); RegionGroupFlag groupFlag = foundFlag.getRegionGroupFlag(); if (groupFlag != null) { region.setFlag(groupFlag, null); } } if (groupValue != null) { RegionGroupFlag groupFlag = foundFlag.getRegionGroupFlag(); if (groupValue == groupFlag.getDefault()) { region.setFlag(groupFlag, null); } else { region.setFlag(groupFlag, groupValue); } } try { mgr.save(); } catch (Exception e) { throw new ConfigRuntimeException("Error while defining flags", ExceptionType.PluginInternalException, t, e); } return new CVoid(t); } private <V> void setFlag(Target t, ProtectedRegion region, Flag<V> flag, CommandSender sender, String value) throws InvalidFlagFormat { region.setFlag(flag, flag.parseInput(Static.getWorldGuardPlugin(t), sender, value)); } @Override public CHVersion since() { return CHVersion.V3_3_1; } } @api public static class sk_region_setpriority extends SKFunction { public String getName() { return "sk_region_setpriority"; } public Integer[] numArgs() { return new Integer[]{2, 3}; } public String docs() { return "void {[world], region, priority} Sets priority for a given region."; } public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.InvalidWorldException, ExceptionType.PluginInternalException}; } public Construct exec(Target t, Environment env, Construct... args) throws CancelCommandException, ConfigRuntimeException { Static.checkPlugin("WorldGuard", t); World world = null; String region; int priority = 0; if (args.length == 2) { region = args[0].val(); MCPlayer m = null; if (env.getEnv(CommandHelperEnvironment.class).GetCommandSender() instanceof MCPlayer) { m = env.getEnv(CommandHelperEnvironment.class).GetPlayer(); } if (m != null) { world = Bukkit.getServer().getWorld(m.getWorld().getName()); } priority = Static.getInt32(args[1], t); } else { region = args[1].val(); world = Bukkit.getServer().getWorld(args[0].val()); priority = Static.getInt32(args[2], t); } if (world == null) { throw new ConfigRuntimeException("Unknown world specified", ExceptionType.InvalidWorldException, t); } if ("__global__".equalsIgnoreCase(region)) { throw new ConfigRuntimeException(String.format("The region cannot be named __global__.", region), ExceptionType.PluginInternalException, t); } RegionManager mgr = Static.getWorldGuardPlugin(t).getGlobalRegionManager().get(world); ProtectedRegion regionExists = mgr.getRegion(region); if (regionExists == null) { throw new ConfigRuntimeException(String.format("The region (%s) does not exist in world (%s).", region, world.getName()), ExceptionType.PluginInternalException, t); } regionExists.setPriority(priority); try { mgr.save(); } catch (Exception e) { throw new ConfigRuntimeException("Error while setting priority for protected region", ExceptionType.PluginInternalException, t, e); } return new CVoid(t); } @Override public CHVersion since() { return CHVersion.V3_3_1; } } @api public static class sk_region_setparent extends SKFunction { public String getName() { return "sk_region_setparent"; } public Integer[] numArgs() { return new Integer[]{2, 3}; } public String docs() { return "void {world, region, [parentRegion]} Sets parent region for a given region."; } public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.InvalidWorldException, ExceptionType.PluginInternalException}; } public Construct exec(Target t, Environment env, Construct... args) throws CancelCommandException, ConfigRuntimeException { Static.checkPlugin("WorldGuard", t); String regionName; String parentName; World world = Bukkit.getServer().getWorld(args[0].val()); if (world == null) { throw new ConfigRuntimeException("Unknown world specified", ExceptionType.InvalidWorldException, t); } regionName = args[1].val(); if ("__global__".equalsIgnoreCase(regionName)) { throw new ConfigRuntimeException(String.format("You cannot set parents for a __global__ cuboid.", regionName), ExceptionType.PluginInternalException, t); } RegionManager mgr = Static.getWorldGuardPlugin(t).getGlobalRegionManager().get(world); ProtectedRegion child = mgr.getRegion(regionName); if (child == null) { throw new ConfigRuntimeException(String.format("The region (%s) does not exist in world (%s).", regionName, world.getName()), ExceptionType.PluginInternalException, t); } if (args.length == 2) { try { child.setParent(null); } catch (ProtectedRegion.CircularInheritanceException ignore) { } } else { parentName = args[2].val(); ProtectedRegion parent = mgr.getRegion(parentName); if (parent == null) { throw new ConfigRuntimeException(String.format("The region (%s) does not exist in world (%s).", parentName, world.getName()), ExceptionType.PluginInternalException, t); } try { child.setParent(parent); } catch (ProtectedRegion.CircularInheritanceException e) { throw new ConfigRuntimeException(String.format("Circular inheritance detected."), ExceptionType.PluginInternalException, t); } } try { mgr.save(); } catch (Exception e) { throw new ConfigRuntimeException("Error while setting parent for protected region", ExceptionType.PluginInternalException, t, e); } return new CVoid(t); } @Override public CHVersion since() { return CHVersion.V3_3_1; } } public static abstract class SKFunction extends AbstractFunction { public boolean isRestricted() { return true; } public CHVersion since() { return CHVersion.V3_2_0; } public Boolean runAsync() { return false; } } }
true
false
null
null
diff --git a/core/src/main/java/cucumber/runtime/table/TableConverter.java b/core/src/main/java/cucumber/runtime/table/TableConverter.java index 51e3dea80..0d997d856 100644 --- a/core/src/main/java/cucumber/runtime/table/TableConverter.java +++ b/core/src/main/java/cucumber/runtime/table/TableConverter.java @@ -1,278 +1,282 @@ package cucumber.runtime.table; import cucumber.api.DataTable; import cucumber.deps.com.thoughtworks.xstream.converters.ConversionException; import cucumber.deps.com.thoughtworks.xstream.converters.SingleValueConverter; import cucumber.deps.com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter; import cucumber.deps.com.thoughtworks.xstream.io.HierarchicalStreamReader; import cucumber.runtime.CucumberException; import cucumber.runtime.ParameterInfo; import cucumber.runtime.xstream.CellWriter; import cucumber.runtime.xstream.ComplexTypeWriter; import cucumber.runtime.xstream.ListOfComplexTypeReader; import cucumber.runtime.xstream.ListOfSingleValueWriter; import cucumber.runtime.xstream.LocalizedXStreams; import cucumber.runtime.xstream.MapWriter; import gherkin.formatter.model.Comment; import gherkin.formatter.model.DataTableRow; import gherkin.util.Mapper; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import static cucumber.runtime.Utils.listItemType; import static cucumber.runtime.Utils.mapKeyType; import static cucumber.runtime.Utils.mapValueType; import static gherkin.util.FixJava.map; import static java.util.Arrays.asList; /** * This class converts a {@link cucumber.api.DataTable} to various other types. */ public class TableConverter { private static final List<Comment> NO_COMMENTS = Collections.emptyList(); private final LocalizedXStreams.LocalizedXStream xStream; private final ParameterInfo parameterInfo; public TableConverter(LocalizedXStreams.LocalizedXStream xStream, ParameterInfo parameterInfo) { this.xStream = xStream; this.parameterInfo = parameterInfo; } public <T> T convert(Type type, DataTable dataTable, boolean transposed) { try { xStream.setParameterType(parameterInfo); if (type == null || (type instanceof Class && ((Class) type).isAssignableFrom(DataTable.class))) { return (T) dataTable; } Type itemType = listItemType(type); if (itemType == null) { throw new CucumberException("Not a List type: " + type); } if (transposed) { dataTable = dataTable.transpose(); } Type listItemType = listItemType(itemType); if (listItemType == null) { SingleValueConverter singleValueConverter = xStream.getSingleValueConverter(itemType); if (singleValueConverter != null) { return (T) toListOfSingleValue(dataTable, singleValueConverter); } else { if (itemType instanceof Class) { if (Map.class.equals(itemType)) { // Non-generic map SingleValueConverter mapKeyConverter = xStream.getSingleValueConverter(String.class); SingleValueConverter mapValueConverter = xStream.getSingleValueConverter(String.class); return (T) toListOfSingleValueMap(dataTable, mapKeyConverter, mapValueConverter); } else { return (T) toListOfComplexType(dataTable, (Class) itemType); } } else { SingleValueConverter mapKeyConverter = xStream.getSingleValueConverter(mapKeyType(itemType)); SingleValueConverter mapValueConverter = xStream.getSingleValueConverter(mapValueType(itemType)); if (mapKeyConverter != null && mapValueConverter != null) { return (T) toListOfSingleValueMap(dataTable, mapKeyConverter, mapValueConverter); } else { throw new CucumberException("Can't convert a table to " + type + ". When using List<SomeComplexType>, SomeComplexType must not be a generic type"); } } } } else { // List<List<Something>> SingleValueConverter singleValueConverter = xStream.getSingleValueConverter(listItemType); if (singleValueConverter != null) { // List<List<SingleValue>> return (T) toListOfListOfSingleValue(dataTable, singleValueConverter); } else { // List<List<NOTSingleValue>> throw new CucumberException("Can't convert to " + type.toString()); } } } finally { xStream.unsetParameterInfo(); } } private <T> List<T> toListOfComplexType(DataTable dataTable, Class<T> itemType) { HierarchicalStreamReader reader = new ListOfComplexTypeReader(itemType, convertTopCellsToFieldNames(dataTable), dataTable.cells(1)); try { return Collections.unmodifiableList((List<T>) xStream.unmarshal(reader)); } catch (AbstractReflectionConverter.UnknownFieldException e) { throw new CucumberException(e.getShortMessage()); } catch (AbstractReflectionConverter.DuplicateFieldException e) { throw new CucumberException(e.getShortMessage()); } catch (ConversionException e) { - throw new CucumberException(String.format("Can't assign null value to one of the primitive fields in %s. Please use boxed types.", e.get("class"))); + if (e.getCause() instanceof NullPointerException) { + throw new CucumberException(String.format("Can't assign null value to one of the primitive fields in %s. Please use boxed types.", e.get("class"))); + } else { + throw e; + } } } private List<Object> toListOfSingleValue(DataTable dataTable, SingleValueConverter singleValueConverter) { List<Object> result = new ArrayList<Object>(); for (String cell : dataTable.flatten()) { result.add(singleValueConverter.fromString(cell)); } return Collections.unmodifiableList(result); } private List<List<Object>> toListOfListOfSingleValue(DataTable dataTable, SingleValueConverter singleValueConverter) { List<List<Object>> result = new ArrayList<List<Object>>(); for (List<String> row : dataTable.raw()) { List<Object> convertedRow = new ArrayList<Object>(); for (String cell : row) { convertedRow.add(singleValueConverter.fromString(cell)); } result.add(Collections.unmodifiableList(convertedRow)); } return Collections.unmodifiableList(result); } private List<Map<Object, Object>> toListOfSingleValueMap(DataTable dataTable, SingleValueConverter mapKeyConverter, SingleValueConverter mapValueConverter) { List<Map<Object, Object>> result = new ArrayList<Map<Object, Object>>(); List<String> keyStrings = dataTable.topCells(); List<Object> keys = new ArrayList<Object>(); for (String keyString : keyStrings) { keys.add(mapKeyConverter.fromString(keyString)); } List<List<String>> valueRows = dataTable.cells(1); for (List<String> valueRow : valueRows) { Map<Object, Object> map = new HashMap<Object, Object>(); int i = 0; for (String cell : valueRow) { map.put(keys.get(i), mapValueConverter.fromString(cell)); i++; } result.add(Collections.unmodifiableMap(map)); } return Collections.unmodifiableList(result); } /** * Converts a DataTable to a List of objects. */ public <T> List<T> toList(final Type type, DataTable dataTable) { if (type == null) { return convert(new GenericListType(new GenericListType(String.class)), dataTable, false); } return convert(new GenericListType(type), dataTable, false); } public <T> List<T> toList(final Type type, DataTable dataTable, boolean transposed) { if (type == null) { return convert(new GenericListType(new GenericListType(String.class)), dataTable, transposed); } return convert(new GenericListType(type), dataTable, transposed); } /** * Converts a List of objects to a DataTable. * * @param objects the objects to convert * @param columnNames an explicit list of column names * @return a DataTable */ public DataTable toTable(List<?> objects, String... columnNames) { try { xStream.setParameterType(parameterInfo); List<String> header = null; List<List<String>> valuesList = new ArrayList<List<String>>(); for (Object object : objects) { CellWriter writer; if (isListOfSingleValue(object)) { // XStream needs an instance of ArrayList object = new ArrayList<Object>((List<Object>) object); writer = new ListOfSingleValueWriter(); } else if (isArrayOfSingleValue(object)) { // XStream needs an instance of ArrayList object = new ArrayList<Object>(asList((Object[]) object)); writer = new ListOfSingleValueWriter(); } else if (object instanceof Map) { writer = new MapWriter(asList(columnNames)); } else { writer = new ComplexTypeWriter(asList(columnNames)); } xStream.marshal(object, writer); if (header == null) { header = writer.getHeader(); } List<String> values = writer.getValues(); valuesList.add(values); } return createDataTable(header, valuesList); } finally { xStream.unsetParameterInfo(); } } private DataTable createDataTable(List<String> header, List<List<String>> valuesList) { List<DataTableRow> gherkinRows = new ArrayList<DataTableRow>(); if (header != null) { gherkinRows.add(gherkinRow(header)); } for (List<String> values : valuesList) { gherkinRows.add(gherkinRow(values)); } return new DataTable(gherkinRows, this); } private DataTableRow gherkinRow(List<String> cells) { return new DataTableRow(NO_COMMENTS, cells, 0); } private List<String> convertTopCellsToFieldNames(DataTable dataTable) { final StringConverter mapper = new CamelCaseStringConverter(); return map(dataTable.topCells(), new Mapper<String, String>() { @Override public String map(String attributeName) { return mapper.map(attributeName); } }); } private boolean isListOfSingleValue(Object object) { if (object instanceof List) { List list = (List) object; return list.size() > 0 && xStream.getSingleValueConverter(list.get(0).getClass()) != null; } return false; } private boolean isArrayOfSingleValue(Object object) { if (object.getClass().isArray()) { Object[] array = (Object[]) object; return array.length > 0 && xStream.getSingleValueConverter(array[0].getClass()) != null; } return false; } private static class GenericListType implements ParameterizedType { private final Type type; public GenericListType(Type type) { this.type = type; } @Override public Type[] getActualTypeArguments() { return new Type[]{type}; } @Override public Type getRawType() { return List.class; } @Override public Type getOwnerType() { throw new UnsupportedOperationException(); } } }
true
false
null
null
diff --git a/sonar-server/src/main/java/org/sonar/server/db/migrations/DatabaseMigrations.java b/sonar-server/src/main/java/org/sonar/server/db/migrations/DatabaseMigrations.java index 360efaa38c..50eb4ea271 100644 --- a/sonar-server/src/main/java/org/sonar/server/db/migrations/DatabaseMigrations.java +++ b/sonar-server/src/main/java/org/sonar/server/db/migrations/DatabaseMigrations.java @@ -1,39 +1,41 @@ /* * SonarQube, open source software quality management tool. * Copyright (C) 2008-2013 SonarSource * mailto:contact AT sonarsource DOT com * * SonarQube is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * SonarQube is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.db.migrations; import com.google.common.collect.ImmutableList; +import org.sonar.server.db.migrations.debt.DevelopmentCostMeasuresMigration; import org.sonar.server.db.migrations.debt.IssueChangelogMigration; import org.sonar.server.db.migrations.debt.IssueMigration; import org.sonar.server.db.migrations.debt.TechnicalDebtMeasuresMigration; import org.sonar.server.db.migrations.violation.ViolationMigration; import java.util.List; public interface DatabaseMigrations { List<Class<? extends DatabaseMigration>> CLASSES = ImmutableList.of( ViolationMigration.class, IssueMigration.class, IssueChangelogMigration.class, - TechnicalDebtMeasuresMigration.class + TechnicalDebtMeasuresMigration.class, + DevelopmentCostMeasuresMigration.class ); }
false
false
null
null
diff --git a/src/Util/Analyzer.java b/src/Util/Analyzer.java index 1b17cef..fcf30eb 100644 --- a/src/Util/Analyzer.java +++ b/src/Util/Analyzer.java @@ -1,673 +1,675 @@ /*----------------------------------------------------------------------*/ /* Module : Analyzer.java Package : Util Classes Included: Analyzer, VoiceAnalysisData Purpose : Music analysis utilities Programmer : Ted Dumitrescu Date Started : 7/14/07 Updates : */ /*----------------------------------------------------------------------*/ package Util; /*----------------------------------------------------------------------*/ /* Imported packages */ import java.io.*; import java.net.*; import java.util.*; import DataStruct.*; import Gfx.*; /*----------------------------------------------------------------------*/ /*------------------------------------------------------------------------ Class: Analyzer Extends: - Purpose: Music analysis utilities for one score ------------------------------------------------------------------------*/ public class Analyzer { /*----------------------------------------------------------------------*/ /* Class variables */ /* for standalone application use */ static boolean screenoutput=false, recursive=false; public static final String BaseDataDir="/data/"; public static String BaseDataURL; static String initdirectory; static final int NUM_MENSURATIONS=4, MENS_O=0, MENS_C=1, MENS_3=2, MENS_P=3; static final String MENSURATION_NAMES[]=new String[] { "O","C","3","P" }; static final int NUMVOICES_FOR_RHYTHM_AVG=2; /*----------------------------------------------------------------------*/ /*----------------------------------------------------------------------*/ /* Instance variables */ PieceData musicData; ScoreRenderer renderedSections[]; int numVoices; /* analysis results */ public VoiceAnalysisData vad[]; public int totalUnpreparedSBDiss=0, totalPassingDissSMPair=0, totalOffbeatDissM=0; public double avgRhythmicDensity[], avgSyncopationDensity=0, OCLength=0, passingSMDissDensity=0, offbeatMDissDensity=0, dissDensity=0; /*----------------------------------------------------------------------*/ /*----------------------------------------------------------------------*/ /* Class methods */ /*------------------------------------------------------------------------ Method: void main(String args[]) Purpose: Main routine Parameters: Input: String args[] - program arguments Output: - Return: - ------------------------------------------------------------------------*/ public static void main(String args[]) { String cmdlineFilename=parseCmdLine(args); /* initialize data locations */ try { initdirectory=new File(".").getCanonicalPath()+BaseDataDir; BaseDataURL="file:///"+initdirectory; } catch (Exception e) { System.err.println("Error loading local file locations: "+e); e.printStackTrace(); } DataStruct.XMLReader.initparser(BaseDataURL,false); MusicWin.initScoreWindowing(BaseDataURL,initdirectory+"music/",false); try { Gfx.MusicFont.loadmusicface(BaseDataURL); } catch (Exception e) { System.err.println("Error loading font: "+e); e.printStackTrace(); } analyzeFiles(cmdlineFilename); } /*------------------------------------------------------------------------ Method: void analyzeFiles(String mainFilename) Purpose: Analyze one set of files (recursing to subdirectories if necessary) Parameters: Input: String mainFilename - name of file set in one directory String subdirName - name of subdirectory (null for base directory) Output: - Return: - ------------------------------------------------------------------------*/ static void analyzeFiles(String mainFilename) { try { PrintStream outs; OptionSet optSet=new OptionSet(null); RecursiveFileList fl=new RecursiveFileList(mainFilename,recursive); LinkedList<Analyzer> results=new LinkedList<Analyzer>(); /* analyze individual pieces */ for (File curfile : fl) { URL fileURL=curfile.toURI().toURL(); String fileName=curfile.getName(); System.out.print("Analyzing: "+fileName+"..."); PieceData musicData=new CMMEParser(fileURL).piece; ScoreRenderer[] renderedSections=renderSections(musicData,optSet); Analyzer a=new Analyzer(musicData,renderedSections); outs=screenoutput ? System.out : new PrintStream("data/stats/"+fileName+".txt"); a.printGeneralAnalysis(outs); if (!screenoutput) outs.close(); System.out.println("done"); results.add(a); } /* output result summary */ outs=screenoutput ? System.out : new PrintStream("data/stats/summary.txt"); if (screenoutput) { outs.println(); outs.println("SUMMARY"); outs.println(); } outs.println("Composer\tTitle\tDensity (O)\tDensity (C)\tDensity (3)\tDensity (P)\tSyncop density\tUnprepared syncop diss\tPassing SM diss density\tOffbeat M diss density"); for (Analyzer a : results) { outs.print(a.musicData.getComposer()+"\t"+a.musicData.getFullTitle()); for (int mi=0; mi<NUM_MENSURATIONS; mi++) { outs.print("\t"); if (a.avgRhythmicDensity[mi]>0) outs.print(String.valueOf(a.avgRhythmicDensity[mi])); else outs.print("-"); } outs.print("\t"+a.avgSyncopationDensity+"\t"+a.totalUnpreparedSBDiss); outs.print("\t"+a.passingSMDissDensity+"\t"+a.offbeatMDissDensity); outs.println(); } if (!screenoutput) outs.close(); } catch (Exception e) { System.err.println("Error: "+e); e.printStackTrace(); } } /*------------------------------------------------------------------------ Method: String parseCmdLine(String args[]) Purpose: Parse command line Parameters: Input: String args[] - program arguments Output: - Return: filename (or "*" if recursive with no filename specified) ------------------------------------------------------------------------*/ static String parseCmdLine(String args[]) { String fn=null; if (args.length<1) usage_exit(); for (int i=0; i<args.length; i++) if (args[i].charAt(0)=='-') /* options */ for (int opti=1; opti<args[i].length(); opti++) switch (args[i].charAt(opti)) { case 's': screenoutput=true; break; case 'r': recursive=true; break; default: usage_exit(); } else /* filename */ if (i!=args.length-1) usage_exit(); else fn=args[i]; if (fn==null) if (recursive) fn="*"; else usage_exit(); return "data\\music\\"+fn; } /*------------------------------------------------------------------------ Method: void usage_exit() Purpose: Exit for invalid command line Parameters: Input: - Output: - Return: - ------------------------------------------------------------------------*/ static void usage_exit() { System.err.println("Usage: java Util.Analyzer [options] filename"); System.err.println("Options:"); System.err.println(" -s: Screen output"); System.err.println(" -r: Recursively search subdirectories"); System.exit(1); } /*------------------------------------------------------------------------ Method: ScoreRenderer[] void renderSections() Purpose: Pre-render all sections of one piece Parameters: Input: - Output: - Return: rendered section array ------------------------------------------------------------------------*/ static final double SECTION_END_SPACING=10; static ScoreRenderer[] renderSections(PieceData musicData,OptionSet options) { double startX=0; /* initialize voice parameters */ int numVoices=musicData.getVoiceData().length; RenderedSectionParams[] sectionParams=new RenderedSectionParams[numVoices]; for (int i=0; i<numVoices; i++) sectionParams[i]=new RenderedSectionParams(); /* initialize sections */ int numSections=musicData.getNumSections(); ScoreRenderer[] renderedSections=new ScoreRenderer[numSections]; int nummeasures=0; for (int i=0; i<numSections; i++) { renderedSections[i]=new ScoreRenderer( i,musicData.getSection(i),musicData, sectionParams, options,nummeasures,startX); sectionParams=renderedSections[i].getEndingParams(); nummeasures+=renderedSections[i].getNumMeasures(); startX+=renderedSections[i].getXsize()+SECTION_END_SPACING; } return renderedSections; } /*----------------------------------------------------------------------*/ /* Instance methods */ /*------------------------------------------------------------------------ Constructor: Analyzer(PieceData musicData,ScoreRenderer renderedSections[]) Purpose: Initialize analysis functions for one score Parameters: Input: PieceData musicData - original music data ScoreRenderer renderedSections[] - scored+rendered music data Output: - ------------------------------------------------------------------------*/ public Analyzer(PieceData musicData,ScoreRenderer renderedSections[]) { this.musicData=musicData; this.renderedSections=renderedSections; this.numVoices=musicData.getVoiceData().length; } /*------------------------------------------------------------------------ Method: void printGeneralAnalysis(PrintStream outp) Purpose: Print generic score analysis Parameters: Input: - Output: PrintStream outp - output destination Return: - ------------------------------------------------------------------------*/ public void printGeneralAnalysis(PrintStream outp) { outp.println("General analysis: "+musicData.getComposer()+", "+musicData.getFullTitle()); outp.println(); outp.println("Number of voices: "+numVoices); outp.println("Number of sections: "+renderedSections.length); outp.println(); vad=new VoiceAnalysisData[numVoices]; for (int i=0; i<numVoices; i++) { vad[i]=new VoiceAnalysisData(); vad[i].vData=musicData.getVoiceData()[i]; } totalUnpreparedSBDiss=0; totalPassingDissSMPair=0; for (ScoreRenderer s : renderedSections) { for (int i=0; i<s.getNumVoices(); i++) { int curMens=MENS_C; Proportion curProp=new Proportion(Proportion.EQUALITY); double curPropVal=curProp.toDouble(), curMensStartTime=0; RenderList rl=s.getRenderedVoice(i); + if (rl==null) + break; int vnum=-1; for (int i1=0; i1<numVoices; i1++) if (rl.getVoiceData()==vad[i1].vData) vnum=i1; NoteEvent ne=null; RenderedEvent rne=null; int renum=0; for (RenderedEvent re : rl) { switch (re.getEvent().geteventtype()) { case Event.EVENT_NOTE: ne=(NoteEvent)re.getEvent(); rne=re; vad[i].numNotes[curMens]++; vad[i].totalNumNotes++; vad[i].totalNoteLengths[curMens]+=ne.getmusictime().toDouble()*curPropVal; if (ne.getPitch().isLowerThan(vad[i].lowestPitch)) vad[i].lowestPitch=ne.getPitch(); if (ne.getPitch().isHigherThan(vad[i].highestPitch)) vad[i].highestPitch=ne.getPitch(); if (curMens!=MENS_3 && curMens!=MENS_P) { vad[i].numNotesOC++; if (syncopated(s,re)) vad[i].totalOffbeat++; if (isUnpreparedSuspension(s,re)) { totalUnpreparedSBDiss++; outp.println("Unprepared SB/M dissonance in m. "+(re.getmeasurenum()+1)); } if (isPassingDissonantSMPair(s,i,renum)) totalPassingDissSMPair++; if (isOffbeatDissonantM(s,re)) totalOffbeatDissM++; } break; case Event.EVENT_MULTIEVENT: // to be implemented Mensuration m=re.getEvent().getMensInfo(); if (m!=null) curMens=getMensType(m); break; case Event.EVENT_MENS: vad[i].totalPassageLengths[curMens]+=re.getmusictime().toDouble()-curMensStartTime; curMensStartTime=re.getmusictime().toDouble(); curMens=getMensType(re.getEvent().getMensInfo()); if (curMens==MENS_O && ((MensEvent)re.getEvent()).getSigns().size()>1 || ((MensEvent)re.getEvent()).getMainSign().signType==MensSignElement.NUMBERS) curMens=MENS_3; break; case Event.EVENT_PROPORTION: curProp.multiply(((ProportionEvent)re.getEvent()).getproportion()); curPropVal=curProp.toDouble(); break; } renum++; } if (ne!=null) { /* discount final longa */ vad[i].numNotes[curMens]--; vad[i].totalNumNotes--; vad[i].totalNoteLengths[curMens]-=ne.getmusictime().toDouble()*curPropVal; vad[i].totalPassageLengths[curMens]+=rne.getmusictime().toDouble()-curMensStartTime; } } } if (totalUnpreparedSBDiss>0) outp.println(); for (int i=0; i<numVoices; i++) { outp.println("Voice "+(i+1)+": "+musicData.getVoiceData()[i].getName()); outp.println(" Range: "+vad[i].lowestPitch+" - "+vad[i].highestPitch); for (int mi=0; mi<NUM_MENSURATIONS; mi++) if (vad[i].numNotes[mi]!=0) { outp.println(" Mensuration type: "+MENSURATION_NAMES[mi]); outp.println(" Number of notes (not including final): "+vad[i].numNotes[mi]); outp.println(" Total note lengths: "+vad[i].totalNoteLengths[mi]); vad[i].rhythmicDensity[mi]=vad[i].totalNoteLengths[mi]/(double)vad[i].numNotes[mi]; outp.println(" Rhythmic density: "+vad[i].rhythmicDensity[mi]); } vad[i].syncopationDensity=(double)vad[i].totalOffbeat/(double)vad[i].numNotesOC; outp.println(" Number of syncopated notes: "+vad[i].totalOffbeat); outp.println(" Syncopation density: "+vad[i].syncopationDensity); outp.println(); } /* averages of the top two voices */ avgRhythmicDensity=new double[] { 0,0,0,0 }; outp.println(); outp.println("Averages for highest "+NUMVOICES_FOR_RHYTHM_AVG+" voices"); for (int i=0; i<numVoices && i<NUMVOICES_FOR_RHYTHM_AVG; i++) for (int mi=0; mi<NUM_MENSURATIONS; mi++) if (vad[i].numNotes[mi]>0) avgRhythmicDensity[mi]+=vad[i].rhythmicDensity[mi]/2; // for SB, not minims for (int mi=0; mi<NUM_MENSURATIONS; mi++) { if (numVoices>NUMVOICES_FOR_RHYTHM_AVG-1) avgRhythmicDensity[mi]/=(double)NUMVOICES_FOR_RHYTHM_AVG; if (avgRhythmicDensity[mi]>0) outp.println(" Rhythmic density in SB ("+MENSURATION_NAMES[mi]+"): "+ avgRhythmicDensity[mi]); } avgSyncopationDensity=0; for (int i=0; i<numVoices && i<NUMVOICES_FOR_RHYTHM_AVG; i++) avgSyncopationDensity+=vad[i].syncopationDensity; if (numVoices>NUMVOICES_FOR_RHYTHM_AVG-1) avgSyncopationDensity/=(double)NUMVOICES_FOR_RHYTHM_AVG; outp.println(" Syncopation density: "+avgSyncopationDensity); if (totalUnpreparedSBDiss>0) outp.println("Number of unprepared syncopated SB/M dissonances: "+totalUnpreparedSBDiss); outp.println("Number of passing dissonant SM pairs: "+totalPassingDissSMPair); outp.println("Number of dissonant offbeat Ms: "+totalOffbeatDissM); double avgMensLengths[]=new double[] { 0,0,0,0 }; for (int i=0; i<numVoices; i++) for (int mi=0; mi<NUM_MENSURATIONS; mi++) avgMensLengths[mi]+=vad[i].totalPassageLengths[mi]; for (int mi=0; mi<NUM_MENSURATIONS; mi++) avgMensLengths[mi]/=(double)numVoices; OCLength=(avgMensLengths[MENS_O]+avgMensLengths[MENS_C])/2; /* in SB */ passingSMDissDensity=totalPassingDissSMPair/OCLength; offbeatMDissDensity=totalOffbeatDissM/OCLength; dissDensity=(totalPassingDissSMPair+totalOffbeatDissM)/OCLength; outp.println("Total length of O/C sections: "+OCLength); outp.println("Passing dissonant SM pair density: "+passingSMDissDensity); outp.println("Offbeat dissonant M density: "+offbeatMDissDensity); // outp.println("Basic dissonance density: "+dissDensity); } int getMensType(Mensuration m) { if (m.prolatio==Mensuration.MENS_TERNARY) return MENS_P; if (m.tempus==Mensuration.MENS_TERNARY) return MENS_O; return MENS_C; } boolean isUnpreparedSuspension(ScoreRenderer s,RenderedEvent re) { MeasureInfo measure=s.getMeasure(re.getmeasurenum()); double mt=re.getmusictime().toDouble(), measurePos=mt-measure.startMusicTime.toDouble(), len=re.getEvent().getLength().toDouble(); NoteEvent ne=(NoteEvent)re.getEvent(); if (re.getmusictime().i2%3==0) /* avoid sesquialtera/tripla */ return false; if (len<1) return false; if (len>=2 && ((int)measurePos)%2==0) return false; if (len>=1 && len<2 && (double)(measurePos-(int)measurePos)<=0.0) return false; Pitch p=ne.getPitch(); RenderedSonority rs=re.getFullSonority(); for (int i=0; i<rs.getNumPitches(); i++) if (isDissonant(p,rs.getPitch(i),i==0) && rs.getRenderedNote(i).getmusictime().toDouble()<mt) return true; return false; } boolean isPassingDissonantSMPair(ScoreRenderer s,int vnum,int renum) { RenderedEvent re=s.eventinfo[vnum].getEvent(renum); MeasureInfo measure=s.getMeasure(re.getmeasurenum()); double mt=re.getmusictime().toDouble(), measurePos=mt-measure.startMusicTime.toDouble(); NoteEvent ne=(NoteEvent)re.getEvent(); if (ne.getnotetype()!=NoteEvent.NT_Semiminima || (double)(measurePos-(int)measurePos)>0 || ((int)measurePos)%2==0) return false; /* check next note */ RenderedEvent nextNote=s.getNeighboringEventOfType(Event.EVENT_NOTE,vnum,renum+1,1); if (nextNote==null || nextNote.getmusictime().toDouble()>mt+0.5) return false; Event e=nextNote.getEvent(); NoteEvent ne2=e.geteventtype()==Event.EVENT_MULTIEVENT ? ((MultiEvent)e).getLowestNote() : (NoteEvent)e; if (ne2.getnotetype()!=NoteEvent.NT_Semiminima) return false; /* check for dissonance */ Pitch p=ne.getPitch(); RenderedSonority rs=re.getFullSonority(); for (int i=0; i<rs.getNumPitches(); i++) if (isDissonant(p,rs.getPitch(i),i==0)) return true; return false; } boolean isOffbeatDissonantM(ScoreRenderer s,RenderedEvent re) { MeasureInfo measure=s.getMeasure(re.getmeasurenum()); double mt=re.getmusictime().toDouble(), measurePos=mt-measure.startMusicTime.toDouble(), len=re.getEvent().getLength().toDouble(); NoteEvent ne=(NoteEvent)re.getEvent(); if (ne.getnotetype()!=NoteEvent.NT_Minima || (double)(measurePos-(int)measurePos)>0 || ((int)measurePos)%2==0) return false; if (len>1) return false; Pitch p=ne.getPitch(); RenderedSonority rs=re.getFullSonority(); for (int i=0; i<rs.getNumPitches(); i++) if (isDissonant(p,rs.getPitch(i),i==0) && rs.getRenderedNote(i).getmusictime().toDouble()<mt) return true; return false; } boolean isDissonant(Pitch p1,Pitch p2,boolean bassInterval) { int interval=getAbsInterval(p1,p2); if (interval==2 || interval==7 || (bassInterval && interval==4)) return true; return false; } int getAbsInterval(Pitch p1,Pitch p2) { return Math.abs(p1.placenum-p2.placenum)%7+1; } boolean syncopated(ScoreRenderer s,RenderedEvent re) { MeasureInfo measure=s.getMeasure(re.getmeasurenum()); double mt=re.getmusictime().toDouble(), measurePos=mt-measure.startMusicTime.toDouble(), len=re.getEvent().getLength().toDouble(); if (re.getmusictime().i2%3==0) /* avoid sesquialtera/tripla */ return false; if (len<=.5) /* no SM or smaller */ return false; if (len<=1 && measurePos-(int)measurePos>0) return true; if (len>1 && (measurePos-(int)measurePos>0 || ((int)measurePos)%2!=0)) return true; return false; } } /*------------------------------------------------------------------------ Class: VoiceAnalysisData Extends: - Purpose: Analysis parameters for one voice ------------------------------------------------------------------------*/ class VoiceAnalysisData { Voice vData=null; int numNotes[]=new int[] { 0,0,0,0 }, totalNumNotes=0, numNotesOC=0; double totalNoteLengths[]=new double[] { 0,0,0,0 }, rhythmicDensity[]=new double[] { 0,0,0,0 }, totalPassageLengths[]=new double[] { 0,0,0,0 }; Pitch lowestPitch=Pitch.HIGHEST_PITCH, highestPitch=Pitch.LOWEST_PITCH; int totalOffbeat=0; double syncopationDensity=0; public VoiceAnalysisData() { } }
true
true
public void printGeneralAnalysis(PrintStream outp) { outp.println("General analysis: "+musicData.getComposer()+", "+musicData.getFullTitle()); outp.println(); outp.println("Number of voices: "+numVoices); outp.println("Number of sections: "+renderedSections.length); outp.println(); vad=new VoiceAnalysisData[numVoices]; for (int i=0; i<numVoices; i++) { vad[i]=new VoiceAnalysisData(); vad[i].vData=musicData.getVoiceData()[i]; } totalUnpreparedSBDiss=0; totalPassingDissSMPair=0; for (ScoreRenderer s : renderedSections) { for (int i=0; i<s.getNumVoices(); i++) { int curMens=MENS_C; Proportion curProp=new Proportion(Proportion.EQUALITY); double curPropVal=curProp.toDouble(), curMensStartTime=0; RenderList rl=s.getRenderedVoice(i); int vnum=-1; for (int i1=0; i1<numVoices; i1++) if (rl.getVoiceData()==vad[i1].vData) vnum=i1; NoteEvent ne=null; RenderedEvent rne=null; int renum=0; for (RenderedEvent re : rl) { switch (re.getEvent().geteventtype()) { case Event.EVENT_NOTE: ne=(NoteEvent)re.getEvent(); rne=re; vad[i].numNotes[curMens]++; vad[i].totalNumNotes++; vad[i].totalNoteLengths[curMens]+=ne.getmusictime().toDouble()*curPropVal; if (ne.getPitch().isLowerThan(vad[i].lowestPitch)) vad[i].lowestPitch=ne.getPitch(); if (ne.getPitch().isHigherThan(vad[i].highestPitch)) vad[i].highestPitch=ne.getPitch(); if (curMens!=MENS_3 && curMens!=MENS_P) { vad[i].numNotesOC++; if (syncopated(s,re)) vad[i].totalOffbeat++; if (isUnpreparedSuspension(s,re)) { totalUnpreparedSBDiss++; outp.println("Unprepared SB/M dissonance in m. "+(re.getmeasurenum()+1)); } if (isPassingDissonantSMPair(s,i,renum)) totalPassingDissSMPair++; if (isOffbeatDissonantM(s,re)) totalOffbeatDissM++; } break; case Event.EVENT_MULTIEVENT: // to be implemented Mensuration m=re.getEvent().getMensInfo(); if (m!=null) curMens=getMensType(m); break; case Event.EVENT_MENS: vad[i].totalPassageLengths[curMens]+=re.getmusictime().toDouble()-curMensStartTime; curMensStartTime=re.getmusictime().toDouble(); curMens=getMensType(re.getEvent().getMensInfo()); if (curMens==MENS_O && ((MensEvent)re.getEvent()).getSigns().size()>1 || ((MensEvent)re.getEvent()).getMainSign().signType==MensSignElement.NUMBERS) curMens=MENS_3; break; case Event.EVENT_PROPORTION: curProp.multiply(((ProportionEvent)re.getEvent()).getproportion()); curPropVal=curProp.toDouble(); break; } renum++; } if (ne!=null) { /* discount final longa */ vad[i].numNotes[curMens]--; vad[i].totalNumNotes--; vad[i].totalNoteLengths[curMens]-=ne.getmusictime().toDouble()*curPropVal; vad[i].totalPassageLengths[curMens]+=rne.getmusictime().toDouble()-curMensStartTime; } } } if (totalUnpreparedSBDiss>0) outp.println(); for (int i=0; i<numVoices; i++) { outp.println("Voice "+(i+1)+": "+musicData.getVoiceData()[i].getName()); outp.println(" Range: "+vad[i].lowestPitch+" - "+vad[i].highestPitch); for (int mi=0; mi<NUM_MENSURATIONS; mi++) if (vad[i].numNotes[mi]!=0) { outp.println(" Mensuration type: "+MENSURATION_NAMES[mi]); outp.println(" Number of notes (not including final): "+vad[i].numNotes[mi]); outp.println(" Total note lengths: "+vad[i].totalNoteLengths[mi]); vad[i].rhythmicDensity[mi]=vad[i].totalNoteLengths[mi]/(double)vad[i].numNotes[mi]; outp.println(" Rhythmic density: "+vad[i].rhythmicDensity[mi]); } vad[i].syncopationDensity=(double)vad[i].totalOffbeat/(double)vad[i].numNotesOC; outp.println(" Number of syncopated notes: "+vad[i].totalOffbeat); outp.println(" Syncopation density: "+vad[i].syncopationDensity); outp.println(); } /* averages of the top two voices */ avgRhythmicDensity=new double[] { 0,0,0,0 }; outp.println(); outp.println("Averages for highest "+NUMVOICES_FOR_RHYTHM_AVG+" voices"); for (int i=0; i<numVoices && i<NUMVOICES_FOR_RHYTHM_AVG; i++) for (int mi=0; mi<NUM_MENSURATIONS; mi++) if (vad[i].numNotes[mi]>0) avgRhythmicDensity[mi]+=vad[i].rhythmicDensity[mi]/2; // for SB, not minims for (int mi=0; mi<NUM_MENSURATIONS; mi++) { if (numVoices>NUMVOICES_FOR_RHYTHM_AVG-1) avgRhythmicDensity[mi]/=(double)NUMVOICES_FOR_RHYTHM_AVG; if (avgRhythmicDensity[mi]>0) outp.println(" Rhythmic density in SB ("+MENSURATION_NAMES[mi]+"): "+ avgRhythmicDensity[mi]); } avgSyncopationDensity=0; for (int i=0; i<numVoices && i<NUMVOICES_FOR_RHYTHM_AVG; i++) avgSyncopationDensity+=vad[i].syncopationDensity; if (numVoices>NUMVOICES_FOR_RHYTHM_AVG-1) avgSyncopationDensity/=(double)NUMVOICES_FOR_RHYTHM_AVG; outp.println(" Syncopation density: "+avgSyncopationDensity); if (totalUnpreparedSBDiss>0) outp.println("Number of unprepared syncopated SB/M dissonances: "+totalUnpreparedSBDiss); outp.println("Number of passing dissonant SM pairs: "+totalPassingDissSMPair); outp.println("Number of dissonant offbeat Ms: "+totalOffbeatDissM); double avgMensLengths[]=new double[] { 0,0,0,0 }; for (int i=0; i<numVoices; i++) for (int mi=0; mi<NUM_MENSURATIONS; mi++) avgMensLengths[mi]+=vad[i].totalPassageLengths[mi]; for (int mi=0; mi<NUM_MENSURATIONS; mi++) avgMensLengths[mi]/=(double)numVoices; OCLength=(avgMensLengths[MENS_O]+avgMensLengths[MENS_C])/2; /* in SB */ passingSMDissDensity=totalPassingDissSMPair/OCLength; offbeatMDissDensity=totalOffbeatDissM/OCLength; dissDensity=(totalPassingDissSMPair+totalOffbeatDissM)/OCLength; outp.println("Total length of O/C sections: "+OCLength); outp.println("Passing dissonant SM pair density: "+passingSMDissDensity); outp.println("Offbeat dissonant M density: "+offbeatMDissDensity); // outp.println("Basic dissonance density: "+dissDensity); }
public void printGeneralAnalysis(PrintStream outp) { outp.println("General analysis: "+musicData.getComposer()+", "+musicData.getFullTitle()); outp.println(); outp.println("Number of voices: "+numVoices); outp.println("Number of sections: "+renderedSections.length); outp.println(); vad=new VoiceAnalysisData[numVoices]; for (int i=0; i<numVoices; i++) { vad[i]=new VoiceAnalysisData(); vad[i].vData=musicData.getVoiceData()[i]; } totalUnpreparedSBDiss=0; totalPassingDissSMPair=0; for (ScoreRenderer s : renderedSections) { for (int i=0; i<s.getNumVoices(); i++) { int curMens=MENS_C; Proportion curProp=new Proportion(Proportion.EQUALITY); double curPropVal=curProp.toDouble(), curMensStartTime=0; RenderList rl=s.getRenderedVoice(i); if (rl==null) break; int vnum=-1; for (int i1=0; i1<numVoices; i1++) if (rl.getVoiceData()==vad[i1].vData) vnum=i1; NoteEvent ne=null; RenderedEvent rne=null; int renum=0; for (RenderedEvent re : rl) { switch (re.getEvent().geteventtype()) { case Event.EVENT_NOTE: ne=(NoteEvent)re.getEvent(); rne=re; vad[i].numNotes[curMens]++; vad[i].totalNumNotes++; vad[i].totalNoteLengths[curMens]+=ne.getmusictime().toDouble()*curPropVal; if (ne.getPitch().isLowerThan(vad[i].lowestPitch)) vad[i].lowestPitch=ne.getPitch(); if (ne.getPitch().isHigherThan(vad[i].highestPitch)) vad[i].highestPitch=ne.getPitch(); if (curMens!=MENS_3 && curMens!=MENS_P) { vad[i].numNotesOC++; if (syncopated(s,re)) vad[i].totalOffbeat++; if (isUnpreparedSuspension(s,re)) { totalUnpreparedSBDiss++; outp.println("Unprepared SB/M dissonance in m. "+(re.getmeasurenum()+1)); } if (isPassingDissonantSMPair(s,i,renum)) totalPassingDissSMPair++; if (isOffbeatDissonantM(s,re)) totalOffbeatDissM++; } break; case Event.EVENT_MULTIEVENT: // to be implemented Mensuration m=re.getEvent().getMensInfo(); if (m!=null) curMens=getMensType(m); break; case Event.EVENT_MENS: vad[i].totalPassageLengths[curMens]+=re.getmusictime().toDouble()-curMensStartTime; curMensStartTime=re.getmusictime().toDouble(); curMens=getMensType(re.getEvent().getMensInfo()); if (curMens==MENS_O && ((MensEvent)re.getEvent()).getSigns().size()>1 || ((MensEvent)re.getEvent()).getMainSign().signType==MensSignElement.NUMBERS) curMens=MENS_3; break; case Event.EVENT_PROPORTION: curProp.multiply(((ProportionEvent)re.getEvent()).getproportion()); curPropVal=curProp.toDouble(); break; } renum++; } if (ne!=null) { /* discount final longa */ vad[i].numNotes[curMens]--; vad[i].totalNumNotes--; vad[i].totalNoteLengths[curMens]-=ne.getmusictime().toDouble()*curPropVal; vad[i].totalPassageLengths[curMens]+=rne.getmusictime().toDouble()-curMensStartTime; } } } if (totalUnpreparedSBDiss>0) outp.println(); for (int i=0; i<numVoices; i++) { outp.println("Voice "+(i+1)+": "+musicData.getVoiceData()[i].getName()); outp.println(" Range: "+vad[i].lowestPitch+" - "+vad[i].highestPitch); for (int mi=0; mi<NUM_MENSURATIONS; mi++) if (vad[i].numNotes[mi]!=0) { outp.println(" Mensuration type: "+MENSURATION_NAMES[mi]); outp.println(" Number of notes (not including final): "+vad[i].numNotes[mi]); outp.println(" Total note lengths: "+vad[i].totalNoteLengths[mi]); vad[i].rhythmicDensity[mi]=vad[i].totalNoteLengths[mi]/(double)vad[i].numNotes[mi]; outp.println(" Rhythmic density: "+vad[i].rhythmicDensity[mi]); } vad[i].syncopationDensity=(double)vad[i].totalOffbeat/(double)vad[i].numNotesOC; outp.println(" Number of syncopated notes: "+vad[i].totalOffbeat); outp.println(" Syncopation density: "+vad[i].syncopationDensity); outp.println(); } /* averages of the top two voices */ avgRhythmicDensity=new double[] { 0,0,0,0 }; outp.println(); outp.println("Averages for highest "+NUMVOICES_FOR_RHYTHM_AVG+" voices"); for (int i=0; i<numVoices && i<NUMVOICES_FOR_RHYTHM_AVG; i++) for (int mi=0; mi<NUM_MENSURATIONS; mi++) if (vad[i].numNotes[mi]>0) avgRhythmicDensity[mi]+=vad[i].rhythmicDensity[mi]/2; // for SB, not minims for (int mi=0; mi<NUM_MENSURATIONS; mi++) { if (numVoices>NUMVOICES_FOR_RHYTHM_AVG-1) avgRhythmicDensity[mi]/=(double)NUMVOICES_FOR_RHYTHM_AVG; if (avgRhythmicDensity[mi]>0) outp.println(" Rhythmic density in SB ("+MENSURATION_NAMES[mi]+"): "+ avgRhythmicDensity[mi]); } avgSyncopationDensity=0; for (int i=0; i<numVoices && i<NUMVOICES_FOR_RHYTHM_AVG; i++) avgSyncopationDensity+=vad[i].syncopationDensity; if (numVoices>NUMVOICES_FOR_RHYTHM_AVG-1) avgSyncopationDensity/=(double)NUMVOICES_FOR_RHYTHM_AVG; outp.println(" Syncopation density: "+avgSyncopationDensity); if (totalUnpreparedSBDiss>0) outp.println("Number of unprepared syncopated SB/M dissonances: "+totalUnpreparedSBDiss); outp.println("Number of passing dissonant SM pairs: "+totalPassingDissSMPair); outp.println("Number of dissonant offbeat Ms: "+totalOffbeatDissM); double avgMensLengths[]=new double[] { 0,0,0,0 }; for (int i=0; i<numVoices; i++) for (int mi=0; mi<NUM_MENSURATIONS; mi++) avgMensLengths[mi]+=vad[i].totalPassageLengths[mi]; for (int mi=0; mi<NUM_MENSURATIONS; mi++) avgMensLengths[mi]/=(double)numVoices; OCLength=(avgMensLengths[MENS_O]+avgMensLengths[MENS_C])/2; /* in SB */ passingSMDissDensity=totalPassingDissSMPair/OCLength; offbeatMDissDensity=totalOffbeatDissM/OCLength; dissDensity=(totalPassingDissSMPair+totalOffbeatDissM)/OCLength; outp.println("Total length of O/C sections: "+OCLength); outp.println("Passing dissonant SM pair density: "+passingSMDissDensity); outp.println("Offbeat dissonant M density: "+offbeatMDissDensity); // outp.println("Basic dissonance density: "+dissDensity); }
diff --git a/editor/src/main/java/kkckkc/jsourcepad/model/Application.java b/editor/src/main/java/kkckkc/jsourcepad/model/Application.java index 4f9f369..ed94a11 100644 --- a/editor/src/main/java/kkckkc/jsourcepad/model/Application.java +++ b/editor/src/main/java/kkckkc/jsourcepad/model/Application.java @@ -1,246 +1,250 @@ package kkckkc.jsourcepad.model; import kkckkc.jsourcepad.Plugin; import kkckkc.jsourcepad.PluginManager; import kkckkc.jsourcepad.ScopeRoot; import kkckkc.jsourcepad.model.bundle.BundleManager; import kkckkc.jsourcepad.model.settings.GlobalSettingsManager; import kkckkc.jsourcepad.model.settings.SettingsManager; import kkckkc.jsourcepad.model.settings.StyleSettings; import kkckkc.jsourcepad.theme.DefaultTheme; import kkckkc.jsourcepad.theme.Theme; import kkckkc.jsourcepad.util.BeanFactoryLoader; import kkckkc.jsourcepad.util.Config; import kkckkc.jsourcepad.util.Null; import kkckkc.jsourcepad.util.command.CommandExecutor; import kkckkc.jsourcepad.util.io.ErrorDialog; import kkckkc.jsourcepad.util.messagebus.AbstractMessageBus; import kkckkc.jsourcepad.util.messagebus.MessageBus; import kkckkc.syntaxpane.parse.grammar.LanguageManager; import kkckkc.syntaxpane.parse.grammar.textmate.ColorUtils; import kkckkc.syntaxpane.style.*; import kkckkc.utils.io.FileUtils; import org.mortbay.jetty.servlet.Context; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.support.DefaultListableBeanFactory; -import java.awt.*; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Application extends AbstractMessageBus implements MessageBus, ScopeRoot { private static Application application = new Application(); private static Theme theme; BeanFactory beanFactory; private ExecutorService threadPool; private StyleScheme cachedStyleScheme; private GlobalSettingsManager settingsManager; private PersistentCacheManagerImpl persistentCacheManager; private BundleManager bundleManager; protected Application() { this.threadPool = Executors.newCachedThreadPool(); this.settingsManager = new GlobalSettingsManager(); this.persistentCacheManager = new PersistentCacheManagerImpl(); } public static Application get() { return application; } public static synchronized void init() { BeanFactoryLoader loader = new BeanFactoryLoader(); DefaultListableBeanFactory beanFactory = loader.load(BeanFactoryLoader.APPLICATION); // Bootstrapped bean beanFactory.registerSingleton("settingsManager", application.getSettingsManager()); beanFactory.registerSingleton("persistentCacheManager", application.getPersistentCacheManager()); beanFactory.registerSingleton("beanFactoryLoader", loader); beanFactory.registerSingleton("application", application); application.beanFactory = beanFactory; theme = initTheme(); theme.activate(); beanFactory.registerSingleton("theme", theme); // Load application controller beanFactory.getBean("applicationController"); beanFactory.preInstantiateSingletons(); } private static Theme initTheme() { for (Plugin p : PluginManager.getActivePlugins()) { if (! (p instanceof Theme)) continue; return (Theme) p; } return new DefaultTheme(); } public PersistentCacheManager getPersistentCacheManager() { return persistentCacheManager; } public SettingsManager getSettingsManager() { return settingsManager; } public Context getHttpServer() { return beanFactory.getBean(Context.class); } public ExecutorService getThreadPool() { return threadPool; } public WindowManager getWindowManager() { return beanFactory.getBean(WindowManager.class); } public LanguageManager getLanguageManager() { return beanFactory.getBean(LanguageManager.class); } public Browser getBrowser() { return beanFactory.getBean(Browser.class); } public StyleScheme getStyleScheme(StyleSettings styleSettings) { StyleParser styleParser = beanFactory.getBean(StyleParser.class); String location = new File(Config.getThemesFolder(), styleSettings.getThemeLocation()).toString(); File source = new File(location); if (cachedStyleScheme != null && cachedStyleScheme.getSource().equals(source)) return cachedStyleScheme; StyleScheme scheme = styleParser.parse(source); scheme = new DelegatingStyleScheme(scheme) { private boolean inited = false; private Map<ScopeSelector, TextStyle> styles; private synchronized void init() { BundleManager bundleManager = getBundleManager(); Map<String, Map<ScopeSelector,Object>> preferences = bundleManager.getPreferences(); Map<ScopeSelector, Object> foregrounds = preferences.get("foreground"); Map<ScopeSelector, Object> backgrounds = preferences.get("background"); + if (foregrounds == null || backgrounds == null) { + this.inited = true; + return; + } + Set<ScopeSelector> keys = new HashSet<ScopeSelector>(foregrounds.keySet()); keys.retainAll(backgrounds.keySet()); styles = super.getStyles(); for (ScopeSelector scopeSelector : keys) { styles.put(scopeSelector, new StyleBean(ColorUtils.makeColor((String) foregrounds.get(scopeSelector)), ColorUtils.makeColor((String) backgrounds.get(scopeSelector)))); } this.inited = true; } @Override public Map<ScopeSelector, TextStyle> getStyles() { if (! inited) init(); return styles; } }; cachedStyleScheme = scheme; return scheme; } public String[] getStyleSchemes() { return Config.getThemesFolder().list(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(".tmTheme"); } }); } public BundleManager getBundleManager() { if (bundleManager == null) bundleManager = beanFactory.getBean(BundleManager.class); return bundleManager; } public Theme getTheme() { return theme; } @Override public DefaultListableBeanFactory getBeanFactory() { return (DefaultListableBeanFactory) this.beanFactory; } public ClipboardManager getClipboardManager() { return beanFactory.getBean(ClipboardManager.class); } public ErrorDialog getErrorDialog() { return beanFactory.getBean(ErrorDialog.class); } public Window open(File file) throws IOException { WindowManager wm = getWindowManager(); file = file.getCanonicalFile(); if (file.isDirectory()) { for (Window w : wm.getWindows()) { if (Null.Utils.isNull(w.getProject())) continue; if (file.equals(w.getProject().getProjectDir())) { return w; } } Window window = wm.newWindow(file); window.getContainer().toFront(); return window; } else { Window windowToUse = null; for (Window w : wm.getWindows()) { if (Null.Utils.isNull(w.getProject()) && windowToUse == null) { windowToUse = w; } else { if (FileUtils.isAncestorOf(file, w.getProject().getProjectDir())) { windowToUse = w; } } } if (windowToUse == null) { windowToUse = wm.newWindow(null); } windowToUse.getDocList().open(file); windowToUse.getContainer().toFront(); return windowToUse; } } public CommandExecutor getCommandExecutor() { return beanFactory.getBean(CommandExecutor.class); } }
false
false
null
null
diff --git a/src/de/nomagic/printerController/pacemaker/ClientConnection.java b/src/de/nomagic/printerController/pacemaker/ClientConnection.java index 45dcb13..a15feee 100644 --- a/src/de/nomagic/printerController/pacemaker/ClientConnection.java +++ b/src/de/nomagic/printerController/pacemaker/ClientConnection.java @@ -1,447 +1,463 @@ /* * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see <http://www.gnu.org/licenses/> * */ package de.nomagic.printerController.pacemaker; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.nomagic.printerController.Tool; /** * @author Lars P&ouml;tter * (<a href=mailto:[email protected]>[email protected]</a>) */ public abstract class ClientConnection extends Thread { private final static Logger log = LoggerFactory.getLogger("ClientConnection"); private final static boolean useNonBlocking = true; public final static int MAX_MS_BETWEEN_TWO_BYTES = 20; public final static int MAX_MS_UNTIL_REPLY_ARRIVES = 100; public final static int MAX_TRANSMISSIONS = 2; // number of tries to send the frame protected InputStream in; protected OutputStream out; protected byte sequenceNumber = 0; protected boolean isSynced = false; private boolean isFirstOrder = true; private BlockingQueue<Reply> receiveQueue = new LinkedBlockingQueue<Reply>(); private static byte crc_array[] = { // 0 1 2 3 4 5 6 7 8 9 A B C D E F /* 0*/ (byte)0x00, (byte)0xa6, (byte)0xea, (byte)0x4c, (byte)0x72, (byte)0xd4, (byte)0x98, (byte)0x3e, (byte)0xe4, (byte)0x42, (byte)0x0e, (byte)0xa8, (byte)0x96, (byte)0x30, (byte)0x7c, (byte)0xda, /* 1*/ (byte)0x6e, (byte)0xc8, (byte)0x84, (byte)0x22, (byte)0x1c, (byte)0xba, (byte)0xf6, (byte)0x50, (byte)0x8a, (byte)0x2c, (byte)0x60, (byte)0xc6, (byte)0xf8, (byte)0x5e, (byte)0x12, (byte)0xb4, /* 2*/ (byte)0xdc, (byte)0x7a, (byte)0x36, (byte)0x90, (byte)0xae, (byte)0x08, (byte)0x44, (byte)0xe2, (byte)0x38, (byte)0x9e, (byte)0xd2, (byte)0x74, (byte)0x4a, (byte)0xec, (byte)0xa0, (byte)0x06, /* 3*/ (byte)0xb2, (byte)0x14, (byte)0x58, (byte)0xfe, (byte)0xc0, (byte)0x66, (byte)0x2a, (byte)0x8c, (byte)0x56, (byte)0xf0, (byte)0xbc, (byte)0x1a, (byte)0x24, (byte)0x82, (byte)0xce, (byte)0x68, /* 4*/ (byte)0x1e, (byte)0xb8, (byte)0xf4, (byte)0x52, (byte)0x6c, (byte)0xca, (byte)0x86, (byte)0x20, (byte)0xfa, (byte)0x5c, (byte)0x10, (byte)0xb6, (byte)0x88, (byte)0x2e, (byte)0x62, (byte)0xc4, /* 5*/ (byte)0x70, (byte)0xd6, (byte)0x9a, (byte)0x3c, (byte)0x02, (byte)0xa4, (byte)0xe8, (byte)0x4e, (byte)0x94, (byte)0x32, (byte)0x7e, (byte)0xd8, (byte)0xe6, (byte)0x40, (byte)0x0c, (byte)0xaa, /* 6*/ (byte)0xc2, (byte)0x64, (byte)0x28, (byte)0x8e, (byte)0xb0, (byte)0x16, (byte)0x5a, (byte)0xfc, (byte)0x26, (byte)0x80, (byte)0xcc, (byte)0x6a, (byte)0x54, (byte)0xf2, (byte)0xbe, (byte)0x18, /* 7*/ (byte)0xac, (byte)0x0a, (byte)0x46, (byte)0xe0, (byte)0xde, (byte)0x78, (byte)0x34, (byte)0x92, (byte)0x48, (byte)0xee, (byte)0xa2, (byte)0x04, (byte)0x3a, (byte)0x9c, (byte)0xd0, (byte)0x76, /* 8*/ (byte)0x3c, (byte)0x9a, (byte)0xd6, (byte)0x70, (byte)0x4e, (byte)0xe8, (byte)0xa4, (byte)0x02, (byte)0xd8, (byte)0x7e, (byte)0x32, (byte)0x94, (byte)0xaa, (byte)0x0c, (byte)0x40, (byte)0xe6, /* 9*/ (byte)0x52, (byte)0xf4, (byte)0xb8, (byte)0x1e, (byte)0x20, (byte)0x86, (byte)0xca, (byte)0x6c, (byte)0xb6, (byte)0x10, (byte)0x5c, (byte)0xfa, (byte)0xc4, (byte)0x62, (byte)0x2e, (byte)0x88, /* A*/ (byte)0xe0, (byte)0x46, (byte)0x0a, (byte)0xac, (byte)0x92, (byte)0x34, (byte)0x78, (byte)0xde, (byte)0x04, (byte)0xa2, (byte)0xee, (byte)0x48, (byte)0x76, (byte)0xd0, (byte)0x9c, (byte)0x3a, /* B*/ (byte)0x8e, (byte)0x28, (byte)0x64, (byte)0xc2, (byte)0xfc, (byte)0x5a, (byte)0x16, (byte)0xb0, (byte)0x6a, (byte)0xcc, (byte)0x80, (byte)0x26, (byte)0x18, (byte)0xbe, (byte)0xf2, (byte)0x54, /* C*/ (byte)0x22, (byte)0x84, (byte)0xc8, (byte)0x6e, (byte)0x50, (byte)0xf6, (byte)0xba, (byte)0x1c, (byte)0xc6, (byte)0x60, (byte)0x2c, (byte)0x8a, (byte)0xb4, (byte)0x12, (byte)0x5e, (byte)0xf8, /* D*/ (byte)0x4c, (byte)0xea, (byte)0xa6, (byte)0x00, (byte)0x3e, (byte)0x98, (byte)0xd4, (byte)0x72, (byte)0xa8, (byte)0x0e, (byte)0x42, (byte)0xe4, (byte)0xda, (byte)0x7c, (byte)0x30, (byte)0x96, /* E*/ (byte)0xfe, (byte)0x58, (byte)0x14, (byte)0xb2, (byte)0x8c, (byte)0x2a, (byte)0x66, (byte)0xc0, (byte)0x1a, (byte)0xbc, (byte)0xf0, (byte)0x56, (byte)0x68, (byte)0xce, (byte)0x82, (byte)0x24, /* F*/ (byte)0x90, (byte)0x36, (byte)0x7a, (byte)0xdc, (byte)0xe2, (byte)0x44, (byte)0x08, (byte)0xae, (byte)0x74, (byte)0xd2, (byte)0x9e, (byte)0x38, (byte)0x06, (byte)0xa0, (byte)0xec, (byte)0x4a }; public Reply sendRequest(final byte order, final byte[] parameter) { if(null == parameter) { return sendRequest(order, parameter, 0, 0); } else { return sendRequest(order, parameter, 0, parameter.length); } } public Reply sendRequest(final int Order, final int[] parameter, int offset, int length) { byte[] para = new byte[length]; for(int i = 0; i < length; i++) { para[i] = (byte)(0xff & parameter[offset + i]); } return sendRequest((byte)(0xff & Order), para, 0, length); } /** sends a request frame to the client. * * @param order The Order byte. * @param parameter the parameter data. May be null ! * @param offset parameter starts at this offset in the buffer. * @param length send only this many bytes. May be 0 ! * @return true= success false = no reply received - timeout */ public Reply sendRequest(final byte Order, final byte[] parameter, int offset, int length) { Reply r = null; int numberOfTransmissions = 0; boolean needsToRetransmitt = false; do { final byte[] buf = new byte[length + 5]; buf[0] = Protocol.START_OF_HOST_FRAME; buf[1] = (byte)(length + 2); // length also includes Control and Order if(false == needsToRetransmitt) { incrementSequenceNumber(); } // else retransmission due to communications error if(false == isFirstOrder) { buf[2] = sequenceNumber; } else { // signal the client that host has reset so hat the client flushes all cached responses buf[2] = (byte)(0x10 | sequenceNumber); isFirstOrder = false; } buf[3] = Order; for(int i = 0; i < length; i++) { buf[4 + i] = parameter[i + offset]; } // log.trace("calculating CRC for : " + Tool.fromByteBufferToHexString(buf, 4 + length)); buf[4 + length] = getCRCfor(buf, 3 + length, 1); try { log.info("Sending Frame: " + Tool.fromByteBufferToHexString(buf)); out.write(buf); numberOfTransmissions++; r = getReply(); } catch (final IOException e) { e.printStackTrace(); log.error("Failed to send Request - Exception !"); return null; } if(false == r.isValid()) { log.error("received invalid Frame ({})!", r); needsToRetransmitt = true; } else { // Transport error -> Retransmission ? if((-1 < r.getReplyCode()) && (Protocol.RESPONSE_OK > r.getReplyCode())) { // Reply codes as defined in Pacemaker Protocol if(Protocol.RESPONSE_FRAME_RECEIPT_ERROR == r.getReplyCode()) { byte[] para = r.getParameter(); switch(para[0]) { case Protocol.RESPONSE_BAD_FRAME: log.error("received Bad Frame error Frame !"); break; case Protocol.RESPONSE_BAD_ERROR_CHECK_CODE: log.error("received bad CRC error Frame !"); break; case Protocol.RESPONSE_UNABLE_TO_ACCEPT_FRAME: log.error("received unable to accept error Frame !"); break; default: log.error("received error Frame with invalid parameter !"); break; } } // new error frames would be here with else if() else { log.error("received invalid error Frame !"); } needsToRetransmitt = true; } else { needsToRetransmitt = false; } } } while((true == needsToRetransmitt) && (numberOfTransmissions < MAX_TRANSMISSIONS)); if(Protocol.RESPONSE_GENERIC_APPLICATION_ERROR == r.getReplyCode()) { // Do some logging - log.error("Generic Application Error : " + r.getParameterAsString(1)); + byte[] para = r.getParameter(); + String type = ""; + switch(para[0]) + { + case Protocol.RESPONSE_UNKNOWN_ORDER: type = "unknown order"; break; + case Protocol.RESPONSE_BAD_PARAMETER_FORMAT: type = "bad parameter format"; break; + case Protocol.RESPONSE_BAD_PARAMETER_VALUE: type = "bad parameter value"; break; + case Protocol.RESPONSE_INVALID_DEVICE_TYPE: type = "wrong device type"; break; + case Protocol.RESPONSE_INVALID_DEVICE_NUMBER: type = "wrong device number"; break; + case Protocol.RESPONSE_INCORRECT_MODE: type = "wrong mode"; break; + case Protocol.RESPONSE_BUSY: type = "busy"; break; + case Protocol.RESPONSE_FAILED: type = "failed"; break; + case Protocol.RESPONSE_FIRMWARE_ERROR: type = "firmware error"; break; + case Protocol.RESPONSE_CANNOT_ACTIVATE_DEVICE: type = "can not activate device"; break; + default: type = "" + (0xff & para[0]); break; + } + log.error("Generic Application Error : " + type + " " + r.getParameterAsString(1)); } return r; } public static byte getCRCfor(final byte[] buf, final int length) { return getCRCfor(buf, length -1, 1/* Byte 0 is Sync and is not included in CRC*/); } public static byte getCRCfor(final byte[] buf, int length, final int offset) { byte crc = 0; int pos = offset; while (length > 0) { crc = crc_array[0xff & (buf[pos] ^ crc)]; pos = pos + 1; length = length - 1; } return crc; } @SuppressWarnings("unused") protected int getAByte() throws IOException, TimeoutException { if(false == useNonBlocking) { final int res = in.read(); if(-1 == res) { throw new IOException("Channel closed"); } log.debug("Received the Byte: " + String.format("%02X", res)); return res; } else { if(1 > in.available()) { int timeoutCounter = 0; do{ try { Thread.sleep(1); } catch(InterruptedException e) { } if(true == isSynced) { timeoutCounter++; if(MAX_MS_BETWEEN_TWO_BYTES < timeoutCounter) { throw new TimeoutException(); } } // else pause between two frames can be as long as it wants to be. }while(1 > in.available()); } // else a byte is already available final int res = in.read(); if(-1 == res) { throw new IOException("Channel closed"); } log.debug("Received the Byte: " + String.format("%02X", res)); return res; } } protected void incrementSequenceNumber() { sequenceNumber ++; if(sequenceNumber > 7) { sequenceNumber = 0; } } protected Reply getReply() { Reply r = null; r = receiveQueue.poll(); if(null != r) { return r; } int timeoutCounter = 0; do{ try { Thread.sleep(1); } catch(InterruptedException e) { } timeoutCounter++; r = receiveQueue.poll(); if((null == r) && (MAX_MS_UNTIL_REPLY_ARRIVES < timeoutCounter)) { log.error("Timeout !"); isFirstOrder = true; return new Reply(null); } }while(null == r); return r; } public void run() { try { while(false == isInterrupted()) { // Sync int sync; do{ try { sync = getAByte(); if((sync != Protocol.START_OF_CLIENT_FRAME) && (true == isSynced)) { // Protocol Error log.error("Frame did not start with sync byte !"); isSynced = false; } else { if(Protocol.START_OF_CLIENT_FRAME == sync) { isSynced = true; } } } catch(TimeoutException e) { isSynced = false; } } while (false == isSynced); log.debug("Synced to client!"); final int replyLength; final int control; final byte reply; final byte[] buf; try { // Length replyLength = getAByte(); if(0 > replyLength) { isSynced = false; continue; } buf = new byte[4 + replyLength]; // Sync, length and CRC are not included in length buf[0] = Protocol.START_OF_CLIENT_FRAME; buf[1] = (byte)(replyLength & 0xff); // Control control = (byte)getAByte(); // check control later buf[2] = (byte)(control & 0xff); // Reply Code reply = (byte)getAByte(); // check reply later buf[3] = reply; // Parameter for(int i = 0; i < replyLength-2;i++) // Control and reply code is also in the length { buf[4 + i] = (byte)getAByte(); // log.traceSystem.out.print(" " + i); } // Error Check Code (CRC-8) buf[2 + replyLength] = (byte)getAByte(); } catch(TimeoutException e) { isSynced = false; isFirstOrder = true; continue; } byte expectedCRC = getCRCfor(buf, replyLength + 2); if(expectedCRC != buf[2 + replyLength]) { log.error("Wrong CRC ! expected : " + String.format("%02X", expectedCRC) + " received : " + String.format("%02X", buf[2 + replyLength])); isSynced = false; continue; } if((control & 0xf) != sequenceNumber) { // debug frames might not always have the correct sequence number. if(Protocol.DEBUG_FLAG == (Protocol.DEBUG_FLAG & control)) { // ok } // if there has been a bit error in the transmission and // the client did not receive the request frame correctly // then it might answer with a wrong reply code, but the // reply will be "bad crc" else if( (Protocol.RESPONSE_FRAME_RECEIPT_ERROR == reply) && (Protocol.RESPONSE_BAD_ERROR_CHECK_CODE == buf[4]) ) { // ok } else { // Protocol Error log.error("Wrong Sequence Number !(Received: {}; Expected: {})", (control & 0xf), sequenceNumber); isSynced = false; continue; } } Reply curReply = new Reply(buf); if(true == curReply.isDebugFrame()) { log.info(curReply.toString()); if(Protocol.RESPONSE_DEBUG_FRAME_NEW_EVENT == curReply.getReplyCode()) { //TODO react to the new event } } else { receiveQueue.put(curReply); } } } catch(InterruptedException ie) { log.info("Has been Interrupted !"); // end the thread } catch (final IOException e) { log.error("Failed to read Reply - Exception !"); e.printStackTrace(); } log.info("Receive Thread stopped !"); } public void close() { this.interrupt(); } }
true
false
null
null
diff --git a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidGraphics.java b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidGraphics.java index 8d7428ced..63e5f9fb6 100644 --- a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidGraphics.java +++ b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidGraphics.java @@ -1,447 +1,447 @@ /******************************************************************************* * Copyright 2010 Mario Zechner ([email protected]) * * 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.badlogic.gdx.backends.android; import java.io.IOException; import java.io.InputStream; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.egl.EGLContext; import javax.microedition.khronos.egl.EGLDisplay; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.opengl.GLSurfaceView.Renderer; import android.view.Display; import android.view.View; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Graphics; import com.badlogic.gdx.RenderListener; import com.badlogic.gdx.backends.android.surfaceview.GLSurfaceView20; import com.badlogic.gdx.backends.android.surfaceview.GLSurfaceViewCupcake; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.GL11; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.GLCommon; import com.badlogic.gdx.graphics.Mesh; import com.badlogic.gdx.graphics.Pixmap; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.Pixmap.Format; import com.badlogic.gdx.graphics.Texture.TextureFilter; import com.badlogic.gdx.graphics.Texture.TextureWrap; import com.badlogic.gdx.graphics.glutils.FrameBuffer; import com.badlogic.gdx.graphics.glutils.ShaderProgram; import com.badlogic.gdx.math.WindowedMean; import com.badlogic.gdx.utils.GdxRuntimeException; /** * An implementation of {@link Graphics} for Android. * * @author mzechner */ final class AndroidGraphics implements Graphics, Renderer { /** * the gl surfaceview * */ protected final View view; /** * the android input we have to call * */ private AndroidInput input; /** * the render listener * */ protected RenderListener listener; /** * width & height of the surface * */ protected int width; protected int height; /** * the app * */ protected AndroidApplication app; /** * Common instance */ protected GLCommon gl; /** * the GL10 instance * */ protected GL10 gl10; /** * the GL11 instance * */ protected GL11 gl11; /** * the GL20 instance * */ protected GL20 gl20; /** * the last frame time * */ private long lastFrameTime = System.nanoTime(); /** * the deltaTime * */ private float deltaTime = 0; /** * frame start time * */ private long frameStart = System.nanoTime(); /** * frame counter * */ private int frames = 0; /** * last fps * */ private int fps; /** * the deltaTime mean * */ private WindowedMean mean = new WindowedMean(5); /** * whether to dispose the render listeners * */ private boolean dispose = false; public AndroidGraphics (AndroidApplication activity, boolean useGL2IfAvailable) { view = createGLSurfaceView(activity, useGL2IfAvailable); this.app = activity; } private View createGLSurfaceView (Activity activity, boolean useGL2) { if (useGL2 && checkGL20()) { GLSurfaceView20 view = new GLSurfaceView20(activity); view.setRenderer(this); return view; } else { if (Integer.parseInt(android.os.Build.VERSION.SDK) <= 4) { GLSurfaceViewCupcake view = new GLSurfaceViewCupcake(activity); view.setRenderer(this); return view; } else { android.opengl.GLSurfaceView view = new android.opengl.GLSurfaceView(activity); view.setRenderer(this); return view; } } } /** * This is a hack... * * @param input */ protected void setInput (AndroidInput input) { this.input = input; } private boolean checkGL20 () { EGL10 egl = (EGL10)EGLContext.getEGL(); EGLDisplay display = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY); int[] version = new int[2]; egl.eglInitialize(display, version); int EGL_OPENGL_ES2_BIT = 4; int[] configAttribs = {EGL10.EGL_RED_SIZE, 4, EGL10.EGL_GREEN_SIZE, 4, EGL10.EGL_BLUE_SIZE, 4, EGL10.EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, EGL10.EGL_NONE}; EGLConfig[] configs = new EGLConfig[10]; int[] num_config = new int[1]; egl.eglChooseConfig(display, configAttribs, configs, 10, num_config); egl.eglTerminate(display); return num_config[0] > 0; } /** * {@inheritDoc} */ @Override public GL10 getGL10 () { return gl10; } /** * {@inheritDoc} */ @Override public GL11 getGL11 () { return gl11; } /** * {@inheritDoc} */ @Override public GL20 getGL20 () { return gl20; } /** * {@inheritDoc} */ @Override public int getHeight () { return height; } /** * {@inheritDoc} */ @Override public int getWidth () { return width; } /** * {@inheritDoc} */ @Override public boolean isGL11Available () { return gl11 != null; } /** * {@inheritDoc} */ @Override public boolean isGL20Available () { return gl20 != null; } private static boolean isPowerOfTwo (int value) { return ((value != 0) && (value & (value - 1)) == 0); } /** * {@inheritDoc} */ @Override public Pixmap newPixmap (int width, int height, Format format) { return new AndroidPixmap(width, height, format); } /** * {@inheritDoc} */ @Override public Pixmap newPixmap (InputStream in) { Bitmap bitmap = BitmapFactory.decodeStream(in); if (bitmap == null) throw new GdxRuntimeException("Couldn't load Pixmap from InputStream"); return new AndroidPixmap(bitmap); } /** * {@inheritDoc} */ @Override public Pixmap newPixmap (FileHandle file) { return newPixmap(file.getInputStream()); } /** * {@inheritDoc} */ @Override public Pixmap newPixmap (Object nativePixmap) { return new AndroidPixmap((Bitmap)nativePixmap); } /** * {@inheritDoc} */ @Override public void setRenderListener (RenderListener listener) { synchronized (this) { if (this.listener != null) this.listener.dispose(); this.listener = listener; } } @Override public void onDrawFrame (javax.microedition.khronos.opengles.GL10 gl) { // calculate delta time deltaTime = (System.nanoTime() - lastFrameTime) / 1000000000.0f; lastFrameTime = System.nanoTime(); mean.addValue(deltaTime); // this is a hack so the events get processed synchronously. if (input != null) input.update(); synchronized (this) { if (listener != null) listener.render(); } if (dispose) { if (listener != null) listener.dispose(); listener = null; dispose = false; } if (System.nanoTime() - frameStart > 1000000000) { fps = frames; frames = 0; frameStart = System.nanoTime(); } frames++; } /** * This instantiates the GL10, GL11 and GL20 instances. Includes the check for certain devices that pretend to support GL11 but * fuck up vertex buffer objects. This includes the pixelflinger which segfaults when buffers are deleted as well as the * Motorola CLIQ and the Samsung Behold II. * * @param gl */ private void setupGL (javax.microedition.khronos.opengles.GL10 gl) { if (gl10 != null || gl20 != null) return; if (view instanceof GLSurfaceView20) { gl20 = new AndroidGL20(); this.gl = gl20; } else { gl10 = new AndroidGL10(gl); this.gl = gl10; if (gl instanceof javax.microedition.khronos.opengles.GL11) { String renderer = gl.glGetString(GL10.GL_RENDERER); - if (renderer.toLowerCase().contains("pixelflinger")) return; - - if (android.os.Build.MODEL.equals("MB200") || android.os.Build.MODEL.equals("MB220") - || android.os.Build.MODEL.contains("Behold")) return; + if (!renderer.toLowerCase().contains("pixelflinger") && + !(android.os.Build.MODEL.equals("MB200") || android.os.Build.MODEL.equals("MB220") + || android.os.Build.MODEL.contains("Behold"))) { gl11 = new AndroidGL11((javax.microedition.khronos.opengles.GL11)gl); gl10 = gl11; + } } } - + Gdx.gl = this.gl; Gdx.gl10 = gl10; Gdx.gl11 = gl11; Gdx.gl20 = gl20; } @Override public void onSurfaceChanged (javax.microedition.khronos.opengles.GL10 gl, int width, int height) { this.width = width; this.height = height; if (listener != null) listener.surfaceChanged(width, height); } @Override public void onSurfaceCreated (javax.microedition.khronos.opengles.GL10 gl, EGLConfig config) { setupGL(gl); Mesh.invalidateAllMeshes(); AndroidTexture.invalidateAllTextures(); ShaderProgram.invalidateAllShaderPrograms(); FrameBuffer.invalidateAllFrameBuffers(); Display display = app.getWindowManager().getDefaultDisplay(); this.width = display.getWidth(); this.height = display.getHeight(); if (listener != null) listener.surfaceCreated(); mean = new WindowedMean(5); this.lastFrameTime = System.nanoTime(); gl.glViewport(0, 0, this.width, this.height); } /** * {@inheritDoc} */ @Override public float getDeltaTime () { return mean.getMean() == 0 ? deltaTime : mean.getMean(); } public void disposeRenderListener () { dispose = true; while (dispose) { try { Thread.sleep(20); } catch (InterruptedException e) { } } } /** * {@inheritDoc} */ @Override public GraphicsType getType () { return GraphicsType.AndroidGL; } /** * {@inheritDoc} */ @Override public int getFramesPerSecond () { return fps; } @Override public Texture newUnmanagedTexture (int width, int height, Format format, TextureFilter minFilter, TextureFilter magFilter, TextureWrap uWrap, TextureWrap vWrap) { if (!isPowerOfTwo(width) || !isPowerOfTwo(height)) throw new GdxRuntimeException("Dimensions have to be a power of two"); Bitmap.Config config = AndroidPixmap.getInternalFormat(format); Bitmap bitmap = Bitmap.createBitmap(width, height, config); Texture texture = null; texture = new AndroidTexture(this, bitmap, minFilter, magFilter, uWrap, vWrap, false, null); bitmap.recycle(); return texture; } @Override public Texture newUnmanagedTexture (Pixmap pixmap, TextureFilter minFilter, TextureFilter magFilter, TextureWrap uWrap, TextureWrap vWrap) { if (!isPowerOfTwo(pixmap.getWidth()) || !isPowerOfTwo(pixmap.getHeight())) throw new GdxRuntimeException("Dimensions have to be a power of two"); return new AndroidTexture(this, (Bitmap)pixmap.getNativePixmap(), minFilter, magFilter, uWrap, vWrap, false, null); } @Override public Texture newTexture (FileHandle file, TextureFilter minFilter, TextureFilter magFilter, TextureWrap uWrap, TextureWrap vWrap) { return new AndroidTexture(this, (Bitmap)null, minFilter, magFilter, uWrap, vWrap, true, file); } public void clearManagedCaches () { Mesh.clearAllMeshes(); AndroidTexture.clearAllTextures(); ShaderProgram.clearAllShaderPrograms(); FrameBuffer.clearAllFrameBuffers(); } /** * @return the GLSurfaceView */ public View getView () { return view; } /** * {@inheritDoc} */ @Override public GLCommon getGLCommon () { return gl; } }
false
false
null
null
diff --git a/modules/org.restlet/src/org/restlet/engine/util/Base64.java b/modules/org.restlet/src/org/restlet/engine/util/Base64.java index f54186bee..da5770f3b 100644 --- a/modules/org.restlet/src/org/restlet/engine/util/Base64.java +++ b/modules/org.restlet/src/org/restlet/engine/util/Base64.java @@ -1,286 +1,288 @@ /** * Copyright 2005-2011 Noelios Technologies. * * The contents of this file are subject to the terms of one of the following * open source licenses: LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL 1.0 (the * "Licenses"). You can select the license that you prefer but you may not use * this file except in compliance with one of these Licenses. * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0.html * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1.php * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1.php * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0.php * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.noelios.com/products/restlet-engine * * Restlet is a registered trademark of Noelios Technologies. */ package org.restlet.engine.util; import java.util.Arrays; import org.restlet.engine.io.BioUtils; /** * Minimal but fast Base64 codec. * * @author Ray Waldin ([email protected]) */ public class Base64 { /** alphabet used for encoding bytes into base64 */ private static final char[] BASE64_DIGITS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" .toCharArray(); /** * Decoding involves replacing each character with the character's value, or * position, from the above alphabet, and this table makes such lookups * quick and easy. Couldn't help myself with the corny name :) */ private static final byte[] DECODER_RING = new byte[128]; /** * Initializes the decoder ring. */ static { Arrays.fill(DECODER_RING, (byte) -1); int i = 0; for (final char c : BASE64_DIGITS) { DECODER_RING[c] = (byte) i++; } DECODER_RING['='] = 0; } private final static int byteAt(byte[] data, int block, int off) { return unsign(data[(block * 3) + off]); } /** * Decodes base64 characters into bytes. Newline characters found at block * boundaries will be ignored. * * @param chars * The characters array to decode. * @return The decoded byte array. */ public static byte[] decode(final char[] chars) { // prepare to ignore newline chars int newlineCount = 0; for (char c : chars) { switch (c) { case '\r': case '\n': newlineCount++; break; default: } } int len = chars.length - newlineCount; if (len % 4 != 0) { throw new IllegalArgumentException( "Base64.decode() requires input length to be a multiple of 4"); } int numBytes = ((len + 3) / 4) * 3; // fix up length relative to padding if (len > 1) { if (chars[chars.length - 2] == '=') { numBytes -= 2; } else if (chars[chars.length - 1] == '=') { numBytes--; } } byte[] result = new byte[numBytes]; int newlineOffset = 0; // decode each block of 4 chars into 3 bytes for (int i = 0; i < (len + 3) / 4; ++i) { int charOffset = newlineOffset + (i * 4); final char c1 = chars[charOffset++]; final char c2 = chars[charOffset++]; final char c3 = chars[charOffset++]; final char c4 = chars[charOffset++]; if (!(validChar(c1) && validChar(c2) && validChar(c3) && validChar(c4))) { throw new IllegalArgumentException( "Invalid Base64 character in block: '" + c1 + c2 + c3 + c4 + "'"); } // pack final int x = DECODER_RING[c1] << 18 | DECODER_RING[c2] << 12 | (c3 == '=' ? 0 : DECODER_RING[c3] << 6) | (c4 == '=' ? 0 : DECODER_RING[c4]); // unpack int byteOffset = i * 3; result[byteOffset++] = (byte) (x >> 16); if (c3 != '=') { result[byteOffset++] = (byte) ((x >> 8) & 0xFF); if (c4 != '=') { result[byteOffset++] = (byte) (x & 0xFF); } } // skip newlines after block outer: while (chars.length > charOffset) { switch (chars[charOffset++]) { case '\r': case '\n': newlineOffset++; break; default: break outer; } } } return result; }; /** * Decodes a base64 string into bytes. Newline characters found at block * boundaries will be ignored. * * @param encodedString * The string to decode. * @return The decoded byte array. */ public static byte[] decode(String encodedString) { return decode(encodedString.toCharArray()); } /** * Encodes an entire byte array into a Base64 string, with optional newlines * after every 76 characters. * * @param bytes * The byte array to encode. * @param newlines * Indicates whether or not newlines are desired. * @return The encoded string. */ public static String encode(byte[] bytes, boolean newlines) { return encode(bytes, 0, bytes.length, newlines); } /** * Encodes specified bytes into a Base64 string, with optional newlines * after every 76 characters. * * @param bytes * The byte array to encode. * @param off * The starting offset. * @param len * The number of bytes to encode. * @param newlines * Indicates whether or not newlines are desired. * * @return The encoded string. */ public static String encode(byte[] bytes, int off, int len, boolean newlines) { final char[] output = new char[(((len + 2) / 3) * 4) + (newlines ? len / 43 : 0)]; int pos = 0; // encode each block of 3 bytes into 4 chars for (int i = 0; i < (len + 2) / 3; ++i) { int pad = 0; if (len + 1 < (i + 1) * 3) { // two trailing '='s pad = 2; } else if (len < (i + 1) * 3) { // one trailing '=' pad = 1; } // pack final int x = (byteAt(bytes, i, off) << 16) | (pad > 1 ? 0 : (byteAt(bytes, i, off + 1) << 8)) | (pad > 0 ? 0 : (byteAt(bytes, i, off + 2))); // unpack output[pos++] = BASE64_DIGITS[x >> 18]; output[pos++] = BASE64_DIGITS[(x >> 12) & 0x3F]; output[pos++] = pad > 1 ? '=' : BASE64_DIGITS[(x >> 6) & 0x3F]; output[pos++] = pad > 0 ? '=' : BASE64_DIGITS[x & 0x3F]; if (newlines && ((i + 1) % 19 == 0)) { output[pos++] = '\n'; } } return new String(output, 0, pos); } + // [ifndef gwt] method /** * Encodes an entire chars array into a Base64 string, with optional * newlines after every 76 characters. * * @param chars * The characters array to encode. * @param newlines * Indicates whether or not newlines are desired. * @return The encoded string. */ public static String encode(char[] chars, boolean newlines) { return encode(BioUtils.toByteArray(chars), newlines); } + // [ifndef gwt] method /** * Encodes an entire chars array into a Base64 string, with optional * newlines after every 76 characters. * * @param chars * The characters array to encode. * @param charset * The character set to use for the character to byte conversion. * @param newlines * Indicates whether or not newlines are desired. * @return The encoded string. */ public static String encode(char[] chars, String charset, boolean newlines) { return encode(BioUtils.toByteArray(chars, charset), newlines); } /** * Computes the unsigned value of a byte. * * @param b * The input byte. * @return The output unsigned value. */ private final static int unsign(byte b) { return b < 0 ? b + 256 : b; } /** * Indicates if the character is valid and can be decoded. * * @param c * The input character. * @return True if the character is valid. */ private final static boolean validChar(char c) { return (c < 128) && (DECODER_RING[c] != -1); } }
false
false
null
null
diff --git a/UnicodeModul.java b/UnicodeModul.java index 97d578d..2685dd9 100644 --- a/UnicodeModul.java +++ b/UnicodeModul.java @@ -1,117 +1,117 @@ import java.io.*; import java.util.Formatter; /** * <p>This program converts the file <a href="http://unicode.org/Public/UNIDATA/UnicodeData.txt">UnicodeData.txt</a> (you should always download it yourself to get the latest version) into a file {@code unicode.module} (containing fitting compose definitions for a linux system).</p> * * <p>You can download the <a href="http://github.com/zephyr/java-compose-creator/">lastest version of this program</a> at GitHub.</p> * * <p>Copyright (C) 2009, 2010 Dennis Heidsiek</p> * * <p>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.</p> * * <p>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.</p> * * <p>You should have received a copy of the GNU General Public License along with this program; if not, see <a href="http://www.gnu.org/licenses/">http://www.gnu.org/licenses/<a>.</p> */ public class UnicodeModul { /** * Converts the given unicode codepoint to a String only containing the according character. */ protected static String unicode(int cp) { return new String(Character.toChars(cp)); } /** * Returns the length of val as string in the given base. * @param val >= 0 - * @param base > 0 + * @param base >= 2 */ protected static int length(int val, int base) { return 1 + (int) (Math.log(val) / Math.log(base)); } /** * Returns the digits of val in the given base. * @param val >= 0 - * @param base > 0 + * @param base >= 2 */ protected static int[] toBase(int val, int base) { if(val==0) return new int[]{0}; int l = length(val, base); int[] res = new int[l]; int pos=l-1; do { res[pos] = val % base; pos--; val/=base; } while(val>0); return res; } /** * @param a single filename (default is UnicodeData.txt) */ public static void main(String[] args) throws Exception { long nanotime = System.nanoTime(); String filename = (args.length == 0) ? "UnicodeData.txt" : args[0]; System.out.format("Usage: CreateUnicodeModule [file-to-parse -- default: UnicodeData.txt]%nThis program is free software (GNU GPL 3+).%n"); BufferedReader in = new BufferedReader(new FileReader(filename)); Formatter f = new Formatter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream("unicode.module"), "UTF-8"))); try { f.format("#configinfo Alle Unicode-Zeichen, 0-10FFFD (uu17f%s%s)%n", unicode(0x2192), unicode(0x17F)); f.format("#%n"); f.format("# This is a autogenerated list of all unicode codepoints (uu0-uu10FFFD),"); f.format("# suitable for appending to the ~/.XCompose file of a GNU/Linux OS.%n"); f.format("#%n"); f.format("# Please dont't change it by hand; instead, look at the Source code:"); f.format("# http://github.com/zephyr/java-compose-creator/"); f.format("#%n"); f.format("# Based on the file: %s%n", filename); f.format("# Author: Dennis Heidsiek%n"); f.format("# Licence (short name): CC-BY-SA 3.0 DE%n"); f.format("# Licence (full name): Creative Commons Namensnennung-Weitergabe unter gleichen Bedingungen 3.0 Deutschland%n"); f.format("# Licence-URL: http://creativecommons.org/licenses/by-sa/3.0/de/%n"); f.format("%n%n"); String line; while((line = in.readLine()) != null) { String[] l = line.split(";"); int cp = Integer.parseInt(l[0], 16); String des = l[1]; if(des.equals("<control>")) { continue; } f.format("<Multi_key> <u> <u>"); for(int d : toBase(cp, 16)) { f.format(" <%c>", d<10 ? ('0'+d) : ('a'+d-10)); } String out = unicode(cp); if(out.equals("\"")) out = "\\\""; if(out.equals("\\")) out = "\\\\"; f.format( " <space> : \"%s\" U%0"+Math.max(4, length(cp,16))+"x # %s%n", out, cp, des ); } } finally { in.close(); f.close(); // Time brenchmark: nanotime = System.nanoTime() - nanotime; System.out.format("Program finished. Time elapsed: %s nano seconds. By your command!%n", nanotime); } } }
false
false
null
null
diff --git a/sculptor-generator/sculptor-generator-core/src/main/java/org/sculptor/generator/util/DbHelperBase.java b/sculptor-generator/sculptor-generator-core/src/main/java/org/sculptor/generator/util/DbHelperBase.java index 8bea55df..93be2199 100644 --- a/sculptor-generator/sculptor-generator-core/src/main/java/org/sculptor/generator/util/DbHelperBase.java +++ b/sculptor-generator/sculptor-generator-core/src/main/java/org/sculptor/generator/util/DbHelperBase.java @@ -1,696 +1,696 @@ /* * Copyright 2007 The Fornax Project Team, including 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.sculptor.generator.util; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.inject.Inject; import sculptormetamodel.Application; import sculptormetamodel.Attribute; import sculptormetamodel.BasicType; import sculptormetamodel.DomainObject; import sculptormetamodel.Entity; import sculptormetamodel.Enum; import sculptormetamodel.EnumConstructorParameter; import sculptormetamodel.EnumValue; import sculptormetamodel.Inheritance; import sculptormetamodel.Module; import sculptormetamodel.NamedElement; import sculptormetamodel.Reference; import sculptormetamodel.SculptormetamodelFactory; import sculptormetamodel.impl.SculptormetamodelFactoryImpl; public class DbHelperBase { private static final String ID_ATTRIBUTE_NAME = "id"; @Inject private HelperBase helperBase; @Inject private PropertiesBase propBase; @Inject private SingularPluralConverter singularPluralConverter; public List<DomainObject> getDomainObjectsInCreateOrder(Application application, Boolean ascending) { List<DomainObject> all = getAllDomainObjects(application); List<DomainObject> orderedClasses = new ArrayList<DomainObject>(); Set<DomainObject> handledClasses = new HashSet<DomainObject>(); for (DomainObject domainObject : all) { addClassRecursive(domainObject, orderedClasses, handledClasses); } if (!ascending) { Collections.reverse(orderedClasses); } return orderedClasses; } /** * @return all persistent DomainObjects */ public List<DomainObject> getAllDomainObjects(Application application) { List<DomainObject> all = new ArrayList<DomainObject>(); List<Module> modules = HelperBase.sortByName(application.getModules()); for (Module m : modules) { if (m.isExternal()) { continue; } List<DomainObject> domainObjects = HelperBase.sortByName(m.getDomainObjects()); for (DomainObject d : domainObjects) { if (helperBase.isPersistent(d) && includeInDdl(d)) { all.add(d); } } } return all; } private boolean includeInDdl(DomainObject domainObj) { return !helperBase.hasHintImpl(domainObj.getHint(), "skipddl"); } private void addClassRecursive(DomainObject domainObject, List<DomainObject> orderedClasses, Set<DomainObject> handledClasses) { if (handledClasses.contains(domainObject)) { // already added return; } if (domainObject instanceof BasicType) { // no tables for BasicType return; } if (!helperBase.isPersistent(domainObject) || !includeInDdl(domainObject)) { // no tables for non persistent ValueObject return; } if (domainObject.getModule().isExternal()) { return; } // add current class, will break recursion if referred again handledClasses.add(domainObject); // we must have the referenced super class first, due to foreign key if (domainObject.getExtends() != null) { addClassRecursive(domainObject.getExtends(), orderedClasses, handledClasses); } // we must have the referenced classes first, due to foreign keys for (Reference ref : getAllOneReferences(domainObject)) { addClassRecursive(ref.getTo(), orderedClasses, handledClasses); } if (!orderedClasses.contains(domainObject)) { orderedClasses.add(domainObject); } } public String getDiscriminatorColumnDatabaseType(Inheritance inheritance) { // create an Attribute so that we can reuse existing logic for // databaseType SculptormetamodelFactory factory = SculptormetamodelFactoryImpl.eINSTANCE; Attribute attr = factory.createAttribute(); if (inheritance.getDiscriminatorColumnName() == null) { attr.setName(propBase.getProperty("db.discriminatorColumnName")); } else { attr.setName(inheritance.getDiscriminatorColumnName()); } attr.setType("discriminatorType." + inheritance.getDiscriminatorType().getLiteral()); if (inheritance.getDiscriminatorColumnLength() != null) { attr.setLength(inheritance.getDiscriminatorColumnLength()); } return getDatabaseType(attr); } public String getDatabaseType(Attribute attribute) { String databaseTypeProperty = attribute.getDatabaseType(); String databaseType; if (databaseTypeProperty == null) { databaseType = getDefaultDbType(attribute.getType()); } else { databaseType = databaseTypeProperty; } String length = getDatabaseLength(attribute); if (length != null && databaseType.indexOf('(') == -1) { databaseType += ("(" + length + ")"); } return databaseType; } public String getEnumDatabaseType(Reference reference) { Attribute enumAttribute = getEnumAttribute((Enum) reference.getTo()); if (helperBase.hasHintImpl(reference.getHint(), "databaseLength")) enumAttribute.setLength(helperBase.getHintImpl(reference.getHint(), "databaseLength")); return getDatabaseType(enumAttribute); } public String getEnumDatabaseType(Enum _enum) { return getDatabaseType(getEnumAttribute(_enum)); } public String getEnumType(Enum _enum) { return getEnumAttribute(_enum).getType(); } public String getEnumDatabaseLength(Enum _enum) { return getEnumAttribute(_enum).getLength(); } private Attribute getEnumKeyAttribute(Enum _enum) { List<Attribute> enumAttributes = _enum.getAttributes(); for (Attribute attribute : enumAttributes) { if (attribute.isNaturalKey()) { return attribute; } } return createDefaultEnumAttribute(); } private Attribute createDefaultEnumAttribute() { SculptormetamodelFactory factory = SculptormetamodelFactoryImpl.eINSTANCE; Attribute attr = factory.createAttribute(); attr.setType("String"); return attr; } private boolean hasNaturalKeyAttribute(Enum _enum) { return (getEnumKeyAttribute(_enum).isNaturalKey()); } private Attribute getEnumAttribute(Enum _enum) { Attribute attribute = getEnumKeyAttribute(_enum); if (_enum.isOrdinal()) { attribute.setType("int"); attribute.setLength(null); } else { if (helperBase.hasHintImpl(_enum.getHint(), "databaseLength")) { attribute.setType("String"); attribute.setLength(helperBase.getHintImpl(_enum.getHint(), "databaseLength")); } else { attribute.setType("String"); attribute.setLength(calcEnumDatabaseLength(_enum)); } } return attribute; } private String calcEnumDatabaseLength(Enum _enum) { int maxLength = 0; if (hasNaturalKeyAttribute(_enum)) { int attributePosition = 0; for (Attribute attribute : (List<Attribute>) _enum.getAttributes()) { if (attribute.isNaturalKey()) { for (EnumValue enumValue : (List<EnumValue>) _enum.getValues()) { EnumConstructorParameter enumParam = (EnumConstructorParameter) enumValue.getParameters().get( attributePosition); maxLength = calcMaxLength(enumParam.getValue(), maxLength); } break; } attributePosition++; } } if (maxLength == 0) { for (EnumValue value : (List<EnumValue>) _enum.getValues()) { maxLength = calcMaxLength(value.getName(), maxLength); } } return "" + maxLength; } private int calcMaxLength(String value, int maxLength) { int length = value.length(); if (value.startsWith("\"")) { length = length - 2; } return (maxLength < length) ? length : maxLength; } public String getDatabaseTypeNullability(Attribute attribute) { if (!attribute.isNullable() || attribute.isNaturalKey()) { return " NOT NULL"; } return ""; } public String getDatabaseTypeNullability(Reference reference) { if (!reference.isNullable() || reference.isNaturalKey()) { return " NOT NULL"; } return ""; } public String getDatabaseLength(Attribute attribute) { if (attribute.getLength() == null) { return getDefaultDbLength(attribute.getType()); } else { return attribute.getLength(); } } private String getDefaultDbType(String javaType) { return propBase.getDbType(javaType); } private String getDefaultDbLength(String javaType) { return propBase.getDbLength(javaType); } - public String getDatabaseName(NamedElement element) { + public String getDatabaseNameBase(NamedElement element) { String name = element.getName(); name = convertDatabaseName(name); return name; } private String convertDatabaseName(String name) { if (propBase.getBooleanProperty("db.useUnderscoreNaming")) { name = CamelCaseConverter.camelCaseToUnderscore(name); } name = truncateLongDatabaseName(name); name = name.toUpperCase(); return name; } public String truncateLongDatabaseName(String name) { int max = propBase.getMaxDbName(); return truncateLongDatabaseName(name, max); } public String truncateLongDatabaseName(String name, Integer max) { if (name.length() <= max) { return name; // no problem } else if (propBase.getBooleanProperty("db.errorWhenTooLongName")) { throw new RuntimeException("Generation aborted due to too long database name: " + name); } else { String hash = String.valueOf(Math.abs(name.hashCode())); hash = "0" + hash; // make sure that it is at least 2 chars hash = hash.substring(hash.length() - 2); // use 2 last characters String truncated = name.substring(0, max - hash.length()) + hash; return truncated; } } public String getDefaultForeignKeyNameBase(Reference ref) { String name; if (ref.isMany()) { name = singularPluralConverter.toSingular(ref.getName()); } else { name = ref.getName(); } DomainObject to = ref.getTo(); name += idSuffix(name, to); return convertDatabaseName(name); } public String getDefaultOppositeForeignKeyName(Reference ref) { if (ref.getOpposite() == null) { return getForeignKeyNameForUnidirectionalToManyWithJoinTable(ref); } else { return getDefaultForeignKeyNameBase(ref.getOpposite()); } } private String getForeignKeyNameForUnidirectionalToManyWithJoinTable(Reference ref) { if (ref.getDatabaseJoinColumn() != null) { return ref.getDatabaseJoinColumn(); } DomainObject from = ref.getFrom(); String name = from.getDatabaseTable(); if (name == null) { name = from.getName(); } name += idSuffix(name, from); return convertDatabaseName(name); } public String getExtendsForeignKeyName(DomainObject extendedClass) { Attribute idAttribute = getIdAttribute(extendedClass); checkIdAttribute(extendedClass, idAttribute); String name = extendedClass.getDatabaseTable(); name += idSuffix(name, extendedClass); return name; } private String idSuffix(String name, DomainObject to) { if (useIdSuffixInForeignKey()) { Attribute idAttribute = getIdAttribute(to); if (idAttribute != null) { String idName = idAttribute.getDatabaseColumn().toUpperCase(); String convertedName = convertDatabaseName(name); if (idName.equals(convertedName) && idName.startsWith(to.getDatabaseTable())) { idName = idName.substring(to.getDatabaseTable().length()); } else if (idName.startsWith(convertedName)) { idName = idName.substring(convertedName.length()); } if (idName.startsWith("_")) { return idName; } else { return ("_" + idName); } } } return ""; } private boolean useIdSuffixInForeignKey() { return propBase.getBooleanProperty("db.useIdSuffixInForeigKey"); } public Attribute getIdAttribute(DomainObject domainObject) { Attribute idAttribute = getAttributeWithName(ID_ATTRIBUTE_NAME, domainObject); if ((idAttribute == null) && (domainObject.getExtends() != null)) { // look in extended DomainOject, recursive call idAttribute = getIdAttribute(domainObject.getExtends()); } return idAttribute; } private Attribute getAttributeWithName(String name, DomainObject domainObject) { for (Object obj : domainObject.getAttributes()) { Attribute attribute = (Attribute) obj; if (attribute.getName().equals(name)) { return attribute; } } // not found return null; } public String getForeignKeyType(Reference ref) { DomainObject referencedClass = ref.getTo(); return getForeignKeyType(referencedClass) + getDatabaseTypeNullability(ref); } public String getForeignKeyType(DomainObject referencedClass) { Attribute idAttribute = getIdAttribute(referencedClass); checkIdAttribute(referencedClass, idAttribute); String type = getDatabaseType(idAttribute); return type; } private void checkIdAttribute(DomainObject referencedClass, Attribute idAttribute) { if (idAttribute == null) { throw new IllegalArgumentException("Referenced class " + referencedClass.getName() + " doesn't contain 'id' attribute"); } } public List<DomainObject> resolveManyToManyRelations(Application application, Boolean ascending) { // first, find all many-to-many references Set<Reference> manyToManyReferences = new HashSet<Reference>(); List<DomainObject> domainObjects = getAllDomainObjects(application); for (DomainObject domainObject : domainObjects) { for (Reference ref : getAllManyReferences(domainObject)) { if (!helperBase.isPersistent(ref.getTo()) || !includeInDdl(ref.getTo())) { // skip this reference, since it refers to a non persistent // object continue; } if (ref.isTransient()) { // skip this reference, since it is transient continue; } Reference opposite = ref.getOpposite(); // undirectional many references are designed in db as // many-to-many, except when inverse is defined to true if ((opposite == null && !ref.isInverse()) || (opposite != null && opposite.isMany() && !opposite.isTransient() && !manyToManyReferences .contains(opposite))) { manyToManyReferences.add(ref); } } } // then, create an fictive DomainObject for each many-to-many reference List<DomainObject> manyToManyClasses = new ArrayList<DomainObject>(); for (Reference ref : manyToManyReferences) { DomainObject relObj = createFictiveManyToManyObject(ref); manyToManyClasses.add(relObj); } manyToManyClasses = HelperBase.sortByName(manyToManyClasses); if (!ascending) { Collections.reverse(manyToManyClasses); } return manyToManyClasses; } public DomainObject createFictiveManyToManyObject(Reference ref) { DomainObject relObj; if (ref.getFrom() instanceof Entity || ref.getTo() instanceof Entity) { relObj = SculptormetamodelFactory.eINSTANCE.createEntity(); } else { // many-to-many between two value objects is not likely (good // design) but whatever... relObj = SculptormetamodelFactory.eINSTANCE.createValueObject(); } String name = getManyToManyJoinTableName(ref); relObj.setName(name.toUpperCase()); - relObj.setDatabaseTable(getDatabaseName(relObj)); + relObj.setDatabaseTable(getDatabaseNameBase(relObj)); relObj.setAbstract(true); Reference ref1 = SculptormetamodelFactory.eINSTANCE.createReference(); ref1.setTo(ref.getTo()); ref1.setName(singularPluralConverter.toSingular(ref.getName())); ref1.setDatabaseColumn(ref.getDatabaseColumn()); ref1.setFrom(relObj); relObj.getReferences().add(ref1); Reference ref2 = SculptormetamodelFactory.eINSTANCE.createReference(); ref2.setTo(ref.getFrom()); if (ref.getOpposite() == null) { // use table name of from obj, it doesn't matter that we loose // upper/lower case ref2.setName(helperBase.toFirstLower(ref.getFrom().getName())); ref2.setDatabaseColumn(getForeignKeyNameForUnidirectionalToManyWithJoinTable(ref)); } else { ref2.setName(singularPluralConverter.toSingular(ref.getOpposite().getName())); ref2.setDatabaseColumn(ref.getOpposite().getDatabaseColumn()); } ref2.setFrom(relObj); relObj.getReferences().add(ref2); String tablespaceHint = helperBase.getHintImpl(ref.getFrom().getHint(), "tablespace"); if (tablespaceHint != null) { helperBase.addHint(relObj, "tablespace=" + tablespaceHint); } return relObj; } public String getManyToManyJoinTableName(Reference ref) { if (ref.getDatabaseJoinTable() != null) { return ref.getDatabaseJoinTable(); } if (ref.getOpposite() != null && ref.getOpposite().getDatabaseJoinTable() != null) { return ref.getOpposite().getDatabaseJoinTable(); } String name1 = ref.getDatabaseColumn(); name1 = removeIdSuffix(name1, ref.getTo()); String name2; if (ref.getOpposite() == null) { name2 = (ref.getFrom().getDatabaseTable() != null) ? ref.getFrom().getDatabaseTable() : ref.getFrom().getName() .toUpperCase(); } else { name2 = ref.getOpposite().getDatabaseColumn(); name2 = removeIdSuffix(name2, ref.getOpposite().getTo()); } return getJoinTableName(name1, name2, true); } public String getElementCollectionTableName(Attribute attribute) { String hintParam = "databaseJoinTableName"; if (helperBase.hasHintImpl(attribute.getHint(), hintParam)) { return helperBase.getHintImpl(attribute.getHint(), hintParam); } String name1 = singularPluralConverter.toSingular(attribute.getDatabaseColumn().toLowerCase()).toUpperCase(); String name2 = ((DomainObject) attribute.eContainer()).getDatabaseTable(); return getJoinTableName(name1, name2, false); } public String getElementCollectionTableName(Reference reference) { if (reference.getDatabaseJoinTable() != null) { return reference.getDatabaseJoinTable(); } String name1 = reference.getDatabaseColumn(); name1 = removeIdSuffix(name1, reference.getTo()); String name2; if (reference.getOpposite() == null) { name2 = (reference.getFrom().getDatabaseTable() != null) ? reference.getFrom().getDatabaseTable() : reference.getFrom() .getName().toUpperCase(); } else { name2 = reference.getOpposite().getDatabaseColumn(); name2 = removeIdSuffix(name2, reference.getOpposite().getTo()); } return getJoinTableName(name1, name2, false); } private String getJoinTableName(String name1, String name2, boolean ordered) { int max = propBase.getMaxDbName(); if ((name1.length() > (max - 6)) && (name2.length() > (max - 6))) { // both names are long, truncate both name1 = name1.substring(0, (max / 2)); name2 = name2.substring(0, (max / 2)); } if ((name1.length() + name2.length() + 1) > max) { // too long, truncate the longest name if (name1.length() > name2.length()) { name1 = name1.substring(0, (max - name2.length() - 1)); } else { name2 = name2.substring(0, (max - name1.length() - 1)); } } // order them in some well defined way, like alphabetic order if (ordered) { String name; if (name1.compareTo(name2) < 0) { name = name1 + "_" + name2; } else { name = name2 + "_" + name1; } return name; } return name2 + "_" + name1; } private String removeIdSuffix(String name, DomainObject to) { String idSuffix = idSuffix(name, to); if (idSuffix.equals("")) { return name; } if (name.endsWith(idSuffix)) { return name.substring(0, name.length() - idSuffix.length()); } return name; } /** * Inverse attribute for many-to-many associations. */ public boolean isInverse(Reference ref) { if (ref.isInverse()) { return true; } if (!ref.isInverse() && (ref.getOpposite() != null) && ref.getOpposite().isInverse()) { return false; } if (ref.getOpposite() == null) { return false; } // inverse not defined on any side, use this algorithm String name1 = ref.getTo().getName(); String name2 = ref.getFrom().getName(); // use a well defined algorithm, like alphabetic order // A -> B inverse=false // B -> A inverse= true return (name1.compareTo(name2) < 0); } /** * List of references with multiplicity > 1 */ private List<Reference> getAllManyReferences(DomainObject domainObject) { List<Reference> allReferences = domainObject.getReferences(); List<Reference> allManyReferences = new ArrayList<Reference>(); for (Reference ref : allReferences) { if (ref.isMany()) { allManyReferences.add(ref); } } return allManyReferences; } /** * List of references with multiplicity = 1 */ private List<Reference> getAllOneReferences(DomainObject domainObject) { List<Reference> allReferences = domainObject.getReferences(); List<Reference> allOneReferences = new ArrayList<Reference>(); for (Reference ref : allReferences) { if (!ref.isMany()) { allOneReferences.add(ref); } } return allOneReferences; } public String getDerivedCascade(Reference ref) { boolean inSameModule = ref.getFrom().getModule().equals(ref.getTo().getModule()); boolean biDirectional = ref.getOpposite() != null; boolean aggregate = helperBase.isEntityOrPersistentValueObject(ref.getTo()) && !ref.getTo().isAggregateRoot(); boolean oneToMany = biDirectional && ref.isMany() && !ref.getOpposite().isMany(); boolean manyToMany = biDirectional && ref.isMany() && ref.getOpposite().isMany(); boolean oneToOne = biDirectional && !ref.isMany() && !ref.getOpposite().isMany(); if (aggregate) { if (oneToMany) { return propBase.getDefaultCascade("aggregate.oneToMany"); } else { return propBase.getDefaultCascade("aggregate"); } } if (!inSameModule) { return null; } if (manyToMany) { return isInverse(ref) ? null : propBase.getDefaultCascade("manyToMany"); } if (oneToMany) { return propBase.getDefaultCascade("oneToMany"); } if (oneToOne) { return propBase.getDefaultCascade("oneToOne"); } if (!biDirectional && ref.isMany()) { return propBase.getDefaultCascade("toMany"); } if (!biDirectional && !ref.isMany()) { return propBase.getDefaultCascade("toOne"); } return null; } }
false
false
null
null
diff --git a/fog.routing.hrm/src/de/tuilmenau/ics/fog/app/routing/QoSTestApp.java b/fog.routing.hrm/src/de/tuilmenau/ics/fog/app/routing/QoSTestApp.java index 4074ba36..a8642a12 100644 --- a/fog.routing.hrm/src/de/tuilmenau/ics/fog/app/routing/QoSTestApp.java +++ b/fog.routing.hrm/src/de/tuilmenau/ics/fog/app/routing/QoSTestApp.java @@ -1,406 +1,429 @@ /******************************************************************************* * Forwarding on Gates Simulator/Emulator - Hierarchical Routing Management * Copyright (c) 2012, Integrated Communication Systems Group, TU Ilmenau. * * 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. ******************************************************************************/ package de.tuilmenau.ics.fog.app.routing; import java.rmi.RemoteException; import java.util.LinkedList; import java.util.Random; import de.tuilmenau.ics.fog.application.ThreadApplication; import de.tuilmenau.ics.fog.facade.Connection; import de.tuilmenau.ics.fog.facade.Name; import de.tuilmenau.ics.fog.facade.NetworkException; import de.tuilmenau.ics.fog.packets.InvisibleMarker; import de.tuilmenau.ics.fog.routing.naming.HierarchicalNameMappingService; import de.tuilmenau.ics.fog.routing.naming.NameMappingEntry; import de.tuilmenau.ics.fog.routing.naming.NameMappingService; import de.tuilmenau.ics.fog.routing.naming.hierarchical.HRMID; import de.tuilmenau.ics.fog.topology.Node; import de.tuilmenau.ics.fog.ui.Logging; import de.tuilmenau.ics.fog.ui.Marker; import de.tuilmenau.ics.fog.ui.eclipse.commands.hierarchical.ProbeRouting; import de.tuilmenau.ics.fog.util.SimpleName; /** * This class is responsible for creating QoS-probe connections and also for their destruction. */ public class QoSTestApp extends ThreadApplication { /** * Stores a reference to the NMS instance. */ private NameMappingService mNMS = null; /** * Stores the current node where the probe routing should start */ private Node mNode = null; /** * Stores the name of the destination node */ Name mDestinationNodeName = null; /** * Stores the last destination HRMID */ HRMID mDestinationHRMID = null; /** * Stores the established connections */ LinkedList<Connection> mConnections = new LinkedList<Connection>(); boolean mQoSTestNeeded = true; boolean mQoSTestRunning = false; enum Operation{INC_CONN, DEC_CONN}; LinkedList<Operation> mOperations = new LinkedList<Operation>(); /** * Constructor * * @param pLocalNode the local node where this app. instance is running * @param pDestinationNodeNameStr the name of the destination node as string */ public QoSTestApp(Node pLocalNode, String pDestinationNodeNameStr) { super(pLocalNode, null); mNode = pLocalNode; /** * Get a reference to the naming-service */ try { mNMS = HierarchicalNameMappingService.getGlobalNameMappingService(mNode.getAS().getSimulation()); } catch (RuntimeException tExc) { mNMS = HierarchicalNameMappingService.createGlobalNameMappingService(mNode.getAS().getSimulation()); } /** * get the name of the central FN */ mDestinationNodeName = new SimpleName(Node.NAMESPACE_HOST, pDestinationNodeNameStr); } /** * Determines the HRMIDs of the destination node * * @return the list of HRMIDs */ private LinkedList<HRMID> getDestinationHRMIDs() { LinkedList<HRMID> tResult = new LinkedList<HRMID>(); /** * Get the HRMID of the destination node */ // send a HRM probe-packet to each registered address for the given target name try { for(NameMappingEntry<?> tNMSEntryForTarget : mNMS.getAddresses(mDestinationNodeName)) { if(tNMSEntryForTarget.getAddress() instanceof HRMID) { // get the HRMID of the target node HRMID tTargetNodeHRMID = (HRMID)tNMSEntryForTarget.getAddress(); Logging.log(this, "Found in the NMS the HRMID " + tTargetNodeHRMID.toString() + " for node " + mDestinationNodeName); } } for(NameMappingEntry<?> tNMSEntryForTarget : mNMS.getAddresses(mDestinationNodeName)) { if(tNMSEntryForTarget.getAddress() instanceof HRMID) { // get the HRMID of the target node HRMID tDestinationNodeHRMID = (HRMID)tNMSEntryForTarget.getAddress(); // an entry in the result list tResult.add(tDestinationNodeHRMID); } } } catch (RemoteException tExc) { Logging.err(this, "Unable to determine addresses for node " + mDestinationNodeName, tExc); } return tResult; } /** * EVENT: increase connections */ public synchronized void eventIncreaseConnections() { Logging.log(this, "EVENT: increase connections (currently: " + countConnections() + ")"); synchronized (mOperations) { mOperations.add(Operation.INC_CONN); } notify(); } /** * EVENT: descrease connections */ public synchronized void eventDecreaseConnections() { Logging.log(this, "EVENT: decrease connections (currently: " + countConnections() + ")"); synchronized (mOperations) { mOperations.add(Operation.DEC_CONN); } notify(); } /** * Sends a marker along an established connection * * @param pConnection the connection, whose route should be marked */ private void sendMarker(Connection pConnection) { Random tRandom = new Random(); int tRed = (int)(tRandom.nextFloat() * 128) + 127; int tGreen = (int)(tRandom.nextFloat() * 128) + 127; int tBlue = (int)(tRandom.nextFloat() * 128) + 127; Logging.log("Creating marker with coloring (" + tRed + ", " + tGreen + ", " + tBlue + ")"); java.awt.Color tMarkerColor = new java.awt.Color(tRed, tGreen, tBlue); String tMarkerText = "Marker " +new Random().nextInt(); InvisibleMarker.Operation tMarkerOperation = InvisibleMarker.Operation.ADD; Marker tMarker = new Marker(tMarkerText, tMarkerColor); InvisibleMarker tMarkerPacketPayload = new InvisibleMarker(tMarker, tMarkerOperation); //Logging.log(this, "Sending: " + tMarkerPacketPayload); try { pConnection.write(tMarkerPacketPayload); } catch (NetworkException tExc) { Logging.err(this, "sendMarker() wasn't able to send marker", tExc); } } /** * Returns the last destination HRMID * * @return the last destination HRMID */ public HRMID getLastDestinationHRMID() { return mDestinationHRMID; } /** * Adds another connection */ private void incConnections() { Logging.log(this, "Increasing connections (currently: " + countConnections() + ")"); LinkedList<HRMID> tDestinationHRMIDs = getDestinationHRMIDs(); HRMID tDestinationHRMID = tDestinationHRMIDs.getFirst(); mDestinationHRMID = tDestinationHRMID; if(!tDestinationHRMIDs.isEmpty()){ /** * Connect to the destination node */ Connection tConnection = ProbeRouting.createProbeRoutingConnection(mNode, tDestinationHRMID, 53 /* ms */, 1000 /* kbit/s */, false); /** * Check if connect request was successful */ if(tConnection != null){ Logging.log(this, " ..found valid connection to " + tDestinationHRMID); synchronized (mConnections) { mConnections.add(tConnection); } /** * Send some test data */ for(int i = 0; i < 3; i++){ try { //Logging.log(this, " ..sending test data " + i); tConnection.write("TEST DATA " + Integer.toString(i)); } catch (NetworkException tExc) { Logging.err(this, "Couldn't send test data", tExc); } } /** * Send connection marker */ sendMarker(tConnection); } } } /** * Removes the last connection */ private void decConnections() { Logging.log(this, "Decreasing connections (currently: " + countConnections() + ")"); /** * get the last connection */ Connection tConnection = null; synchronized (mConnections) { if(countConnections() > 0){ tConnection = mConnections.removeLast(); } } /** * Disconnect by closing the connection */ if(tConnection != null){ tConnection.close(); } } /** * Counts the already established connections * * @return the number of connections */ public int countConnections() { int tResult = 0; synchronized (mConnections) { if(mConnections != null){ tResult = mConnections.size(); } } //Logging.log(this, "Connections: " + tResult); return tResult; } /** * Waits for the next wake-up signal (a new event was triggered) */ private synchronized void waitForNextEvent() { // suspend until next trigger try { wait(); //Logging.log(this, "WakeUp"); } catch (InterruptedException tExc) { Logging.warn(this, "waitForNextEvent() got an interrupt", tExc); } } /** * The main loop */ /* (non-Javadoc) * @see de.tuilmenau.ics.fog.application.ThreadApplication#execute() */ @Override protected void execute() { /** * START */ Logging.log(this, "Main loop started"); mQoSTestRunning = true; /** * MAIN LOOP */ while(mQoSTestNeeded){ Operation tNextOperation = null; do{ /** * Get the next operation */ tNextOperation = null; synchronized (mOperations) { if(mOperations.size() > 0){ tNextOperation = mOperations.removeFirst(); } } /** * Process the next operation */ if(tNextOperation != null){ Logging.log(this, "Processing operation: " + tNextOperation); switch(tNextOperation) { case INC_CONN: incConnections(); break; case DEC_CONN: decConnections(); break; default: break; } } }while(tNextOperation != null); waitForNextEvent(); } - + + /** + * Close all existing connections + */ + Connection tConnection = null; + do{ + /** + * get the last connection + */ + tConnection = null; + synchronized (mConnections) { + if(countConnections() > 0){ + tConnection = mConnections.removeLast(); + } + } + + /** + * Disconnect by closing the connection + */ + if(tConnection != null){ + tConnection.close(); + } + }while(tConnection != null); + /** * END */ Logging.log(this, "Main loop finished"); mQoSTestRunning = false; } /** * Exit the QoS test app. right now */ /* (non-Javadoc) * @see de.tuilmenau.ics.fog.application.Application#exit() */ @Override public synchronized void exit() { Logging.log(this, "exit() starting... (running: " + isRunning() + ")"); mQoSTestNeeded = false; // wakeup if(isRunning()){ notifyAll(); } Logging.log(this, "..exit() finished"); } /** * Returns if the QoS test app. is still running * * @return true or false */ /* (non-Javadoc) * @see de.tuilmenau.ics.fog.application.Application#isRunning() */ @Override public boolean isRunning() { return mQoSTestRunning; } /** * Returns a descriptive string about this app. * * @return the descriptive string */ @Override public String toString() { return getClass().getSimpleName() +"@" + mNode; } }
true
false
null
null
diff --git a/mes-plugins/mes-plugins-states/src/main/java/com/qcadoo/mes/states/aop/AbstractStateChangeAspect.java b/mes-plugins/mes-plugins-states/src/main/java/com/qcadoo/mes/states/aop/AbstractStateChangeAspect.java index 381a08fb67..b81e67cd3b 100644 --- a/mes-plugins/mes-plugins-states/src/main/java/com/qcadoo/mes/states/aop/AbstractStateChangeAspect.java +++ b/mes-plugins/mes-plugins-states/src/main/java/com/qcadoo/mes/states/aop/AbstractStateChangeAspect.java @@ -1,122 +1,122 @@ package com.qcadoo.mes.states.aop; import static com.qcadoo.mes.states.constants.StateChangeStatus.SUCCESSFUL; import java.util.Date; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.DeclarePrecedence; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.transaction.annotation.Transactional; import com.qcadoo.mes.states.StateChangeContext; import com.qcadoo.mes.states.StateChangeEntityDescriber; import com.qcadoo.mes.states.StateEnum; import com.qcadoo.mes.states.constants.StateChangeStatus; import com.qcadoo.mes.states.exception.StateChangeException; import com.qcadoo.mes.states.exception.StateTransitionNotAlloweException; import com.qcadoo.mes.states.messages.constants.StateMessageType; import com.qcadoo.mes.states.messages.util.ValidationMessageHelper; import com.qcadoo.mes.states.service.StateChangePhaseUtil; import com.qcadoo.mes.states.service.StateChangeService; import com.qcadoo.model.api.Entity; /** * Abstract service for changing entity state which provides default implementation. * * @since 1.1.7 */ @Aspect @Configurable @DeclarePrecedence("com.qcadoo.mes.states.aop.StateChangePhaseAspect, com.qcadoo.mes.states.aop.RunInPhaseAspect") public abstract class AbstractStateChangeAspect implements StateChangeService { protected static final int DEFAULT_NUM_OF_PHASES = 2; @Override @Transactional public void changeState(final StateChangeContext stateChangeContext) { stateChangeContext.save(); performPreValidation(stateChangeContext); final StateChangeEntityDescriber describer = stateChangeContext.getDescriber(); try { describer.checkFields(); for (int phase = stateChangeContext.getPhase() + 1; phase <= getNumOfPhases(); phase++) { if (StateChangePhaseUtil.canRun(stateChangeContext)) { stateChangeContext.setPhase(phase); changeStatePhase(stateChangeContext, phase); } } final Entity owner = stateChangeContext.getOwner(); stateChangeContext.setOwner(owner); performChangeEntityState(stateChangeContext); } catch (Exception e) { stateChangeContext.setStatus(StateChangeStatus.FAILURE); stateChangeContext.addMessage("states.messages.change.failure.internalServerError", StateMessageType.FAILURE); stateChangeContext.save(); throw new StateChangeException(e); } } private boolean performPreValidation(final StateChangeContext stateChangeContext) { final StateChangeEntityDescriber describer = stateChangeContext.getDescriber(); final Entity owner = stateChangeContext.getOwner(); owner.setField(describer.getOwnerStateFieldName(), stateChangeContext.getStateChangeEntity().getStringField(describer.getTargetStateFieldName())); owner.getDataDefinition().callValidators(owner); ValidationMessageHelper.copyErrorsFromEntity(stateChangeContext, owner); return owner.isValid(); } /** * Get number of state change phases. Default value is {@link AbstractStateChangeAspect#DEFAULT_NUM_OF_PHASES}. * * @return number of phases */ protected int getNumOfPhases() { return DEFAULT_NUM_OF_PHASES; } /** * Single state change phase join point. * * @param stateChangeEntity * @param phaseNumber */ protected abstract void changeStatePhase(final StateChangeContext stateChangeContext, final int phaseNumber); @Transactional protected void performChangeEntityState(final StateChangeContext stateChangeContext) { final StateChangeEntityDescriber describer = stateChangeContext.getDescriber(); if (!StateChangePhaseUtil.canRun(stateChangeContext)) { if (!stateChangeContext.isOwnerValid()) { stateChangeContext.setStatus(StateChangeStatus.FAILURE); stateChangeContext.setField(describer.getDateTimeFieldName(), new Date()); } return; } - final Entity owner = stateChangeContext.getOwner(); + final Entity owner = describer.getOwnerDataDefinition().save(stateChangeContext.getOwner()); final StateEnum sourceState = stateChangeContext.getStateEnumValue(describer.getSourceStateFieldName()); final StateEnum targetState = stateChangeContext.getStateEnumValue(describer.getTargetStateFieldName()); if (sourceState != null && !sourceState.canChangeTo(targetState)) { throw new StateTransitionNotAlloweException(sourceState, targetState); } boolean ownerIsValid = stateChangeContext.isOwnerValid(); if (ownerIsValid) { owner.setField(describer.getOwnerStateFieldName(), targetState.getStringValue()); ownerIsValid = owner.getDataDefinition().save(owner).isValid(); } if (ownerIsValid) { stateChangeContext.setStatus(SUCCESSFUL); } else { ValidationMessageHelper.copyErrorsFromEntity(stateChangeContext, owner); stateChangeContext.setStatus(StateChangeStatus.FAILURE); } stateChangeContext.setField(describer.getDateTimeFieldName(), new Date()); stateChangeContext.save(); } } diff --git a/mes-plugins/mes-plugins-technologies/src/main/java/com/qcadoo/mes/technologies/TechnologyService.java b/mes-plugins/mes-plugins-technologies/src/main/java/com/qcadoo/mes/technologies/TechnologyService.java index 967e8f24e2..d29c362d71 100644 --- a/mes-plugins/mes-plugins-technologies/src/main/java/com/qcadoo/mes/technologies/TechnologyService.java +++ b/mes-plugins/mes-plugins-technologies/src/main/java/com/qcadoo/mes/technologies/TechnologyService.java @@ -1,879 +1,883 @@ /** * *************************************************************************** * Copyright (c) 2010 Qcadoo Limited * Project: Qcadoo MES * Version: 1.1.6 * * This file is part of Qcadoo. * * Qcadoo is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation; either version 3 of the License, * or (at your option) any later version. * * 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, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *************************************************************************** */ package com.qcadoo.mes.technologies; import static com.qcadoo.mes.technologies.constants.TechnologiesConstants.MODEL_TECHNOLOGY_OPERATION_COMPONENT; import static com.qcadoo.mes.technologies.constants.TechnologiesConstants.REFERENCE_TECHNOLOGY; import static com.qcadoo.mes.technologies.constants.TechnologyFields.STATE; import static com.qcadoo.mes.technologies.states.constants.TechnologyState.ACCEPTED; import static com.qcadoo.mes.technologies.states.constants.TechnologyState.CHECKED; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import com.google.common.collect.Lists; import com.qcadoo.localization.api.TranslationService; import com.qcadoo.mes.basic.constants.BasicConstants; import com.qcadoo.mes.technologies.constants.TechnologiesConstants; +import com.qcadoo.mes.technologies.constants.TechnologyFields; import com.qcadoo.mes.technologies.states.constants.TechnologyState; import com.qcadoo.model.api.DataDefinition; import com.qcadoo.model.api.DataDefinitionService; import com.qcadoo.model.api.Entity; import com.qcadoo.model.api.EntityList; import com.qcadoo.model.api.EntityTree; import com.qcadoo.model.api.EntityTreeNode; import com.qcadoo.model.api.search.SearchCriteriaBuilder; import com.qcadoo.model.api.search.SearchRestrictions; import com.qcadoo.model.api.utils.TreeNumberingService; import com.qcadoo.plugin.api.PluginAccessor; import com.qcadoo.view.api.ComponentState; import com.qcadoo.view.api.ViewDefinitionState; import com.qcadoo.view.api.components.FieldComponent; import com.qcadoo.view.api.components.FormComponent; import com.qcadoo.view.api.components.GridComponent; import com.qcadoo.view.api.components.TreeComponent; import com.qcadoo.view.api.utils.NumberGeneratorService; @Service public class TechnologyService { private static final String L_FORM = "form"; private static final String L_QUANTITY = "quantity"; private static final String L_UNIT_SAMPLING_NR = "unitSamplingNr"; private static final String L_QUALITY_CONTROL_TYPE = "qualityControlType"; private static final String L_ENTITY_TYPE = "entityType"; private static final String L_OPERATION_COMPONENTS = "operationComponents"; private static final String L_REFERENCE_TECHNOLOGY = "referenceTechnology"; private static final String L_PRODUCT = "product"; private static final String L_NAME = "name"; private static final String L_PARENT = "parent"; private static final String L_NUMBER = "number"; public static final String L_04_WASTE = "04waste"; public static final String L_03_FINAL_PRODUCT = "03finalProduct"; public static final String L_01_COMPONENT = "01component"; public static final String L_02_INTERMEDIATE = "02intermediate"; public static final String L_00_UNRELATED = "00unrelated"; private static final String L_TECHNOLOGY = "technology"; private static final String L_MASTER = "master"; private static final String L_OPERATION = "operation"; private static final String L_OPERATION_COMPONENT = "operationComponent"; private static final String L_OPERATION_PRODUCT_IN_COMPONENTS = "operationProductInComponents"; private static final String L_OPERATION_PRODUCT_OUT_COMPONENTS = "operationProductOutComponents"; private static final String L_REFERENCE_MODE = "referenceMode"; @Autowired private DataDefinitionService dataDefinitionService; @Autowired private NumberGeneratorService numberGeneratorService; @Autowired private TreeNumberingService treeNumberingService; @Autowired private TranslationService translationService; @Autowired private ProductQuantitiesService productQuantitiesService; @Autowired private PluginAccessor pluginAccessor; public boolean isTechnologyUsedInActiveOrder(final Entity technology) { if (!ordersPluginIsEnabled()) { return false; } SearchCriteriaBuilder searchCriteria = getOrderDataDefinition().find(); searchCriteria.add(SearchRestrictions.belongsTo("technology", technology)); searchCriteria.add(SearchRestrictions.in("state", Lists.newArrayList("01pending", "02accepted", "03inProgress", "06interrupted"))); searchCriteria.setMaxResults(1); return searchCriteria.uniqueResult() != null; } private boolean ordersPluginIsEnabled() { return pluginAccessor.getPlugin("orders") != null; } private DataDefinition getOrderDataDefinition() { return dataDefinitionService.get("orders", "order"); } private enum ProductDirection { IN, OUT; } public boolean clearMasterOnCopy(final DataDefinition dataDefinition, final Entity entity) { entity.setField(L_MASTER, false); return true; } public void setFirstTechnologyAsDefault(final DataDefinition dataDefinition, final Entity entity) { if ((Boolean) entity.getField(L_MASTER)) { return; } SearchCriteriaBuilder searchCriteria = dataDefinition.find(); searchCriteria.add(SearchRestrictions.belongsTo(L_PRODUCT, entity.getBelongsToField(L_PRODUCT))); entity.setField(L_MASTER, searchCriteria.list().getTotalNumberOfEntities() == 0); } public boolean checkTechnologyDefault(final DataDefinition dataDefinition, final Entity entity) { if (!((Boolean) entity.getField(L_MASTER))) { return true; } SearchCriteriaBuilder searchCriteries = dataDefinition.find(); searchCriteries.add(SearchRestrictions.eq(L_MASTER, true)); searchCriteries.add(SearchRestrictions.belongsTo(L_PRODUCT, entity.getBelongsToField(L_PRODUCT))); if (entity.getId() != null) { searchCriteries.add(SearchRestrictions.idNe(entity.getId())); } if (searchCriteries.list().getTotalNumberOfEntities() == 0) { return true; } entity.addError(dataDefinition.getField(L_MASTER), "orders.validate.global.error.default"); return false; } public void loadProductsForReferencedTechnology(final ViewDefinitionState viewDefinitionState, final ComponentState state, final String[] args) { if (!(state instanceof TreeComponent)) { return; } TreeComponent tree = (TreeComponent) state; if (tree.getSelectedEntityId() == null) { return; } Entity operationComponent = dataDefinitionService.get(TechnologiesConstants.PLUGIN_IDENTIFIER, TechnologiesConstants.MODEL_TECHNOLOGY_OPERATION_COMPONENT).get(tree.getSelectedEntityId()); GridComponent outProductsGrid = (GridComponent) viewDefinitionState.getComponentByReference("outProducts"); GridComponent inProductsGrid = (GridComponent) viewDefinitionState.getComponentByReference("inProducts"); if (!REFERENCE_TECHNOLOGY.equals(operationComponent.getStringField(L_ENTITY_TYPE))) { // inProductsGrid.setEnabled(true); inProductsGrid.setEditable(true); // outProductsGrid.setEnabled(true); outProductsGrid.setEditable(true); return; } Entity technology = operationComponent.getBelongsToField(REFERENCE_TECHNOLOGY); EntityTree operations = technology.getTreeField(L_OPERATION_COMPONENTS); Entity rootOperation = operations.getRoot(); if (rootOperation != null) { outProductsGrid.setEntities(rootOperation.getHasManyField(L_OPERATION_PRODUCT_OUT_COMPONENTS)); } List<Entity> inProducts = new ArrayList<Entity>(); Map<Entity, BigDecimal> productQuantities = productQuantitiesService.getNeededProductQuantities(technology, BigDecimal.ONE, false); for (Entry<Entity, BigDecimal> productQuantity : productQuantities.entrySet()) { Entity inProduct = dataDefinitionService.get(TechnologiesConstants.PLUGIN_IDENTIFIER, TechnologiesConstants.MODEL_OPERATION_PRODUCT_IN_COMPONENT).create(); inProduct.setField(L_OPERATION_COMPONENT, rootOperation); inProduct.setField(L_PRODUCT, productQuantity.getKey()); inProduct.setField(L_QUANTITY, productQuantity.getValue()); inProducts.add(inProduct); } inProductsGrid.setEntities(inProducts); inProductsGrid.setEnabled(false); inProductsGrid.setEditable(false); outProductsGrid.setEnabled(false); outProductsGrid.setEditable(false); } public void checkQualityControlType(final ViewDefinitionState viewDefinitionState, final ComponentState state, final String[] args) { if (!(state instanceof FieldComponent)) { throw new IllegalStateException("component is not select"); } FieldComponent qualityControlType = (FieldComponent) state; FieldComponent unitSamplingNr = (FieldComponent) viewDefinitionState.getComponentByReference(L_UNIT_SAMPLING_NR); if (qualityControlType.getFieldValue() != null) { if (qualityControlType.getFieldValue().equals("02forUnit")) { unitSamplingNr.setRequired(true); unitSamplingNr.setVisible(true); } else { unitSamplingNr.setRequired(false); unitSamplingNr.setVisible(false); } } } public void generateTechnologyGroupNumber(final ViewDefinitionState viewDefinitionState) { numberGeneratorService.generateAndInsertNumber(viewDefinitionState, TechnologiesConstants.PLUGIN_IDENTIFIER, TechnologiesConstants.MODEL_TECHNOLOGY_GROUP, L_FORM, L_NUMBER); } public void generateTechnologyNumber(final ViewDefinitionState state, final ComponentState componentState, final String[] args) { if (!(componentState instanceof FieldComponent)) { throw new IllegalStateException("component is not FieldComponentState"); } FieldComponent number = (FieldComponent) state.getComponentByReference(L_NUMBER); FieldComponent productState = (FieldComponent) componentState; if (!numberGeneratorService.checkIfShouldInsertNumber(state, L_FORM, L_NUMBER) || productState.getFieldValue() == null) { return; } Entity product = getProductById((Long) productState.getFieldValue()); if (product == null) { return; } String numberValue = product.getField(L_NUMBER) + "-" + numberGeneratorService.generateNumber(TechnologiesConstants.PLUGIN_IDENTIFIER, TechnologiesConstants.MODEL_TECHNOLOGY, 3); number.setFieldValue(numberValue); } public void generateTechnologyName(final ViewDefinitionState state, final ComponentState componentState, final String[] args) { if (!(componentState instanceof FieldComponent)) { throw new IllegalStateException("component is not FieldComponentState"); } FieldComponent name = (FieldComponent) state.getComponentByReference(L_NAME); FieldComponent productState = (FieldComponent) componentState; if (StringUtils.hasText((String) name.getFieldValue()) || productState.getFieldValue() == null) { return; } Entity product = getProductById((Long) productState.getFieldValue()); if (product == null) { return; } Calendar cal = Calendar.getInstance(state.getLocale()); cal.setTime(new Date()); name.setFieldValue(translationService.translate("technologies.operation.name.default", state.getLocale(), product.getStringField(L_NAME), product.getStringField(L_NUMBER), cal.get(Calendar.YEAR) + "." + (cal.get(Calendar.MONTH) + 1))); } public void hideReferenceMode(final ViewDefinitionState viewDefinitionState) { FormComponent form = (FormComponent) viewDefinitionState.getComponentByReference(L_FORM); if (form.getEntityId() != null) { ComponentState referenceModeComponent = viewDefinitionState.getComponentByReference(L_REFERENCE_MODE); referenceModeComponent.setFieldValue("01reference"); referenceModeComponent.setVisible(false); } } private Entity getProductById(final Long productId) { return dataDefinitionService.get(BasicConstants.PLUGIN_IDENTIFIER, BasicConstants.MODEL_PRODUCT).get(productId); } public boolean copyReferencedTechnology(final DataDefinition dataDefinition, final Entity entity) { if (!REFERENCE_TECHNOLOGY.equals(entity.getField(L_ENTITY_TYPE)) && entity.getField(REFERENCE_TECHNOLOGY) == null) { return true; } boolean copy = "02copy".equals(entity.getField(L_REFERENCE_MODE)); Entity technology = entity.getBelongsToField(L_TECHNOLOGY); Entity referencedTechnology = entity.getBelongsToField(REFERENCE_TECHNOLOGY); Set<Long> technologies = new HashSet<Long>(); technologies.add(technology.getId()); boolean cyclic = checkForCyclicReferences(technologies, referencedTechnology, copy); if (cyclic) { entity.addError(dataDefinition.getField(REFERENCE_TECHNOLOGY), "technologies.technologyReferenceTechnologyComponent.error.cyclicDependency"); return false; } if (copy) { EntityTreeNode root = referencedTechnology.getTreeField(L_OPERATION_COMPONENTS).getRoot(); Entity copiedRoot = copyReferencedTechnologyOperations(root, entity.getBelongsToField(L_TECHNOLOGY)); for (Entry<String, Object> entry : copiedRoot.getFields().entrySet()) { if (!(entry.getKey().equals("id") || entry.getKey().equals(L_PARENT))) { entity.setField(entry.getKey(), entry.getValue()); } } entity.setField(L_ENTITY_TYPE, L_OPERATION); entity.setField(REFERENCE_TECHNOLOGY, null); } return true; } private boolean checkForCyclicReferences(final Set<Long> technologies, final Entity referencedTechnology, final boolean copy) { if (!copy && technologies.contains(referencedTechnology.getId())) { return true; } technologies.add(referencedTechnology.getId()); for (Entity operationComponent : referencedTechnology.getTreeField(L_OPERATION_COMPONENTS)) { if (REFERENCE_TECHNOLOGY.equals(operationComponent.getField(L_ENTITY_TYPE))) { boolean cyclic = checkForCyclicReferences(technologies, operationComponent.getBelongsToField(REFERENCE_TECHNOLOGY), false); if (cyclic) { return true; } } } return false; } private Entity copyReferencedTechnologyOperations(final Entity node, final Entity technology) { Entity copy = node.copy(); copy.setId(null); copy.setField(L_PARENT, null); copy.setField(L_TECHNOLOGY, technology); for (Entry<String, Object> entry : node.getFields().entrySet()) { Object value = entry.getValue(); if (value instanceof EntityList) { EntityList entities = (EntityList) value; List<Entity> copies = new ArrayList<Entity>(); for (Entity entity : entities) { copies.add(copyReferencedTechnologyOperations(entity, technology)); } copy.setField(entry.getKey(), copies); } } return copy; } public boolean validateTechnologyOperationComponent(final DataDefinition dataDefinition, final Entity entity) { boolean isValid = true; if (L_OPERATION.equals(entity.getStringField(L_ENTITY_TYPE))) { if (entity.getField(L_OPERATION) == null) { entity.addError(dataDefinition.getField(L_OPERATION), "qcadooView.validate.field.error.missing"); isValid = false; } } else if (REFERENCE_TECHNOLOGY.equals(entity.getStringField(L_ENTITY_TYPE))) { if (entity.getField(REFERENCE_TECHNOLOGY) == null) { entity.addError(dataDefinition.getField(REFERENCE_TECHNOLOGY), "qcadooView.validate.field.error.missing"); isValid = false; } if (entity.getField(L_REFERENCE_MODE) == null) { entity.setField(L_REFERENCE_MODE, "01reference"); } } else { throw new IllegalStateException("unknown entityType"); } return isValid; } public boolean checkIfTechnologyHasAtLeastOneComponent(final DataDefinition dataDefinition, final Entity technology) { if (!ACCEPTED.getStringValue().equals(technology.getStringField(STATE)) && !CHECKED.getStringValue().equals(technology.getStringField(STATE))) { return true; } final Entity savedTechnology = dataDefinition.get(technology.getId()); final EntityTree operations = savedTechnology.getTreeField(L_OPERATION_COMPONENTS); if (operations != null && !operations.isEmpty()) { for (Entity operation : operations) { if (L_OPERATION.equals(operation.getStringField(L_ENTITY_TYPE))) { return true; } } } technology.addGlobalError("technologies.technology.validate.global.error.emptyTechnologyTree"); return false; } public boolean checkTopComponentsProducesProductForTechnology(final DataDefinition dataDefinition, final Entity technology) { if (!ACCEPTED.getStringValue().equals(technology.getStringField(STATE)) && !CHECKED.getStringValue().equals(technology.getStringField(STATE))) { return true; } final Entity savedTechnology = dataDefinition.get(technology.getId()); final Entity product = savedTechnology.getBelongsToField(L_PRODUCT); final EntityTree operations = savedTechnology.getTreeField(L_OPERATION_COMPONENTS); final EntityTreeNode root = operations.getRoot(); final EntityList productOutComps = root.getHasManyField(L_OPERATION_PRODUCT_OUT_COMPONENTS); for (Entity productOutComp : productOutComps) { if (product.getId().equals(productOutComp.getBelongsToField(L_PRODUCT).getId())) { return true; } } technology.addGlobalError("technologies.technology.validate.global.error.noFinalProductInTechnologyTree"); return false; } public boolean checkIfAllReferenceTechnologiesAreAceepted(final DataDefinition dataDefinition, final Entity technology) { if (!ACCEPTED.getStringValue().equals(technology.getStringField(STATE)) && !CHECKED.getStringValue().equals(technology.getStringField(STATE))) { return true; } final Entity savedTechnology = dataDefinition.get(technology.getId()); final EntityTree operations = savedTechnology.getTreeField(L_OPERATION_COMPONENTS); for (Entity operation : operations) { if (L_OPERATION.equals(operation.getStringField(L_ENTITY_TYPE))) { continue; } final Entity referenceTechnology = operation.getBelongsToField(L_REFERENCE_TECHNOLOGY); if (referenceTechnology != null && !TechnologyState.ACCEPTED.getStringValue().equals(referenceTechnology.getStringField(STATE))) { technology.addError(dataDefinition.getField(L_OPERATION_COMPONENTS), "technologies.technology.validate.global.error.unacceptedReferenceTechnology"); return false; } } return true; } public boolean checkIfOperationsUsesSubOperationsProds(final DataDefinition dataDefinition, final Entity technology) { if (!ACCEPTED.getStringValue().equals(technology.getStringField(STATE)) && !CHECKED.getStringValue().equals(technology.getStringField(STATE))) { return true; } final Entity savedTechnology = dataDefinition.get(technology.getId()); final EntityTree technologyOperations = savedTechnology.getTreeField(L_OPERATION_COMPONENTS); Set<Entity> operations = checkIfConsumesSubOpsProds(technologyOperations); if (!operations.isEmpty()) { StringBuilder levels = new StringBuilder(); for (Entity operation : operations) { if (levels.length() != 0) { levels.append(", "); } levels.append(operation.getStringField("nodeNumber")); } if (operations.size() == 1) { technology.addError(dataDefinition.getField(L_OPERATION_COMPONENTS), "technologies.technology.validate.global.error.operationDontConsumeSubOperationsProducts", levels.toString()); } else { technology.addError(dataDefinition.getField(L_OPERATION_COMPONENTS), "technologies.technology.validate.global.error.operationDontConsumeSubOperationsProductsPlural", levels.toString()); } return false; } return true; } private boolean checkIfAtLeastOneCommonElement(final List<Entity> prodsIn, final List<Entity> prodsOut) { for (Entity prodOut : prodsOut) { for (Entity prodIn : prodsIn) { if (prodIn.getBelongsToField(L_PRODUCT).getId().equals(prodOut.getBelongsToField(L_PRODUCT).getId())) { return true; } } } return false; } private Set<Entity> checkIfConsumesSubOpsProds(final EntityTree technologyOperations) { Set<Entity> operations = new HashSet<Entity>(); for (Entity technologyOperation : technologyOperations) { final Entity parent = technologyOperation.getBelongsToField(L_PARENT); if (parent == null || L_REFERENCE_TECHNOLOGY.equals(parent.getStringField(L_ENTITY_TYPE))) { continue; } final EntityList prodsIn = parent.getHasManyField(L_OPERATION_PRODUCT_IN_COMPONENTS); if (L_OPERATION.equals(technologyOperation.getStringField(L_ENTITY_TYPE))) { final EntityList prodsOut = technologyOperation.getHasManyField(L_OPERATION_PRODUCT_OUT_COMPONENTS); if (prodsIn == null) { operations.add(parent); continue; } if (prodsIn.isEmpty()) { operations.add(parent); continue; } if (prodsOut == null) { operations.add(technologyOperation); continue; } if (prodsOut.isEmpty()) { operations.add(technologyOperation); continue; } if (!checkIfAtLeastOneCommonElement(prodsOut, prodsIn)) { operations.add(technologyOperation); } } else { final Entity prodOut = technologyOperation.getBelongsToField(L_REFERENCE_TECHNOLOGY); if (prodOut == null) { operations.add(parent); continue; } if (prodsIn == null) { operations.add(technologyOperation); continue; } if (prodsIn.isEmpty()) { operations.add(technologyOperation); continue; } if (!checkIfAtLeastOneCommonElement(Arrays.asList(prodOut), prodsIn)) { operations.add(technologyOperation); } } } return operations; } public boolean checkIfUnitSampligNrIsReq(final DataDefinition dataDefinition, final Entity entity) { String qualityControlType = (String) entity.getField(L_QUALITY_CONTROL_TYPE); if (qualityControlType != null && qualityControlType.equals("02forUnit")) { BigDecimal unitSamplingNr = (BigDecimal) entity.getField(L_UNIT_SAMPLING_NR); if (unitSamplingNr == null || unitSamplingNr.scale() > 3 || unitSamplingNr.compareTo(BigDecimal.ZERO) < 0 || unitSamplingNr.precision() > 7) { entity.addGlobalError("qcadooView.validate.global.error.custom"); entity.addError(dataDefinition.getField(L_UNIT_SAMPLING_NR), "technologies.technology.validate.global.error.unitSamplingNr"); return false; } } return true; } public void setLookupDisableInTechnologyOperationComponent(final ViewDefinitionState viewDefinitionState) { FormComponent form = (FormComponent) viewDefinitionState.getComponentByReference(L_FORM); FieldComponent operationLookup = (FieldComponent) viewDefinitionState.getComponentByReference(L_OPERATION); operationLookup.setEnabled(form.getEntityId() == null); } public final void performTreeNumbering(final DataDefinition dd, final Entity technology) { + if (TechnologyState.ACCEPTED.getStringValue().equals(technology.getStringField(TechnologyFields.STATE))) { + return; + } DataDefinition technologyOperationDD = dataDefinitionService.get(TechnologiesConstants.PLUGIN_IDENTIFIER, MODEL_TECHNOLOGY_OPERATION_COMPONENT); treeNumberingService.generateNumbersAndUpdateTree(technologyOperationDD, L_TECHNOLOGY, technology.getId()); } public void setParentIfRootNodeAlreadyExists(final DataDefinition dd, final Entity technologyOperation) { Entity technology = technologyOperation.getBelongsToField(L_TECHNOLOGY); EntityTree tree = technology.getTreeField(L_OPERATION_COMPONENTS); if (tree == null) { return; } if (tree.isEmpty()) { return; } EntityTreeNode rootNode = tree.getRoot(); if (rootNode == null || technologyOperation.getBelongsToField(L_PARENT) != null) { return; } technologyOperation.setField(L_PARENT, rootNode); } public void toggleDetailsViewEnabled(final ViewDefinitionState view) { view.getComponentByReference(STATE).performEvent(view, "toggleEnabled"); } public boolean invalidateIfBelongsToAcceptedTechnology(final DataDefinition dataDefinition, final Entity entity) { Entity technology = null; String errorMessageKey = "technologies.technology.state.error.modifyBelongsToAcceptedTechnology"; if (L_TECHNOLOGY.equals(dataDefinition.getName())) { technology = entity; errorMessageKey = "technologies.technology.state.error.modifyAcceptedTechnology"; } else if ("technologyOperationComponent".equals(dataDefinition.getName())) { technology = entity.getBelongsToField(L_TECHNOLOGY); } else if ("operationProductOutComponent".equals(dataDefinition.getName()) || "operationProductInComponent".equals(dataDefinition.getName())) { Entity operationComponent = entity.getBelongsToField(L_OPERATION_COMPONENT); if (operationComponent == null) { return true; } technology = operationComponent.getBelongsToField(L_TECHNOLOGY); } if (technology == null || technology.getId() == null) { return true; } Entity existingTechnology = technology.getDataDefinition().get(technology.getId()); if (checkIfDeactivated(dataDefinition, technology, existingTechnology)) { return true; } if (isTechnologyIsAlreadyAccepted(technology, existingTechnology)) { entity.addGlobalError(errorMessageKey, technology.getStringField(L_NAME)); return false; } return true; } private boolean checkIfDeactivated(final DataDefinition dataDefinition, final Entity technology, final Entity existingTechnology) { if (isTechnologyIsAlreadyAccepted(technology, existingTechnology) && L_TECHNOLOGY.equals(dataDefinition.getName()) && technology.isActive() != existingTechnology.isActive()) { return true; } return false; } private boolean isTechnologyIsAlreadyAccepted(final Entity technology, final Entity existingTechnology) { if (technology == null || existingTechnology == null) { return false; } TechnologyState technologyState = TechnologyState.parseString(technology.getStringField(STATE)); TechnologyState existingTechnologyState = TechnologyState.parseString(existingTechnology.getStringField(STATE)); return TechnologyState.ACCEPTED.equals(technologyState) && technologyState.equals(existingTechnologyState); } private boolean productComponentsContainProduct(final List<Entity> components, final Entity product) { boolean contains = false; for (Entity entity : components) { if (entity.getBelongsToField(L_PRODUCT).getId().equals(product.getId())) { contains = true; break; } } return contains; } private SearchCriteriaBuilder createSearchCriteria(final Entity product, final Entity technology, final ProductDirection direction) { String model = direction.equals(ProductDirection.IN) ? TechnologiesConstants.MODEL_OPERATION_PRODUCT_IN_COMPONENT : TechnologiesConstants.MODEL_OPERATION_PRODUCT_OUT_COMPONENT; DataDefinition dd = dataDefinitionService.get(TechnologiesConstants.PLUGIN_IDENTIFIER, model); SearchCriteriaBuilder search = dd.find(); search.add(SearchRestrictions.eq("product.id", product.getId())); search.createAlias(L_OPERATION_COMPONENT, L_OPERATION_COMPONENT); search.add(SearchRestrictions.belongsTo("operationComponent.technology", technology)); return search; } public String getProductType(final Entity product, final Entity technology) { SearchCriteriaBuilder searchIns = createSearchCriteria(product, technology, ProductDirection.IN); SearchCriteriaBuilder searchOuts = createSearchCriteria(product, technology, ProductDirection.OUT); SearchCriteriaBuilder searchOutsForRoots = createSearchCriteria(product, technology, ProductDirection.OUT); searchOutsForRoots.add(SearchRestrictions.isNull("operationComponent.parent")); boolean goesIn = productComponentsContainProduct(searchIns.list().getEntities(), product); boolean goesOut = productComponentsContainProduct(searchOuts.list().getEntities(), product); boolean goesOutInAroot = productComponentsContainProduct(searchOutsForRoots.list().getEntities(), product); if (goesOutInAroot) { if (technology.getBelongsToField(L_PRODUCT).getId().equals(product.getId())) { return L_03_FINAL_PRODUCT; } else { return L_04_WASTE; } } if (goesIn && !goesOut) { return L_01_COMPONENT; } if (goesIn && goesOut) { return L_02_INTERMEDIATE; } if (!goesIn && goesOut) { return L_04_WASTE; } return L_00_UNRELATED; } public void switchStateToDraftOnCopy(final DataDefinition technologyDataDefinition, final Entity technology) { technology.setField(STATE, TechnologyState.DRAFT.getStringValue()); } public void addOperationsFromSubtechnologiesToList(final EntityTree entityTree, final List<Entity> operationComponents) { for (Entity operationComponent : entityTree) { if (L_OPERATION.equals(operationComponent.getField(L_ENTITY_TYPE))) { operationComponents.add(operationComponent); } else { addOperationsFromSubtechnologiesToList( operationComponent.getBelongsToField(L_REFERENCE_TECHNOLOGY).getTreeField(L_OPERATION_COMPONENTS), operationComponents); } } } public boolean invalidateIfAllreadyInTheSameOperation(final DataDefinition dataDefinition, final Entity operationProduct) { if (operationProduct.getId() == null) { Entity product = operationProduct.getBelongsToField(L_PRODUCT); Entity operationComponent = operationProduct.getBelongsToField(L_OPERATION_COMPONENT); String fieldName; if ("operationProductInComponent".equals(dataDefinition.getName())) { fieldName = L_OPERATION_PRODUCT_IN_COMPONENTS; } else { fieldName = L_OPERATION_PRODUCT_OUT_COMPONENTS; } EntityList products = operationComponent.getHasManyField(fieldName); if (product == null || product.getId() == null) { throw new IllegalStateException("Cant get product id"); } if (products != null && listContainsProduct(products, product)) { operationProduct.addError(dataDefinition.getField(L_PRODUCT), "technologyOperationComponent.validate.error.productAlreadyExistInTechnologyOperation"); return false; } } return true; } private boolean listContainsProduct(final EntityList list, final Entity product) { for (Entity prod : list) { if (prod.getBelongsToField(L_PRODUCT).getId().equals(product.getId())) { return true; } } return false; } /** * * @param operationComponent * @return productOutComponent. Assuming operation can have only one product/intermediate. */ public Entity getMainOutputProductComponent(Entity operationComponent) { if (L_REFERENCE_TECHNOLOGY.equals(operationComponent.getStringField(L_ENTITY_TYPE))) { operationComponent = operationComponent.getBelongsToField(L_REFERENCE_TECHNOLOGY) .getTreeField(L_OPERATION_COMPONENTS).getRoot(); } if (operationComponent.getDataDefinition().getName().equals("technologyInstanceOperationComponent")) { operationComponent = operationComponent.getBelongsToField("technologyOperationComponent"); } Entity parentOpComp = operationComponent.getBelongsToField(L_PARENT); List<Entity> prodOutComps = operationComponent.getHasManyField(L_OPERATION_PRODUCT_OUT_COMPONENTS); if (parentOpComp == null) { Entity technology = operationComponent.getBelongsToField(L_TECHNOLOGY); Entity product = technology.getBelongsToField(L_PRODUCT); for (Entity prodOutComp : prodOutComps) { if (prodOutComp.getBelongsToField(L_PRODUCT).getId().equals(product.getId())) { return prodOutComp; } } } else { List<Entity> prodInComps = parentOpComp.getHasManyField(L_OPERATION_PRODUCT_IN_COMPONENTS); for (Entity prodOutComp : prodOutComps) { for (Entity prodInComp : prodInComps) { if (prodOutComp.getBelongsToField(L_PRODUCT).getId().equals(prodInComp.getBelongsToField(L_PRODUCT).getId())) { return prodOutComp; } } } } throw new IllegalStateException("OperationComponent doesn't have any products nor intermediates, id = " + operationComponent.getId()); } /** * * @param operationComponent * @return Quantity of the output product associated with this operationComponent. Assuming operation can have only one * product/intermediate. */ public BigDecimal getProductCountForOperationComponent(final Entity operationComponent) { return getMainOutputProductComponent(operationComponent).getDecimalField(L_QUANTITY); } }
false
false
null
null
diff --git a/src/main/java/org/vertx/java/deploy/impl/jruby/JRubyVerticle.java b/src/main/java/org/vertx/java/deploy/impl/jruby/JRubyVerticle.java index 23b7a26..9d6e224 100644 --- a/src/main/java/org/vertx/java/deploy/impl/jruby/JRubyVerticle.java +++ b/src/main/java/org/vertx/java/deploy/impl/jruby/JRubyVerticle.java @@ -1,95 +1,97 @@ /* * Copyright 2011-2012 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.vertx.java.deploy.impl.jruby; import org.jruby.embed.InvokeFailedException; import org.jruby.embed.LocalContextScope; import org.jruby.embed.ScriptingContainer; import org.jruby.exceptions.RaiseException; +import org.jruby.CompatVersion; import org.vertx.java.core.logging.Logger; import org.vertx.java.core.logging.impl.LoggerFactory; import org.vertx.java.deploy.Verticle; import java.io.IOException; import java.io.InputStream; import java.io.Writer; /** * @author <a href="http://tfox.org">Tim Fox</a> */ public class JRubyVerticle extends Verticle { private static final Logger log = LoggerFactory.getLogger(JRubyVerticle.class); private final ScriptingContainer container; private final ClassLoader cl; private final String scriptName; JRubyVerticle(String scriptName, ClassLoader cl) { this.container = new ScriptingContainer(LocalContextScope.SINGLETHREAD); + container.setCompatVersion(CompatVersion.RUBY1_8); container.setClassLoader(cl); //Prevent JRuby from logging errors to stderr - we want to log ourselves container.setErrorWriter(new NullWriter()); this.cl = cl; this.scriptName = scriptName; } public void start() throws Exception { InputStream is = cl.getResourceAsStream(scriptName); if (is == null) { throw new IllegalArgumentException("Cannot find verticle: " + scriptName); } // Inject vertx as a variable in the script container.runScriptlet(is, scriptName); try { is.close(); } catch (IOException ignore) { } } public void stop() throws Exception { try { // We call the script with receiver = null - this causes the method to be called on the top level // script container.callMethod(null, "vertx_stop"); } catch (InvokeFailedException e) { Throwable cause = e.getCause(); if (cause instanceof RaiseException) { // Gosh, this is a bit long winded! RaiseException re = (RaiseException)cause; String msg = "(NoMethodError) undefined method `vertx_stop'"; if (re.getMessage().startsWith(msg)) { // OK - method is not mandatory return; } } throw e; } } private class NullWriter extends Writer { public void write(char[] cbuf, int off, int len) throws IOException { } public void flush() throws IOException { } public void close() throws IOException { } } }
false
false
null
null
diff --git a/easyb/src/java/org/disco/easyb/BehaviorRunner.java b/easyb/src/java/org/disco/easyb/BehaviorRunner.java index ca079c2..ef94957 100644 --- a/easyb/src/java/org/disco/easyb/BehaviorRunner.java +++ b/easyb/src/java/org/disco/easyb/BehaviorRunner.java @@ -1,109 +1,111 @@ package org.disco.easyb; import java.io.File; import java.util.ArrayList; import java.util.List; import org.disco.easyb.domain.Behavior; import org.disco.easyb.domain.BehaviorFactory; import org.disco.easyb.domain.GroovyShellConfiguration; import org.disco.easyb.listener.BroadcastListener; import org.disco.easyb.listener.ExecutionListener; import org.disco.easyb.listener.FailureDetector; import org.disco.easyb.listener.ResultsCollector; import org.disco.easyb.report.ReportWriter; import org.disco.easyb.exception.VerificationException; public class BehaviorRunner { private List<ReportWriter> reports; private BroadcastListener broadcastListener = new BroadcastListener(); private ResultsCollector resultsCollector = new ResultsCollector(); private FailureDetector failureDetector = new FailureDetector(); public BehaviorRunner(ExecutionListener... listeners) { this(null, listeners); } public BehaviorRunner(List<ReportWriter> reports, ExecutionListener... listeners) { this.reports = reports; broadcastListener.registerListener(resultsCollector); broadcastListener.registerListener(failureDetector); for (ExecutionListener listener : listeners) { broadcastListener.registerListener(listener); } } /** * @param args the command line arguments * usage is: * <p/> * java BehaviorRunner my/path/to/spec/MyStory.groovy -txtstory ./reports/story-report.txt * <p/> * You don't need to pass in the file name for the report either-- if no * path is present, then the runner will create a report in the current directory - * with a default filename following this convention: easyb-<type>-report.<format> + * with a default filename following this convention: + * easyb-<type>-report.<format> (for reports of either story or specification) + * easyb-report.<format> (for reports that contain both) * <p/> * Multiple specifications can be passed in on the command line * <p/> * java BehaviorRunner my/path/to/spec/MyStory.groovy my/path/to/spec/AnotherStory.groovy */ public static void main(String[] args) { Configuration configuration = new ConsoleConfigurator().configure(args); if (configuration != null) { BehaviorRunner runner = new BehaviorRunner(configuration.configuredReports, new ConsoleReporter()); try { runner.runBehavior(getBehaviors(configuration.commandLine.getArgs())); } catch (VerificationException e) { System.exit(-6); } catch (Exception e) { System.err.println("There was an error running your easyb story or specification"); e.printStackTrace(System.err); System.exit(-6); } } } /** * @param behaviors collection of files that contain the specifications * @throws Exception if unable to write report file */ public void runBehavior(List<Behavior> behaviors) throws Exception { for (Behavior behavior : behaviors) { behavior.execute(broadcastListener); } broadcastListener.completeTesting(); for (ReportWriter report : reports) { report.writeReport(resultsCollector); } if (failureDetector.failuresDetected()) { throw new VerificationException("There were specification failures"); } } public static List<Behavior> getBehaviors(GroovyShellConfiguration groovyShellConfiguration, String[] paths) { List<Behavior> behaviors = new ArrayList<Behavior>(); for (String path : paths) { try { behaviors.add(BehaviorFactory.createBehavior(groovyShellConfiguration, new File(path))); } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); System.exit(-1); } } return behaviors; } /** * @param paths locations of the specifications to be loaded * @return collection of files where the only element is the file of the spec to be run */ public static List<Behavior> getBehaviors(String[] paths) { return getBehaviors(BehaviorFactory.DEFAULT_GROOVY_SHELL_CONFIG, paths); } }
true
false
null
null
diff --git a/lib/src/main/java/com/github/fhirschmann/clozegen/lib/generators/DummyGapGenerator.java b/lib/src/main/java/com/github/fhirschmann/clozegen/lib/generators/DummyGapGenerator.java index e5b1d72..4e0258a 100644 --- a/lib/src/main/java/com/github/fhirschmann/clozegen/lib/generators/DummyGapGenerator.java +++ b/lib/src/main/java/com/github/fhirschmann/clozegen/lib/generators/DummyGapGenerator.java @@ -1,41 +1,42 @@ /* * Copyright (C) 2012 Fabian Hirschmann <[email protected]> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package com.github.fhirschmann.clozegen.lib.generators; import com.github.fhirschmann.clozegen.lib.generators.api.Gap; import com.github.fhirschmann.clozegen.lib.generators.api.SingleTokenInputGapGenerator; +import com.google.common.base.Optional; /** * Creates a gap with no invalid answers. * * @author Fabian Hirschmann <[email protected]> */ public class DummyGapGenerator implements SingleTokenInputGapGenerator { /** The valid answer for this gap. */ private String validAnswer; @Override public void initialize(final String token) { this.validAnswer = token; } @Override - public Gap generate(final int count) { - return Gap.with(validAnswer); + public Optional<Gap> generate(final int count) { + return Optional.of(Gap.with(validAnswer)); } } diff --git a/lib/src/main/java/com/github/fhirschmann/clozegen/lib/generators/StupidArticleGapGenerator.java b/lib/src/main/java/com/github/fhirschmann/clozegen/lib/generators/StupidArticleGapGenerator.java index 4922353..4e7d094 100644 --- a/lib/src/main/java/com/github/fhirschmann/clozegen/lib/generators/StupidArticleGapGenerator.java +++ b/lib/src/main/java/com/github/fhirschmann/clozegen/lib/generators/StupidArticleGapGenerator.java @@ -1,43 +1,44 @@ /* * Copyright (C) 2012 Fabian Hirschmann <[email protected]> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package com.github.fhirschmann.clozegen.lib.generators; import com.github.fhirschmann.clozegen.lib.generators.api.Gap; import com.github.fhirschmann.clozegen.lib.generators.api.SingleTokenInputGapGenerator; +import com.google.common.base.Optional; /** * This is a sample implementation of a generator for gaps for articles. This * is only for demonstration purposes! * * @author Fabian Hirschmann <[email protected]> */ public class StupidArticleGapGenerator implements SingleTokenInputGapGenerator { /** The valid answer for this gap. */ private String validAnswer; @Override public void initialize(String token) { this.validAnswer = token; } @Override - public Gap generate(final int count) { - return Gap.with(validAnswer, "a", "an", "the"); + public Optional<Gap> generate(final int count) { + return Optional.of(Gap.with(validAnswer, "a", "an", "the")); } }
false
false
null
null
diff --git a/jadx-gui/src/main/java/jadx/gui/MainWindow.java b/jadx-gui/src/main/java/jadx/gui/MainWindow.java index 481315c4..a171ab1c 100644 --- a/jadx-gui/src/main/java/jadx/gui/MainWindow.java +++ b/jadx-gui/src/main/java/jadx/gui/MainWindow.java @@ -1,228 +1,232 @@ package jadx.gui; import jadx.cli.JadxArgs; +import jadx.gui.treemodel.JClass; import jadx.gui.treemodel.JNode; import jadx.gui.treemodel.JRoot; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JToggleButton; import javax.swing.JToolBar; import javax.swing.JTree; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.filechooser.FileFilter; import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.text.BadLocationException; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeSelectionModel; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.io.File; import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; import org.fife.ui.rsyntaxtextarea.SyntaxConstants; import org.fife.ui.rtextarea.RTextScrollPane; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MainWindow extends JFrame { private static final Logger LOG = LoggerFactory.getLogger(MainWindow.class); private static final String DEFAULT_TITLE = "jadx-gui"; private static final Color BACKGROUND = new Color(0xf7f7f7); private static final ImageIcon ICON_OPEN = Utils.openIcon("folder"); private static final ImageIcon ICON_CLOSE = Utils.openIcon("cross"); private static final ImageIcon ICON_FLAT_PKG = Utils.openIcon("empty_logical_package_obj"); private final JadxWrapper wrapper; private JPanel mainPanel; private JTree tree; private DefaultTreeModel treeModel; private RSyntaxTextArea textArea; public MainWindow(JadxArgs jadxArgs) { this.wrapper = new JadxWrapper(jadxArgs); initUI(); initMenuAndToolbar(); } public void openFile(File file) { wrapper.openFile(file); initTree(); setTitle(DEFAULT_TITLE + " - " + file.getName()); } private void initTree() { JRoot treeRoot = new JRoot(wrapper); treeModel.setRoot(treeRoot); treeModel.reload(); tree.expandRow(0); } private void toggleFlattenPackage() { Object root = treeModel.getRoot(); if (root instanceof JRoot) { JRoot treeRoot = (JRoot) root; treeRoot.setFlatPackages(!treeRoot.isFlatPackages()); treeModel.reload(); tree.expandRow(0); } } private void treeClickAction() { Object obj = tree.getLastSelectedPathComponent(); if (obj instanceof JNode) { JNode node = (JNode) obj; if (node.getJParent() != null) { textArea.setText(node.getJParent().getCode()); scrollToLine(node.getLine()); + } else if (node.getClass() == JClass.class){ + textArea.setText(((JClass)node).getCode()); + scrollToLine(node.getLine()); } } } private void scrollToLine(int line) { if (line < 2) { return; } try { textArea.setCaretPosition(textArea.getLineStartOffset(line - 1)); } catch (BadLocationException e) { LOG.error("Can't scroll to " + line, e); } } private void initMenuAndToolbar() { JMenuBar menuBar = new JMenuBar(); JMenu file = new JMenu("File"); file.setMnemonic(KeyEvent.VK_F); JMenuItem exit = new JMenuItem("Exit", ICON_CLOSE); exit.setMnemonic(KeyEvent.VK_E); exit.setToolTipText("Exit application"); exit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { System.exit(0); } }); JMenuItem open = new JMenuItem("Open", ICON_OPEN); open.setMnemonic(KeyEvent.VK_E); open.setToolTipText("Open file"); open.addActionListener(new OpenListener()); file.add(open); file.addSeparator(); file.add(exit); menuBar.add(file); setJMenuBar(menuBar); JToolBar toolbar = new JToolBar(); toolbar.setFloatable(false); JButton openButton = new JButton(ICON_OPEN); openButton.addActionListener(new OpenListener()); openButton.setToolTipText(NLS.str("file.open")); toolbar.add(openButton); toolbar.addSeparator(); JToggleButton flatPkgButton = new JToggleButton(ICON_FLAT_PKG); flatPkgButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { toggleFlattenPackage(); } }); flatPkgButton.setToolTipText(NLS.str("tree.flatten")); toolbar.add(flatPkgButton); toolbar.addSeparator(); add(toolbar, BorderLayout.NORTH); } private void initUI() { mainPanel = new JPanel(new BorderLayout()); JSplitPane splitPane = new JSplitPane(); mainPanel.add(splitPane); DefaultMutableTreeNode treeRoot = new DefaultMutableTreeNode("Please open file"); treeModel = new DefaultTreeModel(treeRoot); tree = new JTree(treeModel); // tree.setRootVisible(false); // tree.setBackground(BACKGROUND); tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); tree.addTreeSelectionListener(new TreeSelectionListener() { @Override public void valueChanged(TreeSelectionEvent event) { treeClickAction(); } }); tree.setCellRenderer(new DefaultTreeCellRenderer() { @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean isLeaf, int row, boolean focused) { Component c = super.getTreeCellRendererComponent(tree, value, selected, expanded, isLeaf, row, focused); if (value instanceof JNode) { setIcon(((JNode) value).getIcon()); } return c; } }); JScrollPane treeScrollPane = new JScrollPane(tree); splitPane.setLeftComponent(treeScrollPane); textArea = new RSyntaxTextArea(20, 60); textArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_JAVA); textArea.setMarkOccurrences(true); textArea.setBackground(BACKGROUND); textArea.setCodeFoldingEnabled(true); textArea.setAntiAliasingEnabled(true); // textArea.setHyperlinksEnabled(true); textArea.setTabSize(4); RTextScrollPane scrollPane = new RTextScrollPane(textArea); scrollPane.setFoldIndicatorEnabled(true); splitPane.setRightComponent(scrollPane); setContentPane(mainPanel); setTitle(DEFAULT_TITLE); setDefaultCloseOperation(DISPOSE_ON_CLOSE); pack(); setLocationRelativeTo(null); } private class OpenListener implements ActionListener { public void actionPerformed(ActionEvent event) { JFileChooser fileChooser = new JFileChooser(); FileFilter filter = new FileNameExtensionFilter("dex files", "dex", "apk", "jar"); fileChooser.addChoosableFileFilter(filter); int ret = fileChooser.showDialog(mainPanel, "Open file"); if (ret == JFileChooser.APPROVE_OPTION) { File file = fileChooser.getSelectedFile(); openFile(file); } } } }
false
false
null
null
diff --git a/src/java/com/scriptographer/ai/TextItem.java b/src/java/com/scriptographer/ai/TextItem.java index a141cb48..6c993e74 100644 --- a/src/java/com/scriptographer/ai/TextItem.java +++ b/src/java/com/scriptographer/ai/TextItem.java @@ -1,385 +1,383 @@ /* * Scriptographer * * This file is part of Scriptographer, a Plugin for Adobe Illustrator. * * Copyright (c) 2002-2010 Juerg Lehni, http://www.scratchdisk.com. * All rights reserved. * * Please visit http://scriptographer.org/ for updates and contact. * * -- GPL LICENSE NOTICE -- * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * -- GPL LICENSE NOTICE -- * * File created on 23.10.2005. * * $Id$ */ package com.scriptographer.ai; import com.scratchdisk.list.ReadOnlyList; import com.scratchdisk.util.IntegerEnumUtils; import com.scriptographer.CommitManager; -import com.scriptographer.ai.TextRange.CharacterList; -import com.scriptographer.ai.TextRange.TokenizerList; /** * The TextItem type allows you to access and modify the text items in * Illustrator documents. Its functionality is inherited by different text item * types such as {@link PointText}, {@link PathText} and {@link AreaText}. They * each add a layer of functionality that is unique to their type, but share the * underlying properties and functions that they inherit from TextItem. * * @author lehni */ public abstract class TextItem extends Item { // AITextType protected static final short TEXTTYPE_UNKNOWN = -1, TEXTTYPE_POINT = 0, TEXTTYPE_AREA = 1, TEXTTYPE_PATH = 2; TextRange range = null; TextRange visibleRange = null; protected TextItem(int handle, int docHandle, boolean created) { super(handle, docHandle, created); } protected TextItem(int handle) { super(handle); } protected void commit(boolean invalidate) { CommitManager.commit(getStory()); super.commit(invalidate); } private native int nativeGetOrientation(); private native void nativeSetOrientation(int orientation); /** * The orientation of the text in the text frame. */ public TextOrientation getOrientation() { return (TextOrientation) IntegerEnumUtils.get(TextOrientation.class, nativeGetOrientation()); } public void setOrientation(TextOrientation orientation) { nativeSetOrientation(orientation.value); } /** * The padding within the text area. */ public native float getSpacing(); public native void setSpacing(float spacing); /** * Specifies whether to use optical alignment within the text frame. Optical * alignment hangs punctuation outside the edges of a text frame. * * @return {@true if the text frame uses optical alignment} */ public native boolean getOpticalAlignment(); public native void setOpticalAlignment(boolean active); // TODO: // AIAPI AIErr (*DoTextFrameHit) ( const AIHitRef hitRef, TextRangeRef* textRange ); private native Item nativeCreateOutline(); /** * Converts the text in the text frame to outlines. Unlike the Illustrator * 'Create Outlines' action, this won't remove the text frame. * * @return a {@link Group} item containing the outlined text as {@link Path} * and {@link CompoundPath} items. */ public Item createOutline() { // Apply changes and reflow the layout before creating outlines // All styles regarding this story need to be committed, as // CharacterStyle uses Story as the commit key. CommitManager.commit(this.getStory()); // This should not be needed since TextRange takes care of it // when committing already: // document.reflowText(); return nativeCreateOutline(); } /** * {@grouptitle Text Frame Linking} * * Links the supplied text frame to this one. * * @param next The text frame that will be linked * @return {@true if the text frame was linked} */ public native boolean link(TextItem next); /** * Returns {@true if the text frame is linked} */ public native boolean isLinked(); private native boolean nativeUnlink(boolean before, boolean after); /** * Unlinks the text frame from its current story. * * @return {@true if the operation as successful} */ public boolean unlink() { return nativeUnlink(true, true); } /** * Unlinks the text frame from its current story and breaks up the story * into two parts before the text frame. * * @return {@true if the operation as successful} */ public boolean unlinkBefore() { return nativeUnlink(true, false); } /** * Unlinks the text frame from its current story and breaks up the story * into two parts after the text frame. * * @return {@true if the operation as successful} */ public boolean unlinkAfter() { return nativeUnlink(false, true); } /** * {@grouptitle Hierarchy} * * Returns the index of the text frame in its {@link TextItem#getStory()}. */ public native int getIndex(); /** * Returns this text frame's story's index in the document's stories array. */ private native int getStoryIndex(); /** * Returns the story that the text frame belongs to. */ public TextStory getStory() { // don't wrap directly. always go through StoryList // to make sure we're not getting more than one reference // to the same Story, so things can be cached there: int index = getStoryIndex(); ReadOnlyList list = document.getStories(); if (index >= 0 && index < list.size()) return (TextStory) list.get(index); return null; } private TextItem getFrame(int index) { TextStory story = getStory(); if (story != null) { ReadOnlyList list = story.getTextFrames(); if (index >= 0 && index < list.size()) return (TextItem) list.get(index); } return null; } /** * Returns the next text frame in a story of various linked text frames. */ public TextItem getNextFrame() { return getFrame(getIndex() + 1); } /** * Returns the previous text frame in a story of various linked text frames. */ public TextItem getPreviousFrame() { return getFrame(getIndex() - 1); } // ATE /** * {@grouptitle Range Properties} * * The text contents of the text item. */ public String getContent() { return getRange().getContent(); } public void setContent(String text) { getRange().setContent(text); } /** * @jshide */ public native int nativeGetRange(boolean includeOverflow); /** * Returns a text range for all the characters, even the invisible ones * outside the container. */ public TextRange getRange() { // once a range object is created, always return the same reference // and swap handles instead. like this references in JS remain... if (range == null) { range = new TextRange(nativeGetRange(true), document); } else if (range.version != CommitManager.version) { range.changeHandle(nativeGetRange(true)); } return range; } /** * In case there's an overflow in the text, this only returns a range over * the visible characters, while {@link TextItem#getRange()} returns one * over the whole text. */ public TextRange getVisibleRange() { // once a range object is created, always return the same reference // and swap handles instead. like this references in JS remain... if (visibleRange == null) { visibleRange = new TextRange(nativeGetRange(false), document); } else if (visibleRange.version != CommitManager.version) { visibleRange.changeHandle(nativeGetRange(false)); } return visibleRange; } /** * Returns the selected text of the text frame as a text range. */ public native TextRange getSelection(); /** * Returns the index of the first visible character of the text frame. (this * is the equivalent of calling TextFrame.visibleRange.start) */ public int getStart() { return getVisibleRange().getStart(); } /** * Returns the index of the last visible character of the text frame. (this * is the equivalent of calling TextFrame.visibleRange.end) */ public int getEnd() { return getVisibleRange().getEnd(); } /** * {@grouptitle Sub Ranges} * * The text ranges of the words contained within the text item. Note that * the returned text range includes the trailing whitespace characters of * the words. * * Sample code: * <code> * var text = new PointText(new Point(0,0)); * text.content = 'The contents of the point text.'; * var word = text.words[1]; * print(word.content) // 'contents ' - note the space after 'contents'; * </code> */ public ReadOnlyList<TextRange> getWords() { return getRange().getWords(); } /** * The text ranges of the paragraphs contained within the text item. Note * that the returned text range includes the trailing paragraph (\r) * characters of the paragraphs. * * Sample code: * <code> * var text = new PointText(new Point(0,0)); * * // ('\r' is the escaped character that specifies a new paragraph) * text.content = 'First paragraph\rSecond paragraph'; * var paragraph = text.paragraphs[1]; * print(paragraph.content) //returns 'Second paragraph'; * </code> */ public ReadOnlyList<TextRange> getParagraphs() { return getRange().getParagraphs(); } /** * The text ranges of the characters contained within the text item. * * Sample code: * <code> * var text = new PointText(new Point(0,0)); * text.content = 'abc'; * var character = text.characters[1]; * print(character.content) //returns 'b'; * </code> */ public ReadOnlyList<TextRange> getCharacters() { return getRange().getCharacters(); } /** * {@grouptitle Style Properties} * * The character style of the text frame. */ public CharacterStyle getCharacterStyle() { return getRange().getCharacterStyle(); } public void setCharacterStyle(CharacterStyle style) { getRange().setCharacterStyle(style); } /** * The paragraph style of the text frame. */ public ParagraphStyle getParagraphStyle() { return getRange().getParagraphStyle(); } public void setParagraphStyle(ParagraphStyle style) { getRange().setParagraphStyle(style); } public native boolean equals(Object obj); // TODO: // ATEErr (*GetTextLinesIterator) ( TextFrameRef textframe, TextLinesIteratorRef* ret); // ATEErr (*GetLineOrientation) ( TextFrameRef textframe, LineOrientation* ret); // ATEErr (*SetLineOrientation) ( TextFrameRef textframe, LineOrientation lineOrientation); /* Check if this frame is selected. To set the selection, you have to use application specific API for that. In Illustrator case, you can use AIArtSuite to set the selection. */ } \ No newline at end of file diff --git a/src/java/com/scriptographer/ai/ToolEvent.java b/src/java/com/scriptographer/ai/ToolEvent.java index 29df5586..9bc644ae 100644 --- a/src/java/com/scriptographer/ai/ToolEvent.java +++ b/src/java/com/scriptographer/ai/ToolEvent.java @@ -1,259 +1,259 @@ /* * Scriptographer * * This file is part of Scriptographer, a Plugin for Adobe Illustrator. * * Copyright (c) 2002-2010 Juerg Lehni, http://www.scratchdisk.com. * All rights reserved. * * Please visit http://scriptographer.org/ for updates and contact. * * -- GPL LICENSE NOTICE -- * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * -- GPL LICENSE NOTICE -- * * File created on 21.12.2004. * * $Id$ */ package com.scriptographer.ai; import com.scriptographer.script.EnumUtils; import com.scriptographer.sg.Event; /** * The ToolEvent object is received by the {@link Tool}'s mouse event handlers * {@link Tool#getOnMouseDown()}, {@link Tool#getOnMouseDrag()}, * {@link Tool#getOnMouseMove()} and {@link Tool#getOnMouseUp()}. The ToolEvent * object is the only parameter passed to these functions and contains * information about the mouse event. * * Sample code: * <code> * function onMouseUp(event) { * // the position of the mouse when it is released * print(event.point); * } * </code> * * @author lehni */ public class ToolEvent extends Event { private ToolEventHandler tool; private ToolEventType type; private Point point = null; private Point lastPoint = null; private Point downPoint = null; private Point middlePoint = null; private Point delta = null; private double pressure = -1; protected ToolEvent(ToolEventHandler tool, ToolEventType type, int modifiers) { super(modifiers); this.tool = tool; this.type = type; } public String toString() { StringBuffer buf = new StringBuffer(16); buf.append("{ type: ").append(EnumUtils.getScriptName(type)); - buf.append(", point: ").append(point); - buf.append(", pressure: ").append(pressure); + buf.append(", point: ").append(getPoint()); + buf.append(", pressure: ").append(getPressure()); buf.append(", count: ").append(getCount()); buf.append(", modifiers: ").append(getModifiers()); buf.append(" }"); return buf.toString(); } private Point getPoint(Point point, Point toolPoint) { if (point != null) return point; if (toolPoint != null) return new Point(toolPoint); return null; } /** * The position of the mouse in document coordinates when the event was * fired. * * Sample code: * <code> * function onMouseDrag(event) { * // the position of the mouse when it is dragged * print(event.point); * } * * function onMouseUp(event) { * // the position of the mouse when it is released * print(event.point); * } * </code> */ public Point getPoint() { return getPoint(point, tool.point); } public void setPoint(Point point) { this.point = point; } /** * The position of the mouse in document coordinates when the previous * event was fired. */ public Point getLastPoint() { return getPoint(lastPoint, tool.lastPoint); } public void setLastPoint(Point lastPoint) { this.lastPoint = lastPoint; } /** * The position of the mouse in document coordinates when the mouse button * was last clicked. */ public Point getDownPoint() { return getPoint(downPoint, tool.downPoint); } public void setDownPoint(Point downPoint) { this.downPoint = downPoint; } /** * The point in the middle between {@link #getLastPoint()} and * {@link #getPoint()}. This is a useful position to use when creating * artwork based on the moving direction of the mouse, as returned by * {@link #getDelta()}. */ public Point getMiddlePoint() { // For explanations, see getDelta() if (middlePoint == null && tool.lastPoint != null) return tool.point.add(tool.lastPoint).divide(2); return middlePoint; } public void setMiddlePoint(Point middlePoint) { this.middlePoint = middlePoint; } /** * The difference between the current position and the last position of the * mouse when the event was fired. In case of the mouse-up event, the * difference to the mouse-down position is returned. */ public Point getDelta() { // Do not put the calculated delta into delta, since this only reserved // for overriding event.delta. // Instead, keep calculating the delta each time, so the result can be // directly modified by the script without changing the internal values. // We could cache this and use clone, but this is almost as fast... if (delta == null && tool.lastPoint != null) return tool.point.subtract(tool.lastPoint); return delta; } public void setDelta(Point delta) { this.delta = delta; } /** * The amount of force being applied by a pressure-sensitive input device, * such as a graphic tablet. * * @return the pressure as a value between 0 and 1 */ public double getPressure() { return pressure != -1 ? pressure : tool.pressure; } public void setPressure(double pressure) { this.pressure = pressure; } /** * The number of times the mouse event was fired. * * Sample code: * <code> * function onMouseDrag(event) { * // the amount of times the onMouseDrag event was fired * // since the last onMouseDown event * print(event.count); * } * * function onMouseUp(event) { * // the amount of times the onMouseUp event was fired * // since the tool was activated * print(event.point); * } * </code> */ public int getCount() { switch (type) { case MOUSE_DOWN: case MOUSE_UP: // Return downCount for both mouse down and up, since // the count is the same. return tool.downCount; default: return tool.count; } } public void setCount(int count) { switch (type) { case MOUSE_DOWN: case MOUSE_UP: tool.downCount = count; break; default: tool.count = count; break; } } public ToolEventType getType() { return type; } public void setType(ToolEventType type) { this.type = type; } // TODO: Consider adding these, present since CS2 /* * For graphic tablets, tangential pressure on the finger wheel of the * airbrush tool. */ // AIToolPressure stylusWheel; /* * How the tool is angled, also called altitude or elevation. */ // AIToolAngle tilt; /* * The direction of tilt, measured clockwise in degrees around the Z axis, * also called azimuth, */ // AIToolAngle bearing; /* * Rotation of the tool, measured clockwise in degrees around the tool's * barrel. */ // AIToolAngle rotation; }
false
false
null
null
diff --git a/eu/icecraft/iceban/commands/BanCommands.java b/eu/icecraft/iceban/commands/BanCommands.java index 8dc789a..a8c3c56 100644 --- a/eu/icecraft/iceban/commands/BanCommands.java +++ b/eu/icecraft/iceban/commands/BanCommands.java @@ -1,130 +1,130 @@ package eu.icecraft.iceban.commands; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import eu.icecraft.iceban.BanInfo; import eu.icecraft.iceban.BanInfo.BanType; import eu.icecraft.iceban.IceBan; import eu.icecraft.iceban.Utils; public class BanCommands implements CommandExecutor { public IceBan plugin; public Pattern timePattern; public BanCommands(IceBan iceBan) { this.plugin = iceBan; timePattern = Pattern.compile("^(.+?) (.+?) \\-t (.+?)$"); } @Override public boolean onCommand(CommandSender sender, Command cmd, String cmdLbl, String[] args) { if(!sender.hasPermission("iceban." + cmdLbl)) return false; if(cmdLbl.equals("ban") || cmdLbl.equals("sbh")) { boolean forceBan = false; boolean permanent = false; boolean silent = false; String nick = ""; String reason = ""; String time = ""; String allArgs = ""; for (String word : args) { if(word.equals("-f")) { forceBan = true; continue; } if(word.equals("-p")) { permanent = true; continue; } if(word.equals("-s")) { silent = true; continue; } allArgs = allArgs + " " + word; } Matcher m = timePattern.matcher(allArgs); if (m.find() && !permanent) { nick = m.group(1).trim(); // nick reason = m.group(2).trim(); // reason time = m.group(3).trim(); // time } else { nick = args[0]; int i = 0; for (String word : args) { i++; if(i == 1 || word.equals("-f") || word.equals("-p") || word.equals("-s")) continue; reason = reason + " " + word; } reason = reason.trim(); if(!sender.hasPermission("iceban.longbans")) time = "1d"; else time = "30d"; } int banTime; if(sender.hasPermission("iceban.permabans") && permanent) banTime = 0; else { banTime = Utils.parseTimeSpec(time.trim()) * 60; if(banTime < 0) { sender.sendMessage(ChatColor.RED + "Invalid time string!"); return true; } if(!sender.hasPermission("iceban.longbans") && banTime > 86400) { - sender.sendMessage(ChatColor.RED + "Ban lenght was above your limit, setting to 1 day"); + sender.sendMessage(ChatColor.RED + "Ban length was above your limit, setting to 1 day"); banTime = 86400; } banTime += (int) (System.currentTimeMillis() / 1000L); } if(reason.equals("") || reason.startsWith("-t") || reason.startsWith("-s") || reason.startsWith("-f") || reason.startsWith("-p")) { sender.sendMessage(ChatColor.RED + "Invalid reason."); return true; } String ip = plugin.iceAuth.getIP(nick); if(ip == null && !forceBan) { sender.sendMessage(ChatColor.RED + "Player IP not found in history! Use -f to override"); return true; } BanInfo oldBan = plugin.getNameBan(nick.toLowerCase()); if(oldBan.getBanType() != BanType.NOT_BANNED) { sender.sendMessage(ChatColor.RED + "Player has previous active bans, marking them as past."); plugin.unban(oldBan); } plugin.sql.ban(nick, ip, banTime, reason, sender.getName()); BanInfo newBan = plugin.getNameBan(nick.toLowerCase()); for(Player currPlayer : Bukkit.getServer().getOnlinePlayers()) { if(currPlayer.getName().equalsIgnoreCase(nick)) currPlayer.kickPlayer(plugin.getKickMessage(newBan)); - if(!silent || !currPlayer.isOp()) sender.sendMessage(ChatColor.RED + "IceBan: " + ChatColor.AQUA + nick + " was banned by " + sender.getName()); + if(!silent || !currPlayer.isOp()) currPlayer.sendMessage(ChatColor.RED + "IceBan: " + ChatColor.AQUA + nick + " was banned by " + sender.getName()); } System.out.println(sender.getName() + " banned " + nick + " with reason " + reason + " for " + (permanent ? "a long time" : time) + " ban id: " + newBan.getBanID()); sender.sendMessage(ChatColor.GREEN + "Banned " + nick + " with reason " + reason + " for " + (permanent ? "a long time" : time) + " ban id: " + newBan.getBanID()); return true; } if(cmdLbl.equals("unban") || cmdLbl.equals("sunban")) { BanInfo ban = plugin.getNameBan(args[0]); if(ban.isNameBanned()) { plugin.unban(ban); sender.sendMessage(ChatColor.GOLD + "Player " + ChatColor.GRAY + args[0] + ChatColor.GOLD + " unbanned sucessfully."); } else { sender.sendMessage(ChatColor.GOLD + "Player " + ChatColor.GRAY + args[0] + ChatColor.GOLD + " isn't banned."); } return true; } return false; } }
false
true
public boolean onCommand(CommandSender sender, Command cmd, String cmdLbl, String[] args) { if(!sender.hasPermission("iceban." + cmdLbl)) return false; if(cmdLbl.equals("ban") || cmdLbl.equals("sbh")) { boolean forceBan = false; boolean permanent = false; boolean silent = false; String nick = ""; String reason = ""; String time = ""; String allArgs = ""; for (String word : args) { if(word.equals("-f")) { forceBan = true; continue; } if(word.equals("-p")) { permanent = true; continue; } if(word.equals("-s")) { silent = true; continue; } allArgs = allArgs + " " + word; } Matcher m = timePattern.matcher(allArgs); if (m.find() && !permanent) { nick = m.group(1).trim(); // nick reason = m.group(2).trim(); // reason time = m.group(3).trim(); // time } else { nick = args[0]; int i = 0; for (String word : args) { i++; if(i == 1 || word.equals("-f") || word.equals("-p") || word.equals("-s")) continue; reason = reason + " " + word; } reason = reason.trim(); if(!sender.hasPermission("iceban.longbans")) time = "1d"; else time = "30d"; } int banTime; if(sender.hasPermission("iceban.permabans") && permanent) banTime = 0; else { banTime = Utils.parseTimeSpec(time.trim()) * 60; if(banTime < 0) { sender.sendMessage(ChatColor.RED + "Invalid time string!"); return true; } if(!sender.hasPermission("iceban.longbans") && banTime > 86400) { sender.sendMessage(ChatColor.RED + "Ban lenght was above your limit, setting to 1 day"); banTime = 86400; } banTime += (int) (System.currentTimeMillis() / 1000L); } if(reason.equals("") || reason.startsWith("-t") || reason.startsWith("-s") || reason.startsWith("-f") || reason.startsWith("-p")) { sender.sendMessage(ChatColor.RED + "Invalid reason."); return true; } String ip = plugin.iceAuth.getIP(nick); if(ip == null && !forceBan) { sender.sendMessage(ChatColor.RED + "Player IP not found in history! Use -f to override"); return true; } BanInfo oldBan = plugin.getNameBan(nick.toLowerCase()); if(oldBan.getBanType() != BanType.NOT_BANNED) { sender.sendMessage(ChatColor.RED + "Player has previous active bans, marking them as past."); plugin.unban(oldBan); } plugin.sql.ban(nick, ip, banTime, reason, sender.getName()); BanInfo newBan = plugin.getNameBan(nick.toLowerCase()); for(Player currPlayer : Bukkit.getServer().getOnlinePlayers()) { if(currPlayer.getName().equalsIgnoreCase(nick)) currPlayer.kickPlayer(plugin.getKickMessage(newBan)); if(!silent || !currPlayer.isOp()) sender.sendMessage(ChatColor.RED + "IceBan: " + ChatColor.AQUA + nick + " was banned by " + sender.getName()); } System.out.println(sender.getName() + " banned " + nick + " with reason " + reason + " for " + (permanent ? "a long time" : time) + " ban id: " + newBan.getBanID()); sender.sendMessage(ChatColor.GREEN + "Banned " + nick + " with reason " + reason + " for " + (permanent ? "a long time" : time) + " ban id: " + newBan.getBanID()); return true; } if(cmdLbl.equals("unban") || cmdLbl.equals("sunban")) { BanInfo ban = plugin.getNameBan(args[0]); if(ban.isNameBanned()) { plugin.unban(ban); sender.sendMessage(ChatColor.GOLD + "Player " + ChatColor.GRAY + args[0] + ChatColor.GOLD + " unbanned sucessfully."); } else { sender.sendMessage(ChatColor.GOLD + "Player " + ChatColor.GRAY + args[0] + ChatColor.GOLD + " isn't banned."); } return true; } return false; }
public boolean onCommand(CommandSender sender, Command cmd, String cmdLbl, String[] args) { if(!sender.hasPermission("iceban." + cmdLbl)) return false; if(cmdLbl.equals("ban") || cmdLbl.equals("sbh")) { boolean forceBan = false; boolean permanent = false; boolean silent = false; String nick = ""; String reason = ""; String time = ""; String allArgs = ""; for (String word : args) { if(word.equals("-f")) { forceBan = true; continue; } if(word.equals("-p")) { permanent = true; continue; } if(word.equals("-s")) { silent = true; continue; } allArgs = allArgs + " " + word; } Matcher m = timePattern.matcher(allArgs); if (m.find() && !permanent) { nick = m.group(1).trim(); // nick reason = m.group(2).trim(); // reason time = m.group(3).trim(); // time } else { nick = args[0]; int i = 0; for (String word : args) { i++; if(i == 1 || word.equals("-f") || word.equals("-p") || word.equals("-s")) continue; reason = reason + " " + word; } reason = reason.trim(); if(!sender.hasPermission("iceban.longbans")) time = "1d"; else time = "30d"; } int banTime; if(sender.hasPermission("iceban.permabans") && permanent) banTime = 0; else { banTime = Utils.parseTimeSpec(time.trim()) * 60; if(banTime < 0) { sender.sendMessage(ChatColor.RED + "Invalid time string!"); return true; } if(!sender.hasPermission("iceban.longbans") && banTime > 86400) { sender.sendMessage(ChatColor.RED + "Ban length was above your limit, setting to 1 day"); banTime = 86400; } banTime += (int) (System.currentTimeMillis() / 1000L); } if(reason.equals("") || reason.startsWith("-t") || reason.startsWith("-s") || reason.startsWith("-f") || reason.startsWith("-p")) { sender.sendMessage(ChatColor.RED + "Invalid reason."); return true; } String ip = plugin.iceAuth.getIP(nick); if(ip == null && !forceBan) { sender.sendMessage(ChatColor.RED + "Player IP not found in history! Use -f to override"); return true; } BanInfo oldBan = plugin.getNameBan(nick.toLowerCase()); if(oldBan.getBanType() != BanType.NOT_BANNED) { sender.sendMessage(ChatColor.RED + "Player has previous active bans, marking them as past."); plugin.unban(oldBan); } plugin.sql.ban(nick, ip, banTime, reason, sender.getName()); BanInfo newBan = plugin.getNameBan(nick.toLowerCase()); for(Player currPlayer : Bukkit.getServer().getOnlinePlayers()) { if(currPlayer.getName().equalsIgnoreCase(nick)) currPlayer.kickPlayer(plugin.getKickMessage(newBan)); if(!silent || !currPlayer.isOp()) currPlayer.sendMessage(ChatColor.RED + "IceBan: " + ChatColor.AQUA + nick + " was banned by " + sender.getName()); } System.out.println(sender.getName() + " banned " + nick + " with reason " + reason + " for " + (permanent ? "a long time" : time) + " ban id: " + newBan.getBanID()); sender.sendMessage(ChatColor.GREEN + "Banned " + nick + " with reason " + reason + " for " + (permanent ? "a long time" : time) + " ban id: " + newBan.getBanID()); return true; } if(cmdLbl.equals("unban") || cmdLbl.equals("sunban")) { BanInfo ban = plugin.getNameBan(args[0]); if(ban.isNameBanned()) { plugin.unban(ban); sender.sendMessage(ChatColor.GOLD + "Player " + ChatColor.GRAY + args[0] + ChatColor.GOLD + " unbanned sucessfully."); } else { sender.sendMessage(ChatColor.GOLD + "Player " + ChatColor.GRAY + args[0] + ChatColor.GOLD + " isn't banned."); } return true; } return false; }
diff --git a/org.eclipse.scout.rt.client/src/org/eclipse/scout/rt/client/ui/basic/table/columnfilter/ColumnFilterForm.java b/org.eclipse.scout.rt.client/src/org/eclipse/scout/rt/client/ui/basic/table/columnfilter/ColumnFilterForm.java index 0c1e46361e..5f95b2c97c 100644 --- a/org.eclipse.scout.rt.client/src/org/eclipse/scout/rt/client/ui/basic/table/columnfilter/ColumnFilterForm.java +++ b/org.eclipse.scout.rt.client/src/org/eclipse/scout/rt/client/ui/basic/table/columnfilter/ColumnFilterForm.java @@ -1,573 +1,576 @@ /******************************************************************************* * Copyright (c) 2010 BSI Business Systems Integration AG. * 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: * BSI Business Systems Integration AG - initial API and implementation ******************************************************************************/ package org.eclipse.scout.rt.client.ui.basic.table.columnfilter; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; +import org.eclipse.scout.commons.HTMLUtility; +import org.eclipse.scout.commons.StringUtility; import org.eclipse.scout.commons.TypeCastUtility; import org.eclipse.scout.commons.annotations.Order; import org.eclipse.scout.commons.exception.ProcessingException; import org.eclipse.scout.rt.client.ui.basic.table.AbstractTable; import org.eclipse.scout.rt.client.ui.basic.table.ITableRow; import org.eclipse.scout.rt.client.ui.basic.table.TableRow; import org.eclipse.scout.rt.client.ui.basic.table.columnfilter.ColumnFilterForm.MainBox.CloseButton; import org.eclipse.scout.rt.client.ui.basic.table.columnfilter.ColumnFilterForm.MainBox.DateDetailBox; import org.eclipse.scout.rt.client.ui.basic.table.columnfilter.ColumnFilterForm.MainBox.DateDetailBox.DateSequenceBox.DateFromField; import org.eclipse.scout.rt.client.ui.basic.table.columnfilter.ColumnFilterForm.MainBox.DateDetailBox.DateSequenceBox.DateToField; import org.eclipse.scout.rt.client.ui.basic.table.columnfilter.ColumnFilterForm.MainBox.NumberDetailBox; import org.eclipse.scout.rt.client.ui.basic.table.columnfilter.ColumnFilterForm.MainBox.NumberDetailBox.NumberSequenceBox.NumberFromField; import org.eclipse.scout.rt.client.ui.basic.table.columnfilter.ColumnFilterForm.MainBox.NumberDetailBox.NumberSequenceBox.NumberToField; import org.eclipse.scout.rt.client.ui.basic.table.columnfilter.ColumnFilterForm.MainBox.OkButton; import org.eclipse.scout.rt.client.ui.basic.table.columnfilter.ColumnFilterForm.MainBox.StringDetailBox; import org.eclipse.scout.rt.client.ui.basic.table.columnfilter.ColumnFilterForm.MainBox.StringDetailBox.PatternField; import org.eclipse.scout.rt.client.ui.basic.table.columnfilter.ColumnFilterForm.MainBox.ValuesBox.ValuesTableField; import org.eclipse.scout.rt.client.ui.basic.table.columns.AbstractObjectColumn; import org.eclipse.scout.rt.client.ui.basic.table.columns.AbstractStringColumn; import org.eclipse.scout.rt.client.ui.basic.table.columns.IColumn; import org.eclipse.scout.rt.client.ui.basic.table.columns.IDateColumn; import org.eclipse.scout.rt.client.ui.basic.table.columns.IDoubleColumn; import org.eclipse.scout.rt.client.ui.basic.table.columns.IIntegerColumn; import org.eclipse.scout.rt.client.ui.basic.table.columns.ILongColumn; import org.eclipse.scout.rt.client.ui.form.AbstractForm; import org.eclipse.scout.rt.client.ui.form.AbstractFormHandler; import org.eclipse.scout.rt.client.ui.form.fields.IFormField; import org.eclipse.scout.rt.client.ui.form.fields.IValueField; import org.eclipse.scout.rt.client.ui.form.fields.button.AbstractButton; import org.eclipse.scout.rt.client.ui.form.fields.button.AbstractCloseButton; import org.eclipse.scout.rt.client.ui.form.fields.button.AbstractLinkButton; import org.eclipse.scout.rt.client.ui.form.fields.button.AbstractOkButton; import org.eclipse.scout.rt.client.ui.form.fields.datefield.AbstractDateField; import org.eclipse.scout.rt.client.ui.form.fields.datefield.IDateField; import org.eclipse.scout.rt.client.ui.form.fields.doublefield.AbstractDoubleField; import org.eclipse.scout.rt.client.ui.form.fields.doublefield.IDoubleField; import org.eclipse.scout.rt.client.ui.form.fields.groupbox.AbstractGroupBox; import org.eclipse.scout.rt.client.ui.form.fields.sequencebox.AbstractSequenceBox; import org.eclipse.scout.rt.client.ui.form.fields.stringfield.AbstractStringField; import org.eclipse.scout.rt.client.ui.form.fields.tablefield.AbstractTableField; import org.eclipse.scout.rt.shared.ScoutTexts; import org.eclipse.scout.rt.shared.services.lookup.LookupRow; public class ColumnFilterForm extends AbstractForm { private ITableColumnFilter<?> m_columnFilter; public ColumnFilterForm() throws ProcessingException { } @Override protected String getConfiguredTitle() { return ScoutTexts.get("ColumnFilter"); } @Override protected boolean getConfiguredModal() { return true; } public ITableColumnFilter<?> getColumnFilter() { return m_columnFilter; } public void setColumnFilter(ITableColumnFilter<?> columnFilter) { m_columnFilter = columnFilter; } public MainBox getMainBox() { return (MainBox) getRootGroupBox(); } public ValuesTableField getValuesTableField() { return getFieldByClass(ValuesTableField.class); } public StringDetailBox getStringDetailBox() { return getFieldByClass(StringDetailBox.class); } public PatternField getPatternField() { return getFieldByClass(PatternField.class); } public DateDetailBox getDateDetailBox() { return getFieldByClass(DateDetailBox.class); } public DateFromField getDateFromField() { return getFieldByClass(DateFromField.class); } public DateToField getDateToField() { return getFieldByClass(DateToField.class); } public NumberDetailBox getNumberDetailBox() { return getFieldByClass(NumberDetailBox.class); } public NumberFromField getNumberFromField() { return getFieldByClass(NumberFromField.class); } public NumberToField getNumberToField() { return getFieldByClass(NumberToField.class); } public OkButton getOkButton() { return getFieldByClass(OkButton.class); } public CloseButton getCloseButton() { return getFieldByClass(CloseButton.class); } public void startModify() throws ProcessingException { startInternal(new ModifyHandler()); } private void setupDateField(IDateField f, IColumn<?> obj) { if (obj instanceof IDateColumn) { IDateColumn col = (IDateColumn) obj; f.setHasTime(col.isHasTime()); f.setFormat(col.getFormat()); } } private void setupNumberField(IDoubleField f, IColumn<?> obj) { if (obj instanceof IDoubleColumn) { IDoubleColumn col = (IDoubleColumn) obj; f.setFormat(col.getFormat()); f.setGroupingUsed(col.isGroupingUsed()); f.setMaxFractionDigits(col.getMaxFractionDigits()); f.setMinFractionDigits(col.getMinFractionDigits()); f.setMultiplier(col.getMultiplier()); f.setPercent(col.isPercent()); } else if (obj instanceof IIntegerColumn) { IIntegerColumn col = (IIntegerColumn) obj; f.setFormat(col.getFormat()); f.setGroupingUsed(col.isGroupingUsed()); f.setMaxFractionDigits(0); f.setMinFractionDigits(0); } else if (obj instanceof ILongColumn) { ILongColumn col = (ILongColumn) obj; f.setFormat(col.getFormat()); f.setGroupingUsed(col.isGroupingUsed()); f.setMaxFractionDigits(0); f.setMinFractionDigits(0); } } @Order(10) public class MainBox extends AbstractGroupBox { @Override protected int getConfiguredGridW() { return 1; } @Order(20) public class ValuesBox extends AbstractGroupBox { @Override protected String getConfiguredLabel() { return ScoutTexts.get("ColumnFilterValuesSection"); } @Override protected int getConfiguredGridColumnCount() { return 1; } @Order(10) public class ButtonsSequenceBox extends AbstractSequenceBox { @Override protected boolean getConfiguredLabelVisible() { return false; } @Override protected boolean getConfiguredAutoCheckFromTo() { return false; } @Order(10) public class CheckAllButton extends AbstractLinkButton { @Override protected String getConfiguredLabel() { return ScoutTexts.get("CheckAll"); } @Override protected boolean getConfiguredProcessButton() { return false; } @Override protected void execClickAction() throws ProcessingException { for (ITableRow row : getValuesTableField().getTable().getRows()) { row.setChecked(true); } } } @Order(20) public class UncheckAllButton extends AbstractLinkButton { @Override protected String getConfiguredLabel() { return ScoutTexts.get("UncheckAll"); } @Override protected boolean getConfiguredProcessButton() { return false; } @Override protected void execClickAction() throws ProcessingException { for (ITableRow row : getValuesTableField().getTable().getRows()) { row.setChecked(false); } } } } @Order(30) public class ValuesTableField extends AbstractTableField<ValuesTableField.Table> { @Override protected int getConfiguredGridW() { return 1; } @Override protected int getConfiguredGridH() { return 8; } @Override protected boolean getConfiguredLabelVisible() { return false; } @Override protected void execReloadTableData() throws ProcessingException { List<LookupRow> hist = getColumnFilter().createHistogram(); ArrayList<ITableRow> rowList = new ArrayList<ITableRow>(hist.size() + 1); for (LookupRow histRow : hist) { - TableRow tableRow = new TableRow(getTable().getColumnSet(), new Object[]{histRow.getKey(), histRow.getText()}); + String text = StringUtility.isNullOrEmpty(StringUtility.getTag(histRow.getText(), "body")) ? histRow.getText() : HTMLUtility.getPlainText(histRow.getText()); + TableRow tableRow = new TableRow(getTable().getColumnSet(), new Object[]{histRow.getKey(), text}); tableRow.setIconId(histRow.getIconId()); tableRow.setForegroundColor(histRow.getForegroundColor()); tableRow.setBackgroundColor(histRow.getBackgroundColor()); tableRow.setFont(histRow.getFont()); rowList.add(tableRow); } getTable().discardAllRows(); getTable().addRows(rowList.toArray(new ITableRow[rowList.size()])); //set checks Set<?> selectedKeys = getColumnFilter().getSelectedValues(); if (selectedKeys != null) { Table.KeyColumn keyCol = getTable().getKeyColumn(); for (ITableRow row : getTable().getRows()) { if (selectedKeys.contains(keyCol.getValue(row))) { row.setChecked(true); } } } } public class Table extends AbstractTable { @Override protected boolean getConfiguredCheckable() { return true; } @Override protected boolean getConfiguredHeaderVisible() { return false; } @Override protected boolean getConfiguredAutoResizeColumns() { return true; } public KeyColumn getKeyColumn() { return getColumnSet().getColumnByClass(KeyColumn.class); } public TextColumn getTextColumn() { return getColumnSet().getColumnByClass(TextColumn.class); } @Order(10) public class KeyColumn extends AbstractObjectColumn { @Override protected boolean getConfiguredDisplayable() { return false; } @Override protected boolean getConfiguredPrimaryKey() { return true; } } @Order(20) public class TextColumn extends AbstractStringColumn { @Override protected String getConfiguredHeaderText() { return ScoutTexts.get("ColumnValues"); } @Override protected int getConfiguredHorizontalAlignment() { return -1; } @Override protected int getConfiguredWidth() { return 200; } } } } } @Order(30) public class StringDetailBox extends AbstractGroupBox { @Override protected String getConfiguredLabel() { return ScoutTexts.get("ColumnFilterStringSection"); } @Override protected boolean getConfiguredVisible() { return false; } @Override protected int getConfiguredGridColumnCount() { return 1; } @Order(10) public class PatternField extends AbstractStringField { @Override protected String getConfiguredLabel() { return ScoutTexts.get("StringPattern"); } @Override protected boolean getConfiguredLabelVisible() { return false; } @Override public boolean isSpellCheckEnabled() { return false; } } } @Order(40) public class DateDetailBox extends AbstractGroupBox { @Override protected String getConfiguredLabel() { return ScoutTexts.get("ColumnFilterDateSection"); } @Override protected boolean getConfiguredVisible() { return false; } @Order(10) public class DateSequenceBox extends AbstractSequenceBox { @Override protected boolean getConfiguredLabelVisible() { return false; } @Order(10) public class DateFromField extends AbstractDateField { @Override protected String getConfiguredLabel() { return ScoutTexts.get("from"); } } @Order(20) public class DateToField extends AbstractDateField { @Override protected String getConfiguredLabel() { return ScoutTexts.get("to"); } } } } @Order(40) public class NumberDetailBox extends AbstractGroupBox { @Override protected String getConfiguredLabel() { return ScoutTexts.get("ColumnFilterNumberSection"); } @Override protected boolean getConfiguredVisible() { return false; } @Order(10) public class NumberSequenceBox extends AbstractSequenceBox { @Override protected boolean getConfiguredLabelVisible() { return false; } @Order(10) public class NumberFromField extends AbstractDoubleField { @Override protected String getConfiguredLabel() { return ScoutTexts.get("from"); } } @Order(20) public class NumberToField extends AbstractDoubleField { @Override protected String getConfiguredLabel() { return ScoutTexts.get("to"); } } } } /** * Button "ok" */ @Order(100) public class OkButton extends AbstractOkButton { } /** * Button "close" */ @Order(110) public class CloseButton extends AbstractCloseButton { } /** * Button "reset" */ @Order(120) public class RemoveButton extends AbstractButton { @Override protected String getConfiguredLabel() { return ScoutTexts.get("ColumnFilterRemoveButton"); } @Override protected void execClickAction() throws ProcessingException { for (ITableRow r : getValuesTableField().getTable().getRows()) { r.setChecked(false); } for (IFormField f : getAllFields()) { if (f instanceof IValueField<?>) { ((IValueField<?>) f).setValue(null); } } doOk(); } } } /** * Handler for "Modify" */ public class ModifyHandler extends AbstractFormHandler { @Override protected void execLoad() throws ProcessingException { setTitle(getColumnFilter().getColumn().getHeaderCell().getText()); getValuesTableField().reloadTableData(); // if (getColumnFilter() instanceof StringColumnFilter) { StringColumnFilter filter = (StringColumnFilter) getColumnFilter(); getStringDetailBox().setVisible(true); getPatternField().setValue(filter.getPattern()); } else if (getColumnFilter() instanceof ComparableColumnFilter) { ComparableColumnFilter filter = (ComparableColumnFilter) getColumnFilter(); Class dataType = filter.getColumn().getDataType(); if (Date.class.isAssignableFrom(dataType)) { getDateDetailBox().setVisible(true); setupDateField(getDateFromField(), getColumnFilter().getColumn()); setupDateField(getDateToField(), getColumnFilter().getColumn()); getDateFromField().setValue((Date) filter.getMinimumValue()); getDateToField().setValue((Date) filter.getMaximumValue()); } else if (Number.class.isAssignableFrom(dataType)) { getNumberDetailBox().setVisible(true); setupNumberField(getNumberFromField(), getColumnFilter().getColumn()); setupNumberField(getNumberToField(), getColumnFilter().getColumn()); getNumberFromField().setValue(TypeCastUtility.castValue(filter.getMinimumValue(), Double.class)); getNumberToField().setValue(TypeCastUtility.castValue(filter.getMaximumValue(), Double.class)); } } } @Override protected void execPostLoad() throws ProcessingException { touch(); } @SuppressWarnings("unchecked") @Override protected void execStore() throws ProcessingException { Object[] checkedKeys = getValuesTableField().getTable().getKeyColumn().getValues(getValuesTableField().getTable().getCheckedRows()); if (checkedKeys.length > 0) { getColumnFilter().setSelectedValues(new HashSet(Arrays.asList(checkedKeys))); } else { getColumnFilter().setSelectedValues(null); } // if (getColumnFilter() instanceof StringColumnFilter) { StringColumnFilter filter = (StringColumnFilter) getColumnFilter(); filter.setPattern(getPatternField().getValue()); } else if (getColumnFilter() instanceof ComparableColumnFilter) { ComparableColumnFilter filter = (ComparableColumnFilter) getColumnFilter(); Class dataType = filter.getColumn().getDataType(); if (Date.class.isAssignableFrom(dataType)) { filter.setMinimumValue(getDateFromField().getValue()); filter.setMaximumValue(getDateToField().getValue()); } else if (Number.class.isAssignableFrom(dataType)) { filter.setMinimumValue((Comparable) TypeCastUtility.castValue(getNumberFromField().getValue(), dataType)); filter.setMaximumValue((Comparable) TypeCastUtility.castValue(getNumberToField().getValue(), dataType)); } } } } }
false
false
null
null
diff --git a/project_resource/working_folder/Simulation/UpdateSimulation.java b/project_resource/working_folder/Simulation/UpdateSimulation.java index 3033fde..33918f7 100644 --- a/project_resource/working_folder/Simulation/UpdateSimulation.java +++ b/project_resource/working_folder/Simulation/UpdateSimulation.java @@ -1,483 +1,485 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Simulation; import RosterGenerator.Duration; import database.TimetableInfo; import Simulation.Simulation; import database.database; import database.BusStopInfo; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Arrays; /** * * @author nathantilsley */ public class UpdateSimulation { public static void updateSim(ArrayList<Simulation> simulation, int route) { Date date = new Date(simulation.get(0).getDate().getTimeInMillis()); // current time table kind TimetableInfo.timetableKind timetableKind = TimetableInfo.timetableKind(date); // array of all timetable kinds, weekday = 0 saturday = 1, sunday = 2, TimetableInfo.timetableKind[] timetableKinds = TimetableInfo.timetableKind.values(); // now set the current time to the next minute int currentTime = simulation.get(0).getCurrentTime() + 1; int currentService = 0; // array to hold any services we may have to get later on // for cancel or delays we may need the next service int[] tempServiceTimes; // set the changed variable of the Simulations to false for(int i = 0; i < simulation.size(); i++) { simulation.get(i).setChanged(false); } if(route == 66) { for(int i = 0; i < simulation.size(); i++) { simulation.get(i).setCurrentTime(currentTime); if(simulation.get(i).getNextArriveTime() <= currentTime) { // the bus has come to the stop, so the next bus at the stop will be the next service simulation.get(i).setServiceNumber(simulation.get(i).getServiceNumber() + 1); if(simulation.get(i).getServiceNumber() == 2 || simulation.get(i).getServiceNumber() == 4 || simulation.get(i).getServiceNumber() == 11 || simulation.get(i).getServiceNumber() == 13) { if(i < 7) { simulation.get(i).setServiceNumber(simulation.get(i).getServiceNumber() + 1); } // if else i -= 7; } // if else if(simulation.get(i).getServiceNumber() == 9) { if(i < 6) { simulation.get(i).setServiceNumber(simulation.get(i).getServiceNumber() + 1); } // if else i-= 6; } // else if // now we need to get the service times for this stop tempServiceTimes = TimetableInfo.getServiceTimes(route, timetableKind, simulation.get(i).getServiceNumber()); System.out.println("i " + i); System.out.println(tempServiceTimes.length + ":" + simulation.get(i).getServiceNumber()); // some bugs in the database, so might need to sort Array if(i != 0) { if(tempServiceTimes[i] < tempServiceTimes[i - 1] && (tempServiceTimes[i] < 100)) { tempServiceTimes = sortArray(tempServiceTimes); } } // set the next arrival time accordingly simulation.get(i).setNextArriveTime(tempServiceTimes[i]); // generate a random status (very rare is there a cancel or delay simulation.get(i).setStatus(randGenerateStatus()); // reset any delays simulation.get(i).setDelay(0); // reset the message simulation.get(i).setMessage(""); // we have changed this bus stop info so let the simulation know we have simulation.get(i).setChanged(true); // sort out any delays, if they affect any later, bus stops // they should be updated accordingly if(simulation.get(i).getStatus() == 2) setDelay(simulation, i); // same as above goes for cancellation // but with cancellations, we get the next Service Time and put that // as the next arrive Time (see method for details) if(simulation.get(i).getStatus() == 1) setCancel(simulation, i, route, timetableKind); // Now we want to see if this new simulation object, // has any cancellations or delays before it // which may have an effect on this array // can not do that o if(i != 0) { // if the service before was delayed if((simulation.get(i).getServiceNumber() == simulation.get(i - 1).getServiceNumber()) && simulation.get(i - 1).getStatus() == 2) { // then set delay the delay to the delay of the previous one simulation.get(i).setDelay(simulation.get(i - 1).getDelay()); // plus increase the next arrival time by the delay simulation.get(i).setNextArriveTime(simulation.get(i).getNextArriveTime() + simulation.get(i - 1).getDelay()); // also set the status to be delayed simulation.get(i).setStatus(2); } // if the service before was cancelled if((simulation.get(i).getServiceNumber() == simulation.get(i - 1).getServiceNumber()) && simulation.get(i - 1).getStatus() == 1) { // set the cancellation time to be the current cancellation time simulation.get(i).setCancel(simulation.get(i).getNextArriveTime()); // now get the service number of the previous one int serviceNo = simulation.get(i - 1).getServiceNumber(); // set the service number to be that service number simulation.get(i).setServiceNumber(serviceNo); // get the serviceTimes for the next service tempServiceTimes = TimetableInfo.getServiceTimes(route, timetableKind, simulation.get(i).getServiceNumber()); // set the next arrival time to the corresponding service time simulation.get(i).setNextArriveTime(tempServiceTimes[i]); // also set the status to be cancelled simulation.get(i).setStatus(1); // and set the message appropriatley simulation.get(i).setMessage("Service " + serviceNo + " at " + simulation.get(i).getHours(simulation.get(i).getCurrentTime()) + + simulation.get(i).getMinutes(simulation.get(i).getCurrentTime()) + " cancelled, next service is shown"); } // if } // if } // if System.out.println("Next arriveTime " + simulation.get(i).getNextArriveTime() + " service " + simulation.get(i).getServiceNumber() + " timetableKind " + timetableKind); } // for } // if else { for(int i = 0; i < simulation.size(); i++) { simulation.get(i).setCurrentTime(currentTime); if(simulation.get(i).getNextArriveTime() <= currentTime) { // the bus has come to the stop, so the next bus at the stop will be the next service simulation.get(i).setServiceNumber(simulation.get(i).getServiceNumber() + 1); // now we need to get the service times for this stop tempServiceTimes = TimetableInfo.getServiceTimes(route, timetableKind, simulation.get(i).getServiceNumber()); // set the next arrival time accordingly // some bugs in the database, so might need to sort Array if(i != 0) { if(tempServiceTimes[i] < tempServiceTimes[i - 1]) { tempServiceTimes = sortArray(tempServiceTimes); } } simulation.get(i).setNextArriveTime(tempServiceTimes[i]); // generate a random status (very rare is there a cancel or delay simulation.get(i).setStatus(randGenerateStatus()); // reset any delays simulation.get(i).setDelay(0); // reset the message simulation.get(i).setMessage(""); // we have changed this bus stop info so let the simulation know we have simulation.get(i).setChanged(true); // sort out any delays, if they affect any later, bus stops // they should be updated accordingly if(simulation.get(i).getStatus() == 2) setDelay(simulation, i); // same as above goes for cancellation // but with cancellations, we get the next Service Time and put that // as the next arrive Time (see method for details) if(simulation.get(i).getStatus() == 1) setCancel(simulation, i, route, timetableKind); // Now we want to see if this new simulation object, // has any cancellations or delays before it // which may have an effect on this array // can not do that o if(i != 0) { // if the service before was delayed if((simulation.get(i).getServiceNumber() == simulation.get(i - 1).getServiceNumber()) && simulation.get(i - 1).getStatus() == 2) { // then set delay the delay to the delay of the previous one simulation.get(i).setDelay(simulation.get(i - 1).getDelay()); // plus increase the next arrival time by the delay simulation.get(i).setNextArriveTime(simulation.get(i).getNextArriveTime() + simulation.get(i - 1).getDelay()); // also set the status to be delayed simulation.get(i).setStatus(2); } // if the service before was cancelled if((simulation.get(i).getServiceNumber() == simulation.get(i - 1).getServiceNumber()) && simulation.get(i - 1).getStatus() == 1) { // set the cancellation time to be the current cancellation time simulation.get(i).setCancel(simulation.get(i).getNextArriveTime()); // now get the service number of the previous one int serviceNo = simulation.get(i - 1).getServiceNumber(); // set the service number to be that service number simulation.get(i).setServiceNumber(serviceNo); // get the serviceTimes for the next service tempServiceTimes = TimetableInfo.getServiceTimes(route, timetableKind, simulation.get(i).getServiceNumber()); // set the next arrival time to the corresponding service time simulation.get(i).setNextArriveTime(tempServiceTimes[i]); // also set the status to be cancelled simulation.get(i).setStatus(1); // and set the message appropriatley simulation.get(i).setMessage("Service " + serviceNo + " at " + simulation.get(i).getHours(simulation.get(i).getCurrentTime()) + + simulation.get(i).getMinutes(simulation.get(i).getCurrentTime()) + " cancelled, next service is shown"); } // if } //if }// if System.out.println("Next arriveTime " + simulation.get(i).getNextArriveTime() + " service " + simulation.get(i).getServiceNumber() + " timetableKind " + timetableKind); } // for } // else } // updateSim public static ArrayList<Simulation> initialiseArrayListForRoute(int route, GregorianCalendar date) { Date newDate = new Date((long)date.getTimeInMillis()); TimetableInfo.timetableKind timetableKind = TimetableInfo.timetableKind(newDate); TimetableInfo.timetableKind[] timetableKinds = TimetableInfo.timetableKind.values(); int[] busStops = BusStopInfo.getBusStops(route); ArrayList<Simulation> simArray = new ArrayList<Simulation>(); // temp index for accessing service times int j = 0; // get the service times for the start of the day int[] serviceTimes = TimetableInfo.getServiceTimes(route, TimetableInfo.timetableKind(newDate), 0); switch(route) { //for bus route 383, the database has 11 stops 3 of which are not use // so we ignore them // in adition to this the service time for hotel depart is // not on the database case 65: j = 0; for(int i = 0; i < busStops.length; i++) { //System.out.println(serviceTimes[i]); if(i != 1 && i != 4 && i != 8) { Simulation sim = new Simulation(busStops[i], serviceTimes[j], 0, serviceTimes[0], date, 0); j++; simArray.add(sim); } } break; // route 384 works all good because there is no discrepancies case 66: for(int i = 0; i < busStops.length; i++) { Simulation sim = new Simulation(busStops[i], serviceTimes[i], 0, serviceTimes[0], date, 0); simArray.add(sim); } break; case 67: // get the times for the next service becasue there is only 4 stops on the first service int[] nextServiceTimes358Out = TimetableInfo.getServiceTimes(route, TimetableInfo.timetableKind(newDate), 1); System.out.println(nextServiceTimes358Out.length); // the first service does not stop at all buses for the 358 journeys // so we need to get the correct ones, we use a temp index for this j = 0; for(int i = 0; i < busStops.length; i++) { // ignore thornsett, Printers arms, and the database has some random extra stops // which we do not want if(i > 2 && i != 5) { Simulation sim; if(!((timetableKinds[1].equals(timetableKind) || (timetableKinds[2].equals(timetableKind))) && i == 7 )) { if(i < 8 ) { sim = new Simulation(busStops[i], serviceTimes[j], 0, serviceTimes[0], date, 0); } else { sim = new Simulation(busStops[i], nextServiceTimes358Out[j], 0, serviceTimes[0], date, 1); } j++; simArray.add(sim); } } } break; case 68: // get the times for the next service becasue there is only 4 stops on the first service int[] nextServiceTimes358back = TimetableInfo.getServiceTimes(route, TimetableInfo.timetableKind(newDate), 1); // the first service does not stop at all buses for the 358 journeys // so we need to get the correct ones, we use a temp index for this j = 0; + int k = 0; for(int i = 0; i < busStops.length; i++) { // ignore thornsett, Printers arms, and the database has some random extra stops // which we do not want if(i < 11 && i != 8) { Simulation sim; if(!((timetableKinds[1].equals(timetableKind) || (timetableKinds[2].equals(timetableKind))) && i == 6)) { - if(i < 6) + if(i > 6) { - sim = new Simulation(busStops[i], serviceTimes[j], 0, serviceTimes[0], date, 0); - System.out.println("i" + i + ":" + serviceTimes[j] + BusStopInfo.getFullName(busStops[i])); + sim = new Simulation(busStops[k], serviceTimes[k], 0, serviceTimes[0], date, 0); + System.out.println("i" + i + ":" + serviceTimes[k] + BusStopInfo.getFullName(busStops[i])); + k++; } else { - sim = new Simulation(busStops[i], nextServiceTimes358back[j], 0, serviceTimes[0], date, 1); + sim = new Simulation(busStops[j], nextServiceTimes358back[j], 0, serviceTimes[0], date, 1); System.out.println("i" + i + ":" + nextServiceTimes358back[j] + BusStopInfo.getFullName(busStops[i])); } j++; simArray.add(sim); } } } break; } return simArray; } // 1 / 100 chance of a delay or cancellation // status' 0 = onTime, 1 = cancelled, 2 = delayed public static int randGenerateStatus() { int status = (int)(100 * Math.random()); if(status == 10 ) return 1; if(status == 20) return 2; else return 0; } // called if the randomly generated status is '2' // generates a delay between 0 - 60 public static int randGenerateDelay() { int delay = (int)(60 * Math.random()); return delay; } // if you want to set a delay for a bus stop // we need to apply it to all later bus stops (which have the same service) // this method does that public static void setDelay(ArrayList<Simulation> simulation, int index) { int delay = randGenerateDelay(); int serviceNo = simulation.get(index).getServiceNumber(); for(int j = index; j < simulation.size(); j++) { // set delay attribute = to delay // delay decrease each time because the bus speeds up // set the message to the correct message if(simulation.get(j).getServiceNumber() == serviceNo) { simulation.get(j).setMessage("Service " + serviceNo + " at " + simulation.get(j).getHours(simulation.get(j).getNextArriveTime()) + + simulation.get(j).getMinutes(simulation.get(j).getNextArriveTime()) + " delayed by " + simulation.get(j).getDelay()); simulation.get(j).setDelay(delay); simulation.get(j).setNextArriveTime(simulation.get(j).getNextArriveTime() + delay); delay--; } } } // we need to apply it to all later bus stops (which have the same service) // this method does that public static void setCancel(ArrayList<Simulation> simulation, int index, int route, TimetableInfo.timetableKind timetableKind) { // so the next service is the one we want int serviceNo = simulation.get(index).getServiceNumber() + 1; int[] serviceTimes = TimetableInfo.getServiceTimes(route, timetableKind, serviceNo); // update the nextArriveTime accordingly // set the message correctly // set the cancel time so can be printed out for(int j = index; j < simulation.size(); j++) { if(simulation.get(j).getServiceNumber() == serviceNo) { simulation.get(j).setCancel(simulation.get(j).getNextArriveTime()); simulation.get(j).setNextArriveTime(serviceTimes[j]); simulation.get(j).setServiceNumber(serviceNo); simulation.get(j).setMessage("Service " + serviceNo + " at " + simulation.get(j).getHours(simulation.get(j).getNextArriveTime()) + + simulation.get(j).getMinutes(simulation.get(j).getNextArriveTime()) + " cancelled, next service is shown"); } } } // method that will sort an array into // some bugs in the database // if time goes past 1440 (midnight) // it is ordered wrongly! public static int[] sortArray(int[] arrayToSort) { Arrays.sort(arrayToSort); return arrayToSort; } public static void main(String[] args) { database.openBusDatabase(); - int route = 66; + int route = 68; - GregorianCalendar date = new GregorianCalendar(2013, 5, 7, 0, 0, 0); + GregorianCalendar date = new GregorianCalendar(2013, 5, 23, 0, 0, 0); Date newDate = new Date(date.getTimeInMillis()); // so initalise an array for a date and a route ArrayList<Simulation> simArray = initialiseArrayListForRoute(route, date); // print out all the bus stops in the array for(int i = 0; i < simArray.size(); i++) { System.out.println("bus Stop " + simArray.get(i).getBusStopID()); } int k = 0; // while the last service has not gone // keep showing the time while(simArray.get(simArray.size() - 1).getServiceNumber() != TimetableInfo.getNumberOfServices(route, TimetableInfo.timetableKind(newDate))); { updateSim(simArray, 66); System.out.println("current time " + simArray.get(0).getCurrentTime()); k++; } } }
false
false
null
null
diff --git a/ws-security-stax/src/main/java/org/apache/wss4j/stax/validate/SecurityContextTokenValidatorImpl.java b/ws-security-stax/src/main/java/org/apache/wss4j/stax/validate/SecurityContextTokenValidatorImpl.java index d89ef9473..c74ac7fdc 100644 --- a/ws-security-stax/src/main/java/org/apache/wss4j/stax/validate/SecurityContextTokenValidatorImpl.java +++ b/ws-security-stax/src/main/java/org/apache/wss4j/stax/validate/SecurityContextTokenValidatorImpl.java @@ -1,85 +1,83 @@ /** * 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.wss4j.stax.validate; import org.apache.wss4j.binding.wssc.AbstractSecurityContextTokenType; import org.apache.wss4j.common.ext.WSPasswordCallback; import org.apache.wss4j.common.ext.WSSecurityException; +import org.apache.wss4j.common.util.KeyUtils; import org.apache.wss4j.stax.ext.WSSUtils; import org.apache.wss4j.stax.securityToken.WSSecurityTokenConstants; import org.apache.xml.security.exceptions.XMLSecurityException; -import org.apache.xml.security.stax.config.JCEAlgorithmMapper; import org.apache.xml.security.stax.ext.XMLSecurityConstants; import org.apache.xml.security.stax.impl.securityToken.AbstractInboundSecurityToken; import org.apache.xml.security.stax.securityToken.InboundSecurityToken; -import javax.crypto.spec.SecretKeySpec; import java.security.Key; public class SecurityContextTokenValidatorImpl implements SecurityContextTokenValidator { @Override public InboundSecurityToken validate(final AbstractSecurityContextTokenType securityContextTokenType, final String identifier, final TokenContext tokenContext) throws WSSecurityException { AbstractInboundSecurityToken securityContextToken = new AbstractInboundSecurityToken( tokenContext.getWsSecurityContext(), identifier, WSSecurityTokenConstants.KeyIdentifier_ExternalReference, true) { @Override public boolean isAsymmetric() { return false; } @Override public Key getKey(String algorithmURI, XMLSecurityConstants.AlgorithmUsage algorithmUsage, String correlationID) throws XMLSecurityException { Key key = getSecretKey().get(algorithmURI); if (key != null) { return key; } - String algo = JCEAlgorithmMapper.translateURItoJCEID(algorithmURI); WSPasswordCallback passwordCallback = new WSPasswordCallback( identifier, WSPasswordCallback.Usage.SECURITY_CONTEXT_TOKEN); WSSUtils.doSecretKeyCallback( tokenContext.getWssSecurityProperties().getCallbackHandler(), passwordCallback, null); if (passwordCallback.getKey() == null) { throw new WSSecurityException(WSSecurityException.ErrorCode.SECURITY_TOKEN_UNAVAILABLE, "noKey", securityContextTokenType.getId()); } - key = new SecretKeySpec(passwordCallback.getKey(), algo); + key = KeyUtils.prepareSecretKey(algorithmURI, passwordCallback.getKey()); setSecretKey(algorithmURI, key); return key; } @Override public WSSecurityTokenConstants.TokenType getTokenType() { return WSSecurityTokenConstants.SecurityContextToken; } }; securityContextToken.setElementPath(tokenContext.getElementPath()); securityContextToken.setXMLSecEvent(tokenContext.getFirstXMLSecEvent()); return securityContextToken; } }
false
false
null
null
diff --git a/platform-infrastructure/comms-frwk/PubsubClientBundle/src/main/java/org/societies/comm/xmpp/pubsub/impl/PubsubClientImpl.java b/platform-infrastructure/comms-frwk/PubsubClientBundle/src/main/java/org/societies/comm/xmpp/pubsub/impl/PubsubClientImpl.java index 982c476d3..329aaae0e 100644 --- a/platform-infrastructure/comms-frwk/PubsubClientBundle/src/main/java/org/societies/comm/xmpp/pubsub/impl/PubsubClientImpl.java +++ b/platform-infrastructure/comms-frwk/PubsubClientBundle/src/main/java/org/societies/comm/xmpp/pubsub/impl/PubsubClientImpl.java @@ -1,630 +1,630 @@ package org.societies.comm.xmpp.pubsub.impl; import java.io.ByteArrayInputStream; import java.util.AbstractMap; import java.util.AbstractMap.SimpleEntry; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.UnavailableException; import org.jabber.protocol.pubsub.Create; import org.jabber.protocol.pubsub.Item; import org.jabber.protocol.pubsub.Items; import org.jabber.protocol.pubsub.Publish; import org.jabber.protocol.pubsub.Pubsub; import org.jabber.protocol.pubsub.Retract; import org.jabber.protocol.pubsub.Subscribe; import org.jabber.protocol.pubsub.Unsubscribe; import org.jabber.protocol.pubsub.owner.Affiliations; import org.jabber.protocol.pubsub.owner.Delete; import org.jabber.protocol.pubsub.owner.Purge; import org.jabber.protocol.pubsub.owner.Subscriptions; import org.simpleframework.xml.Namespace; import org.simpleframework.xml.Root; import org.simpleframework.xml.Serializer; import org.simpleframework.xml.convert.AnnotationStrategy; import org.simpleframework.xml.core.Persister; import org.simpleframework.xml.strategy.Strategy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.societies.api.comm.xmpp.datatypes.Stanza; import org.societies.api.comm.xmpp.datatypes.StanzaError; import org.societies.api.comm.xmpp.datatypes.XMPPInfo; import org.societies.api.comm.xmpp.exceptions.CommunicationException; import org.societies.api.comm.xmpp.exceptions.XMPPError; import org.societies.api.comm.xmpp.interfaces.ICommCallback; import org.societies.api.comm.xmpp.interfaces.ICommManager; import org.societies.api.comm.xmpp.pubsub.Affiliation; import org.societies.api.comm.xmpp.pubsub.PubsubClient; import org.societies.api.comm.xmpp.pubsub.Subscriber; import org.societies.api.comm.xmpp.pubsub.Subscription; import org.societies.api.comm.xmpp.pubsub.SubscriptionState; import org.societies.api.identity.IIdentity; import org.societies.api.identity.IIdentityManager; import org.societies.api.identity.InvalidFormatException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.w3c.dom.Element; import org.w3c.dom.ls.DOMImplementationLS; import org.w3c.dom.ls.LSSerializer; import com.sun.org.apache.xerces.internal.dom.ElementNSImpl; @Component public class PubsubClientImpl implements PubsubClient, ICommCallback { public static final int WAIT_TIMEOUT = 10000; public static final long REQUEST_TIMEOUT = 20000; private final static List<String> NAMESPACES = Collections .unmodifiableList(Arrays.asList("http://jabber.org/protocol/pubsub#event", "http://jabber.org/protocol/pubsub", "http://jabber.org/protocol/pubsub#errors", "http://jabber.org/protocol/pubsub#owner", "jabber:x:data")); private static final List<String> PACKAGES = Collections .unmodifiableList(Arrays.asList("org.jabber.protocol.pubsub.event", "org.jabber.protocol.pubsub", "org.jabber.protocol.pubsub.errors", "org.jabber.protocol.pubsub.owner", "jabber.x.data")); private static Logger LOG = LoggerFactory .getLogger(PubsubClientImpl.class); private ICommManager endpoint; private Map<String,Object> responses; private Map<String,Long> responseTimeout; private Map<Subscription,List<Subscriber>> subscribers; private IIdentityManager idm; private final Map<String, String> nsToPackage = new HashMap<String, String>(); private String packagesContextPath; private IIdentity localIdentity; private Map<String,Class<?>> elementToClass; private Serializer serializer; @Autowired public PubsubClientImpl(ICommManager endpoint) { responses = new HashMap<String, Object>(); responseTimeout = new HashMap<String, Long>(); subscribers = new HashMap<Subscription, List<Subscriber>>(); elementToClass = new HashMap<String, Class<?>>(); Strategy strategy = new AnnotationStrategy(); serializer = new Persister(strategy); this.endpoint = endpoint; idm = endpoint.getIdManager(); try { if (endpoint.isConnected()) localIdentity = idm.getThisNetworkNode(); else throw new CommunicationException("Injected endpoint is not connected!"); packagesContextPath = ""; endpoint.register(this); } catch (CommunicationException e) { LOG.error(e.getMessage(),e); } } public ICommManager getICommManager() { return endpoint; } /* * CommCallback Impl */ @Override public List<String> getXMLNamespaces() { return NAMESPACES; } @Override public List<String> getJavaPackages() { return PACKAGES; } /** Retrieves a package from a namespace mapping * @param namespace * @return * @throws UnavailableException */ private String getPackage(String namespace) { return nsToPackage.get(namespace); } @Override public void receiveMessage(Stanza stanza, Object payload) { if (payload instanceof org.jabber.protocol.pubsub.event.Event) { org.jabber.protocol.pubsub.event.Items items = ((org.jabber.protocol.pubsub.event.Event)payload).getItems(); String node = items.getNode(); Subscription sub = new Subscription(stanza.getFrom(), stanza.getTo(), node, null); // TODO may break due to mismatch between "to" and local IIdentity org.jabber.protocol.pubsub.event.Item i = items.getItem().get(0); // TODO assume only one item per notification Object bean = unmarshallBean((ElementNSImpl) i.getAny()); //POST EVENT List<Subscriber> subscriberList = subscribers.get(sub); for (Subscriber subscriber : subscriberList) subscriber.pubsubEvent(stanza.getFrom(), node, i.getId(), bean); // TODO multiple subscribers and classloaders // TODO CLASSLOADING MAGIC DISABLED! // Thread.currentThread().setContextClassLoader(oldCl); } } // TODO subId // <message from='pubsub.shakespeare.lit' to='[email protected]' id='foo'> // <event xmlns='http://jabber.org/protocol/pubsub#event'> // <items node='princely_musings'> // <item id='ae890ac52d0df67ed7cfdf51b644e901'/> // </items> // </event> // <headers xmlns='http://jabber.org/protocol/shim'> // <header name='SubID'>123-abc</header> // <header name='SubID'>004-yyy</header> // </headers> // </message> private Object unmarshallBean(ElementNSImpl eventBean) { Object bean = null; //CONVERT THE .getAny() OBJECT TO XML DOMImplementationLS domImplLS = (DOMImplementationLS) eventBean.getOwnerDocument().getImplementation(); LSSerializer domSerializer = domImplLS.createLSSerializer(); String eventBeanXML = domSerializer.writeToString(eventBean); //SERIALISE OBJECT String elementID = "{" + eventBean.getNamespaceURI() + "}" + eventBean.getLocalName(); Class<?> c = elementToClass.get(elementID); // TODO CLASSLOADING MAGIC DISABLED! // ClassLoader oldCl = Thread.currentThread().getContextClassLoader(); // Thread.currentThread().setContextClassLoader(c.getClassLoader()); if (c==null) { // when received xml was has not been binded print a warn and notify with raw XML String[] keyArray = new String[elementToClass.keySet().size()]; keyArray = elementToClass.keySet().toArray(keyArray); LOG.warn("No class found for namespace{element} '"+elementID+"', passing unmarshalled XML element... Registered entries are: "+Arrays.toString(keyArray)); bean = eventBean; } else { // unmarshall item content try { bean = serializer.read(c, eventBeanXML); } catch (Exception e) { LOG.error(e.getMessage(), e); } } return bean; } @Override public void receiveResult(Stanza stanza, Object payload) { synchronized (responses) { // LOG.info("receiveResult 4 id "+stanza.getId()); responses.put(stanza.getId(), payload); responses.notifyAll(); } } @Override public void receiveError(Stanza stanza, XMPPError error) { synchronized (responses) { // LOG.info("receiveError 4 id "+stanza.getId()); responses.put(stanza.getId(), error); responses.notifyAll(); } } @Override public void receiveInfo(Stanza stanza, String node, XMPPInfo info) { // TODO Auto-generated method stub } @Override public void receiveItems(Stanza stanza, String node, List<String> items) { SimpleEntry<String, List<String>> mapSimpleEntry = new AbstractMap.SimpleEntry<String, List<String>>(node, items); synchronized (responses) { // LOG.info("receiveItems 4 id "+stanza.getId()); responses.put(stanza.getId(), mapSimpleEntry); responses.notifyAll(); } } /* * PubsubClient Impl - emulates synchronous */ private Object blockingIQ(Stanza stanza, Object payload) throws CommunicationException, XMPPError { endpoint.sendIQSet(stanza, payload, this); return waitForResponse(stanza.getId()); } private Object waitForResponse(String id) throws XMPPError { synchronized (responseTimeout) { responseTimeout.put(id, REQUEST_TIMEOUT); Object response = null; synchronized (responses) { while (!responses.containsKey(id)) { long cycleStart = System.currentTimeMillis(); try { // LOG.info("waiting response 4 id "+id); responses.wait(WAIT_TIMEOUT); } catch (InterruptedException e) { LOG.info(e.getMessage(),e); } // LOG.info("checking response 4 id "+id+" in "+Arrays.toString(responses.keySet().toArray())); long timeLeft = responseTimeout.get(id)-System.currentTimeMillis()+cycleStart; if (timeLeft>0) responseTimeout.put(id,timeLeft); else { LOG.warn("Result for request with id='"+id+"' timed out..."); throw new XMPPError(StanzaError.remote_server_timeout); } } response = responses.remove(id); // LOG.info("got response 4 id "+id); } if (response instanceof XMPPError) throw (XMPPError)response; return response; } } @Override public List<String> discoItems(IIdentity pubsubService, String node) throws XMPPError, CommunicationException { String id = endpoint.getItems(pubsubService, node, this); Object response = waitForResponse(id); // TODO node check // String returnedNode = ((SimpleEntry<String, List<XMPPNode>>)response).getKey(); // if (returnedNode != node) // throw new CommunicationException(""); return ((SimpleEntry<String, List<String>>)response).getValue(); } @Override public Subscription subscriberSubscribe(IIdentity pubsubService, String node, Subscriber subscriber) throws XMPPError, CommunicationException { Subscription subscription = new Subscription(pubsubService, localIdentity, node, null); List<Subscriber> subscriberList = subscribers.get(subscription); if (subscriberList==null) { subscriberList = new ArrayList<Subscriber>(); Stanza stanza = new Stanza(pubsubService); Pubsub payload = new Pubsub(); Subscribe sub = new Subscribe(); sub.setJid(localIdentity.getBareJid()); sub.setNode(node); payload.setSubscribe(sub); Object response = blockingIQ(stanza, payload); String subId = ((Pubsub)response).getSubscription().getSubid(); subscription = new Subscription(pubsubService, localIdentity, node, subId); subscribers.put(subscription, subscriberList); } subscriberList.add(subscriber); return subscription; } @Override public void subscriberUnsubscribe(IIdentity pubsubService, String node, Subscriber subscriber) throws XMPPError, CommunicationException { Subscription subscription = new Subscription(pubsubService, localIdentity, node, null); List<Subscriber> subscriberList = subscribers.get(subscription); subscriberList.remove(subscriber); if (subscriberList.size()==0) { Stanza stanza = new Stanza(pubsubService); Pubsub payload = new Pubsub(); Unsubscribe unsub = new Unsubscribe(); - unsub.setJid(localIdentity.getJid()); + unsub.setJid(localIdentity.getBareJid()); unsub.setNode(node); payload.setUnsubscribe(unsub); Object response = blockingIQ(stanza, payload); } } @Override public List<Object> subscriberRetrieveLast(IIdentity pubsubService, String node, String subId) throws XMPPError, CommunicationException { Stanza stanza = new Stanza(pubsubService); Pubsub payload = new Pubsub(); Items items = new Items(); items.setNode(node); if (subId!=null) items.setSubid(subId); // TODO max items... in the server also! payload.setItems(items); Object response = blockingIQ(stanza, payload); List<Item> itemList = ((Pubsub)response).getItems().getItem(); List<Object> returnList = new ArrayList<Object>(); for (Item i : itemList) returnList.add(unmarshallBean((ElementNSImpl) i.getAny())); return returnList; } @Override public List<Object> subscriberRetrieveSpecific(IIdentity pubsubService, String node, String subId, List<String> itemIdList) throws XMPPError, CommunicationException { Stanza stanza = new Stanza(pubsubService); Pubsub payload = new Pubsub(); Items items = new Items(); items.setNode(node); if (subId!=null) items.setSubid(subId); for(String itemId : itemIdList) { Item item = new Item(); item.setId(itemId); items.getItem().add(item); } payload.setItems(items); Object response = blockingIQ(stanza, payload); List<Item> itemList = ((Pubsub)response).getItems().getItem(); List<Object> returnList = new ArrayList<Object>(); for (Item i : itemList) returnList.add(unmarshallBean((ElementNSImpl) i.getAny())); return returnList; } @Override public String publisherPublish(IIdentity pubsubService, String node, String itemId, Object item) throws XMPPError, CommunicationException { Stanza stanza = new Stanza(pubsubService); Pubsub payload = new Pubsub(); Publish p = new Publish(); p.setNode(node); Item i = new Item(); if (itemId!=null) i.setId(itemId); i.setAny(item); p.setItem(i); payload.setPublish(p); Object response = blockingIQ(stanza, payload); if (response!=null) return ((Pubsub)response).getPublish().getItem().getId(); else return itemId; } @Override public void publisherDelete(IIdentity pubsubService, String node, String itemId) throws XMPPError, CommunicationException { Stanza stanza = new Stanza(pubsubService); Pubsub payload = new Pubsub(); Retract retract = new Retract(); retract.setNode(node); Item i = new Item(); i.setId(itemId); retract.getItem().add(i); payload.setRetract(retract); Object response = blockingIQ(stanza, payload); } @Override public void ownerCreate(IIdentity pubsubService, String node) throws XMPPError, CommunicationException { Stanza stanza = new Stanza(pubsubService); Pubsub payload = new Pubsub(); Create c = new Create(); c.setNode(node); payload.setCreate(c); blockingIQ(stanza, payload); } @Override public void ownerDelete(IIdentity pubsubService, String node) throws XMPPError, CommunicationException { Stanza stanza = new Stanza(pubsubService); org.jabber.protocol.pubsub.owner.Pubsub payload = new org.jabber.protocol.pubsub.owner.Pubsub(); Delete delete = new Delete(); delete.setNode(node); payload.setDelete(delete); blockingIQ(stanza, payload); } @Override public void ownerPurgeItems(IIdentity pubsubService, String node) throws XMPPError, CommunicationException { Stanza stanza = new Stanza(pubsubService); org.jabber.protocol.pubsub.owner.Pubsub payload = new org.jabber.protocol.pubsub.owner.Pubsub(); Purge purge = new Purge(); purge.setNode(node); payload.setPurge(purge); blockingIQ(stanza, payload); } @Override public Map<IIdentity, SubscriptionState> ownerGetSubscriptions( IIdentity pubsubService, String node) throws XMPPError, CommunicationException { Stanza stanza = new Stanza(pubsubService); org.jabber.protocol.pubsub.owner.Pubsub payload = new org.jabber.protocol.pubsub.owner.Pubsub(); Subscriptions subs = new Subscriptions(); subs.setNode(node); payload.setSubscriptions(subs); blockingIQ(stanza, payload); List<org.jabber.protocol.pubsub.owner.Subscription> subList = ((org.jabber.protocol.pubsub.owner.Pubsub)payload).getSubscriptions().getSubscription(); Map<IIdentity, SubscriptionState> returnMap = new HashMap<IIdentity, SubscriptionState>(); for (org.jabber.protocol.pubsub.owner.Subscription s : subList) try { returnMap.put(idm.fromJid(s.getJid()), SubscriptionState.valueOf(s.getSubscription())); } catch (InvalidFormatException e) { LOG.warn("Unable to parse subscription JIDs",e); } return returnMap; } @Override public Map<IIdentity, Affiliation> ownerGetAffiliations( IIdentity pubsubService, String node) throws XMPPError, CommunicationException { Stanza stanza = new Stanza(pubsubService); org.jabber.protocol.pubsub.owner.Pubsub payload = new org.jabber.protocol.pubsub.owner.Pubsub(); Affiliations affs = new Affiliations(); affs.setNode(node); payload.setAffiliations(affs); blockingIQ(stanza, payload); List<org.jabber.protocol.pubsub.owner.Affiliation> affList = ((org.jabber.protocol.pubsub.owner.Pubsub)payload).getAffiliations().getAffiliation(); Map<IIdentity, Affiliation> returnMap = new HashMap<IIdentity, Affiliation>(); for (org.jabber.protocol.pubsub.owner.Affiliation a : affList) try { returnMap.put(idm.fromJid(a.getJid()), Affiliation.valueOf(a.getAffiliation())); } catch (InvalidFormatException e) { LOG.warn("Unable to parse affiliation JIDs",e); } return returnMap; } @Override public void ownerSetSubscriptions(IIdentity pubsubService, String node, Map<IIdentity, SubscriptionState> subscriptions) throws XMPPError, CommunicationException { Stanza stanza = new Stanza(pubsubService); org.jabber.protocol.pubsub.owner.Pubsub payload = new org.jabber.protocol.pubsub.owner.Pubsub(); Subscriptions subs = new Subscriptions(); subs.setNode(node); payload.setSubscriptions(subs); for (IIdentity subscriber : subscriptions.keySet()) { org.jabber.protocol.pubsub.owner.Subscription s = new org.jabber.protocol.pubsub.owner.Subscription(); s.setJid(subscriber.getJid()); s.setSubscription(subscriptions.get(subscriber).toString()); subs.getSubscription().add(s); } blockingIQ(stanza, payload); // TODO error handling on multiple subscription changes } @Override public void ownerSetAffiliations(IIdentity pubsubService, String node, Map<IIdentity, Affiliation> affiliations) throws XMPPError, CommunicationException { Stanza stanza = new Stanza(pubsubService); org.jabber.protocol.pubsub.owner.Pubsub payload = new org.jabber.protocol.pubsub.owner.Pubsub(); Affiliations affs = new Affiliations(); affs.setNode(node); payload.setAffiliations(affs); for (IIdentity subscriber : affiliations.keySet()) { org.jabber.protocol.pubsub.owner.Affiliation a = new org.jabber.protocol.pubsub.owner.Affiliation(); a.setJid(subscriber.getJid()); a.setAffiliation(affiliations.get(subscriber).toString()); affs.getAffiliation().add(a); } blockingIQ(stanza, payload); // TODO error handling on multiple affiliation changes } @Override public synchronized void addJaxbPackages(List<String> packageList) { //throws JAXBException { if (packagesContextPath.length()==0) { // TODO first run! } StringBuilder contextPath = new StringBuilder(packagesContextPath); for (String pack : packageList) contextPath.append(":" + pack); /* JAXBContext jc = JAXBContext.newInstance(contextPath.toString(), this.getClass().getClassLoader()); contentUnmarshaller = jc.createUnmarshaller(); contentMarshaller = jc.createMarshaller(); */ //TODO: SIMPLE try { for (int i=0; i<packageList.size(); i++) { String packageStr = packageList.get(i); String nsStr = getNSfromPackage(packageStr); nsToPackage.put(nsStr, packageStr); } } catch (Exception ex) { LOG.error("Error in JAXBMapping adding: " + ex.getMessage()); } packagesContextPath = contextPath.toString(); } /** Returns the Namespace for a Package string * @param packageString * @return */ private String getNSfromPackage(String packageString) { String ns = ""; String[] packArr = packageString.split("\\."); ns = "http://" + packArr[1] + "." + packArr[0]; for(int i=2; i<packArr.length; i++) ns+="/" + packArr[i]; return ns; } @Override public void addSimpleClasses(List<String> classList) throws ClassNotFoundException { ClassLoader cl = Thread.currentThread().getContextClassLoader(); try { for (String c : classList) { Class<?> clazz = cl.loadClass(c); Root rootAnnotation = clazz.getAnnotation(Root.class); Namespace namespaceAnnotation = clazz.getAnnotation(Namespace.class); if (rootAnnotation!=null && namespaceAnnotation!=null) { elementToClass.put("{"+namespaceAnnotation.reference()+"}"+rootAnnotation.name(),clazz); } } } catch (ClassNotFoundException e) { throw new ClassNotFoundException(e.getMessage()+" from classloader "+cl.toString()+": class being registered from a context that doesn't have access to it.", e); } } }
true
false
null
null
diff --git a/src/simpleserver/command/SetGroupCommand.java b/src/simpleserver/command/SetGroupCommand.java index b68e3e5..af488f7 100644 --- a/src/simpleserver/command/SetGroupCommand.java +++ b/src/simpleserver/command/SetGroupCommand.java @@ -1,62 +1,67 @@ /* * Copyright (c) 2010 SimpleServer authors (see CONTRIBUTORS) * * 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 simpleserver.command; import simpleserver.Player; import simpleserver.Server; public class SetGroupCommand extends PlayerArgCommand { public SetGroupCommand() { super("setgroup PLAYER GROUP", "Set the group ID of the named player"); } @Override protected void executeWithTarget(Player player, String message, String target) { Server server = player.getServer(); if ( player.getGroupId() <= server.permissions.getNameGroup(target) ) { player.addMessage("\u00a7cYou cannot set the group of this user!"); return; } String[] arguments = extractArguments(message); if (arguments.length > 1) { int group; try { group = Integer.parseInt(arguments[1]); } catch (NumberFormatException e) { player.addMessage("\u00a7cGroup must be a number!"); return; } if (group >= player.getGroupId()) { player.addMessage("\u00a7cYou cannot promote to your group or higher!"); } else { server.permissions.setPlayerGroup(target, group); + + Player t = player.getServer().findPlayer(target); + if (t != null) + t.updateGroup(); + player.addMessage("\u00a77Player " + target + "'s group was set to " + group + "!"); server.adminLog("User " + player.getName() + " set player's group:\t " + target + "\t(" + group + ")"); } } } }
true
false
null
null
diff --git a/CubicTestPlugin/src/main/java/org/cubictest/common/utils/CubicCloner.java b/CubicTestPlugin/src/main/java/org/cubictest/common/utils/CubicCloner.java index 0668e631..2264eaf3 100644 --- a/CubicTestPlugin/src/main/java/org/cubictest/common/utils/CubicCloner.java +++ b/CubicTestPlugin/src/main/java/org/cubictest/common/utils/CubicCloner.java @@ -1,33 +1,49 @@ /* * This software is licensed under the terms of the GNU GENERAL PUBLIC LICENSE * Version 2, which can be found at http://www.gnu.org/copyleft/gpl.html */ package org.cubictest.common.utils; +import java.lang.reflect.Method; + import org.cubictest.persistence.CubicTestXStream; +import org.eclipse.core.resources.IProject; /** * Creates a deep copy of an object using XStream. * * @author Christian Schwarz */ public class CubicCloner { public static CubicTestXStream xStream; /** * Returns a deep copy of an object using XStream. */ public static Object deepCopy(Object oldObj) { if (xStream == null) { xStream = new CubicTestXStream(); } String xml = xStream.toXML(oldObj); Object newObj = xStream.fromXML(xml); - + + //check if the variable "project" can be set (typically transient, and thus not copied by XStream): + IProject project = null; + try { + Method getProject = oldObj.getClass().getMethod("getProject", null); + if (getProject != null) { + project = (IProject) getProject.invoke(oldObj, null); + } + Method setProject = oldObj.getClass().getMethod("setProject", new Class[] {IProject.class}); + if (setProject != null) { + setProject.invoke(newObj, project); + } + } catch (Exception e) { + //ignore + } return newObj; } - } diff --git a/CubicTestPlugin/src/main/java/org/cubictest/model/SubTest.java b/CubicTestPlugin/src/main/java/org/cubictest/model/SubTest.java index 93361b81..bf0eb79b 100644 --- a/CubicTestPlugin/src/main/java/org/cubictest/model/SubTest.java +++ b/CubicTestPlugin/src/main/java/org/cubictest/model/SubTest.java @@ -1,111 +1,118 @@ /* * This software is licensed under the terms of the GNU GENERAL PUBLIC LICENSE * Version 2, which can be found at http://www.gnu.org/copyleft/gpl.html */ package org.cubictest.model; +import org.cubictest.common.utils.Logger; import org.cubictest.persistence.TestPersistance; import org.cubictest.resources.interfaces.IResourceMonitor; import org.eclipse.core.resources.IProject; /** * Subtest node contained within another test. * * @author ehalvorsen * @author chr_schwarz */ public class SubTest extends ConnectionPoint { private String filePath; private transient Test test; private transient IProject project; private transient IResourceMonitor resourceMonitor; public SubTest(String filePath, IProject project) { super(); this.filePath = filePath; this.project = project; + if (project == null) { + Logger.warn("Invoked SubTest constructor with null project"); + } } /** * @return Test the sub test that this object represents */ public Test getTest(boolean forceRefreshFile) { if(test == null || forceRefreshFile) { + if (project == null && test != null) { + project = test.getProject(); + } test = TestPersistance.loadFromFile(project, getFilePath()); test.setResourceMonitor(resourceMonitor); test.resetStatus(); } return test; } @Override public String getName() { return getTest(false).getName() + " (" + getFileName() + ")"; } public String getFileName() { int pos1 = getFilePath().lastIndexOf("/"); int pos2 = getFilePath().lastIndexOf("\\"); return getFilePath().substring(Math.max(pos1, pos2) + 1); } public String getFilePath() { return filePath; } public boolean containsTest(Test test) { if(test.getFilePath().equals(getFilePath())) { return true; } for(SubTest subTest : getTest(false).getSubTests()) { if(subTest.getFilePath() == test.getFilePath() || subTest.containsTest(test)) { return true; } } return false; } /* * We need to know the project to figure out what file to load (since all paths are project relative) */ public void setProject(IProject project) { this.project = project; } public IProject getProject() { return project; } @Override public void resetStatus() { setStatus(TestPartStatus.UNKNOWN); test = null; } public void setResourceMonitor(IResourceMonitor resourceMonitor) { this.resourceMonitor = resourceMonitor; } public void setFilePath(String filePath) { this.filePath = filePath; } @Override public String toString() { return getClass().getSimpleName() + ": Name = " + getName() + ", FilePath = " + getFilePath(); } public void updateStatus(boolean hadException, ConnectionPoint targetConnectionPoint) { if (hadException) { setStatus(TestPartStatus.EXCEPTION); return; } setStatus(getTest(false).updateAndGetStatus(targetConnectionPoint)); } } \ No newline at end of file
false
false
null
null
diff --git a/src/com/google/javascript/jscomp/NodeUtil.java b/src/com/google/javascript/jscomp/NodeUtil.java index d009c399b..7890945f3 100644 --- a/src/com/google/javascript/jscomp/NodeUtil.java +++ b/src/com/google/javascript/jscomp/NodeUtil.java @@ -1,1930 +1,1930 @@ /* * Copyright 2004 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.collect.Maps; import com.google.javascript.rhino.FunctionNode; import com.google.javascript.rhino.JSDocInfo; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import com.google.javascript.rhino.TokenStream; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; /** * NodeUtil contains utilities that get properties from the Node object. * * * */ public final class NodeUtil { // TODO(user): Eliminate this class and make all of the static methods // instance methods of com.google.javascript.rhino.Node. /** the set of builtin constructors that don't have side effects. */ private static final Set<String> CONSTRUCTORS_WITHOUT_SIDE_EFFECTS = new HashSet<String>(Arrays.asList( "Array", "Date", "Error", "Object", "RegExp", "XMLHttpRequest")); public static final String CONSTANT_MARKER = "$$constant"; // Utility class; do not instantiate. private NodeUtil() {} /** * Gets the boolean value of a node that represents a literal. This method * effectively emulates the <code>Boolean()</code> JavaScript cast function. * * @throws IllegalArgumentException If {@code n} is not a literal value */ static boolean getBooleanValue(Node n) { switch (n.getType()) { case Token.STRING: return n.getString().length() > 0; case Token.NUMBER: return n.getDouble() != 0; case Token.NULL: case Token.FALSE: case Token.VOID: return false; case Token.NAME: String name = n.getString(); if ("undefined".equals(name) || "NaN".equals(name)) { // We assume here that programs don't change the value of the keyword // undefined to something other than the value undefined. return false; } else if ("Infinity".equals(name)) { return true; } break; case Token.TRUE: case Token.ARRAYLIT: case Token.OBJECTLIT: case Token.REGEXP: return true; } throw new IllegalArgumentException("Non-literal value: " + n); } /** * Gets the value of a node as a String, or null if it cannot be converted. * When it returns a non-null String, this method effectively emulates the * <code>String()</code> JavaScript cast function. */ static String getStringValue(Node n) { // TODO(user): Convert constant array, object, and regex literals as well. switch (n.getType()) { case Token.NAME: case Token.STRING: return n.getString(); case Token.NUMBER: double value = n.getDouble(); long longValue = (long) value; // Return "1" instead of "1.0" if (longValue == value) { return Long.toString(longValue); } else { return Double.toString(n.getDouble()); } case Token.FALSE: case Token.TRUE: case Token.NULL: return Node.tokenToName(n.getType()); case Token.VOID: return "undefined"; } return null; } /** * Gets the function's name. This method recognizes five forms: * <ul> * <li>{@code function name() ...}</li> * <li>{@code var name = function() ...}</li> * <li>{@code qualified.name = function() ...}</li> * <li>{@code var name2 = function name1() ...}</li> * <li>{@code qualified.name2 = function name1() ...}</li> * </ul> * In two last cases with named anonymous functions, the second name is * returned (the variable of qualified name). * * @param n a node whose type is {@link Token#FUNCTION} * @param parent {@code n}'s parent (never {@code null}) * @return the function's name, or {@code null} if it has no name */ static String getFunctionName(Node n, Node parent) { String name = n.getFirstChild().getString(); switch (parent.getType()) { case Token.NAME: // var name = function() ... // var name2 = function name1() ... return parent.getString(); case Token.ASSIGN: // qualified.name = function() ... // qualified.name2 = function name1() ... return parent.getFirstChild().getQualifiedName(); default: // function name() ... return name != null && name.length() != 0 ? name : null; } } /** * Returns true if this is an immutable value. */ static boolean isImmutableValue(Node n) { switch (n.getType()) { case Token.STRING: case Token.NUMBER: case Token.NULL: case Token.TRUE: case Token.FALSE: case Token.VOID: return true; case Token.NEG: return isImmutableValue(n.getFirstChild()); case Token.NAME: String name = n.getString(); // We assume here that programs don't change the value of the keyword // undefined to something other than the value undefined. return "undefined".equals(name) || "Infinity".equals(name) || "NaN".equals(name); } return false; } /** * Returns true if this is a literal value. We define a literal value * as any node that evaluates to the same thing regardless of when or * where it is evaluated. So /xyz/ and [3, 5] are literals, but * function() { return a; } is not. */ static boolean isLiteralValue(Node n) { // TODO(nicksantos): Refine this function to catch more literals. switch (n.getType()) { case Token.ARRAYLIT: case Token.OBJECTLIT: case Token.REGEXP: // Return true only if all children are const. for (Node child = n.getFirstChild(); child != null; child = child.getNext()) { if (!isLiteralValue(child)) { return false; } } return true; default: return isImmutableValue(n); } } /** * Determines whether the given value may be assigned to a define. * * @param val The value being assigned. * @param defines The list of names of existing defines. */ static boolean isValidDefineValue(Node val, Set<String> defines) { switch (val.getType()) { case Token.STRING: case Token.NUMBER: case Token.TRUE: case Token.FALSE: return true; // Single operators are valid if the child is valid. case Token.BITAND: case Token.BITNOT: case Token.BITOR: case Token.BITXOR: case Token.NOT: case Token.NEG: return isValidDefineValue(val.getFirstChild(), defines); // Names are valid if and only if they are defines themselves. case Token.NAME: case Token.GETPROP: if (val.isQualifiedName()) { return defines.contains(val.getQualifiedName()); } } return false; } /** * Returns whether this a BLOCK node with no children. * * @param block The node. */ static boolean isEmptyBlock(Node block) { if (block.getType() != Token.BLOCK) { return false; } for (Node n = block.getFirstChild(); n != null; n = n.getNext()) { if (n.getType() != Token.EMPTY) { return false; } } return true; } /** * A "simple" operator is one whose children are expressions, * has no direct side-effects (unlike '+='), and has no * conditional aspects (unlike '||'). */ static boolean isSimpleOperatorType(int type) { switch (type) { case Token.ADD: case Token.BITAND: case Token.BITNOT: case Token.BITOR: case Token.BITXOR: case Token.COMMA: case Token.DIV: case Token.EQ: case Token.GE: case Token.GETELEM: case Token.GETPROP: case Token.GT: case Token.INSTANCEOF: case Token.LE: case Token.LSH: case Token.LT: case Token.MOD: case Token.MUL: case Token.NE: case Token.NOT: case Token.RSH: case Token.SHEQ: case Token.SHNE: case Token.SUB: case Token.TYPEOF: case Token.VOID: case Token.POS: case Token.NEG: case Token.URSH: return true; default: return false; } } /** * Creates an EXPR_RESULT. * * @param child The expression itself. * @return Newly created EXPR node with the child as subexpression. */ public static Node newExpr(Node child) { return new Node(Token.EXPR_RESULT, child); } /** * Returns true if the node may create new mutable state, or change existing * state. * * @see <a href="http://www.xkcd.org/326/">XKCD Cartoon</a> */ static boolean mayEffectMutableState(Node n) { return checkForStateChangeHelper(n, true); } /** * Returns true if the node which may have side effects when executed. */ static boolean mayHaveSideEffects(Node n) { return checkForStateChangeHelper(n, false); } /** * Returns true if some node in n's subtree changes application state. * If {@code checkForNewObjects} is true, we assume that newly created * mutable objects (like object literals) change state. Otherwise, we assume * that they have no side effects. */ private static boolean checkForStateChangeHelper( Node n, boolean checkForNewObjects) { // Rather than id which ops may have side effects, id the ones // that we know to be safe switch (n.getType()) { // other side-effect free statements and expressions case Token.AND: case Token.BLOCK: case Token.EXPR_RESULT: case Token.HOOK: case Token.IF: case Token.IN: case Token.LP: case Token.NUMBER: case Token.OR: case Token.THIS: case Token.TRUE: case Token.FALSE: case Token.NULL: case Token.STRING: case Token.SWITCH: case Token.TRY: case Token.EMPTY: break; // Throws are by definition side effects case Token.THROW: return true; case Token.OBJECTLIT: case Token.ARRAYLIT: case Token.REGEXP: if (checkForNewObjects) { return true; } break; case Token.VAR: // empty var statement (no declaration) case Token.NAME: // variable by itself if (n.getFirstChild() != null) return true; break; case Token.FUNCTION: // Anonymous functions don't have side-effects, but named ones // change the namespace. Therefore, we check if the function has // a name. Either way, we don't need to check the children, since // they aren't executed at declaration time. // return !isFunctionAnonymous(n); case Token.NEW: { if (checkForNewObjects) { return true; } // calls to constructors that have no side effects have the // no side effect property set. if (n.isNoSideEffectsCall()) { break; } // certain constructors are certified side effect free Node constructor = n.getFirstChild(); if (Token.NAME == constructor.getType()) { String className = constructor.getString(); if (CONSTRUCTORS_WITHOUT_SIDE_EFFECTS.contains(className)) { // loop below will see if the constructor parameters have // side-effects break; } } else { // the constructor could also be an expression like // new (useArray ? Object : Array)(); } } return true; case Token.CALL: // calls to functions that have no side effects have the no // side effect property set. if (n.isNoSideEffectsCall()) { // loop below will see if the function parameters have // side-effects break; } return true; default: if (isSimpleOperatorType(n.getType())) break; return true; } for (Node c = n.getFirstChild(); c != null; c = c.getNext()) { if (checkForStateChangeHelper(c, checkForNewObjects)) { return true; } } return false; } /** * Do calls to this constructor have side effects? * * @param callNode - construtor call node */ static boolean constructorCallHasSideEffects(Node callNode) { Preconditions.checkArgument( callNode.getType() == Token.NEW, "Expected NEW node, got " + Token.name(callNode.getType())); if (callNode.isNoSideEffectsCall()) { return false; } Node nameNode = callNode.getFirstChild(); if (nameNode.getType() == Token.NAME && CONSTRUCTORS_WITHOUT_SIDE_EFFECTS.contains(nameNode.getString())) { return false; } return true; } /** * Returns true if calls to this function have side effects. * * @param callNode - function call node */ static boolean functionCallHasSideEffects(Node callNode) { Preconditions.checkArgument( callNode.getType() == Token.CALL, "Expected CALL node, got " + Token.name(callNode.getType())); if (callNode.isNoSideEffectsCall()) { return false; } Node nameNode = callNode.getFirstChild(); // Built-in functions with no side effects. if (nameNode.getType() == Token.NAME) { String name = nameNode.getString(); if (name.equals("String")) { return false; } } // Functions in the "Math" namespace have no side effects. if (nameNode.getType() == Token.GETPROP && nameNode.getFirstChild().getType() == Token.NAME) { String namespaceName = nameNode.getFirstChild().getString(); if (namespaceName.equals("Math")) { return false; } } return true; } /** * Returns true if the current node's type implies side effects. * * This is a non-recursive version of the may have side effects * check; used to check wherever the current node's type is one of * the reason's why a subtree has side effects. */ static boolean nodeTypeMayHaveSideEffects(Node n) { if (NodeUtil.isAssignmentOp(n)) { return true; } switch(n.getType()) { case Token.CALL: case Token.DELPROP: case Token.NEW: case Token.DEC: case Token.INC: case Token.THROW: return true; case Token.NAME: // A variable definition. return n.hasChildren(); default: return false; } } /** * @return Whether the tree can be affected by side-effects or * has side-effects. */ static boolean canBeSideEffected(Node n) { Set<String> emptySet = Collections.emptySet(); return canBeSideEffected(n, emptySet); } /** * @param knownConstants A set of names known to be constant value at * node 'n' (such as locals that are last written before n can execute). * @return Whether the tree can be affected by side-effects or * has side-effects. */ static boolean canBeSideEffected(Node n, Set<String> knownConstants) { switch (n.getType()) { case Token.CALL: case Token.NEW: // Function calls or constructor can reference changed values. // TODO(johnlenz): Add some mechanism for determining that functions // are unaffected by side effects. return true; case Token.NAME: // Non-constant names values may have been changed. return !NodeUtil.isConstantName(n) && !knownConstants.contains(n.getString()); // Properties on constant NAMEs can still be side-effected. case Token.GETPROP: case Token.GETELEM: return true; } for (Node c = n.getFirstChild(); c != null; c = c.getNext()) { if (canBeSideEffected(c, knownConstants)) { return true; } } return false; } /* * 0 comma , * 1 assignment = += -= *= /= %= <<= >>= >>>= &= ^= |= * 2 conditional ?: * 3 logical-or || * 4 logical-and && * 5 bitwise-or | * 6 bitwise-xor ^ * 7 bitwise-and & * 8 equality == != * 9 relational < <= > >= * 10 bitwise shift << >> >>> * 11 addition/subtraction + - * 12 multiply/divide * / % * 13 negation/increment ! ~ - ++ -- * 14 call, member () [] . */ static int precedence(int type) { switch (type) { case Token.COMMA: return 0; case Token.ASSIGN_BITOR: case Token.ASSIGN_BITXOR: case Token.ASSIGN_BITAND: case Token.ASSIGN_LSH: case Token.ASSIGN_RSH: case Token.ASSIGN_URSH: case Token.ASSIGN_ADD: case Token.ASSIGN_SUB: case Token.ASSIGN_MUL: case Token.ASSIGN_DIV: case Token.ASSIGN_MOD: case Token.ASSIGN: return 1; case Token.HOOK: return 2; // ?: operator case Token.OR: return 3; case Token.AND: return 4; case Token.BITOR: return 5; case Token.BITXOR: return 6; case Token.BITAND: return 7; case Token.EQ: case Token.NE: case Token.SHEQ: case Token.SHNE: return 8; case Token.LT: case Token.GT: case Token.LE: case Token.GE: case Token.INSTANCEOF: case Token.IN: return 9; case Token.LSH: case Token.RSH: case Token.URSH: return 10; case Token.SUB: case Token.ADD: return 11; case Token.MUL: case Token.MOD: case Token.DIV: return 12; case Token.INC: case Token.DEC: case Token.NEW: case Token.DELPROP: case Token.TYPEOF: case Token.VOID: case Token.NOT: case Token.BITNOT: case Token.POS: case Token.NEG: return 13; case Token.ARRAYLIT: case Token.CALL: case Token.EMPTY: case Token.FALSE: case Token.FUNCTION: case Token.GETELEM: case Token.GETPROP: case Token.GET_REF: case Token.IF: case Token.LP: case Token.NAME: case Token.NULL: case Token.NUMBER: case Token.OBJECTLIT: case Token.REGEXP: case Token.RETURN: case Token.STRING: case Token.THIS: case Token.TRUE: return 15; default: throw new Error("Unknown precedence for " + Node.tokenToName(type) + " (type " + type + ")"); } } /** * Returns true if the operator is associative. * e.g. (a * b) * c = a * (b * c) * Note: "+" is not associative because it is also the concatentation * for strings. e.g. "a" + (1 + 2) is not "a" + 1 + 2 */ static boolean isAssociative(int type) { switch (type) { case Token.MUL: case Token.AND: case Token.OR: case Token.BITOR: case Token.BITAND: return true; default: return false; } } static boolean isAssignmentOp(Node n) { switch (n.getType()){ case Token.ASSIGN: case Token.ASSIGN_BITOR: case Token.ASSIGN_BITXOR: case Token.ASSIGN_BITAND: case Token.ASSIGN_LSH: case Token.ASSIGN_RSH: case Token.ASSIGN_URSH: case Token.ASSIGN_ADD: case Token.ASSIGN_SUB: case Token.ASSIGN_MUL: case Token.ASSIGN_DIV: case Token.ASSIGN_MOD: return true; } return false; } static int getOpFromAssignmentOp(Node n) { switch (n.getType()){ case Token.ASSIGN_BITOR: return Token.BITOR; case Token.ASSIGN_BITXOR: return Token.BITXOR; case Token.ASSIGN_BITAND: return Token.BITAND; case Token.ASSIGN_LSH: return Token.LSH; case Token.ASSIGN_RSH: return Token.RSH; case Token.ASSIGN_URSH: return Token.URSH; case Token.ASSIGN_ADD: return Token.ADD; case Token.ASSIGN_SUB: return Token.SUB; case Token.ASSIGN_MUL: return Token.MUL; case Token.ASSIGN_DIV: return Token.DIV; case Token.ASSIGN_MOD: return Token.MOD; } throw new IllegalArgumentException("Not an assiment op"); } static boolean isExpressionNode(Node n) { return n.getType() == Token.EXPR_RESULT; } /** * Determines if the given node contains a function declaration. */ static boolean containsFunctionDeclaration(Node n) { return containsType(n, Token.FUNCTION); } /** * Returns true if the subtree contains references to 'this' keyword */ static boolean referencesThis(Node n) { return containsType(n, Token.THIS); } /** * Is this a GETPROP or GETELEM node? */ static boolean isGet(Node n) { return n.getType() == Token.GETPROP || n.getType() == Token.GETELEM; } /** * Is this a GETPROP node? */ static boolean isGetProp(Node n) { return n.getType() == Token.GETPROP; } /** * Is this a NAME node? */ static boolean isName(Node n) { return n.getType() == Token.NAME; } /** * Is this a NEW node? */ static boolean isNew(Node n) { return n.getType() == Token.NEW; } /** * Is this a VAR node? */ static boolean isVar(Node n) { return n.getType() == Token.VAR; } /** * Is this node the name of a variable being declared? * * @param n The node * @return True if {@code n} is NAME and {@code parent} is VAR */ static boolean isVarDeclaration(Node n) { // There is no need to verify that parent != null because a NAME node // always has a parent in a valid parse tree. return n.getType() == Token.NAME && n.getParent().getType() == Token.VAR; } /** * For an assignment or variable declaration get the assigned value. * @return The value node representing the new value. */ static Node getAssignedValue(Node n) { Preconditions.checkState(isName(n)); Node parent = n.getParent(); if (isVar(parent)) { return n.getFirstChild(); } else if (isAssign(parent) && parent.getFirstChild() == n) { return n.getNext(); } else { return null; } } /** * Is this a STRING node? */ static boolean isString(Node n) { return n.getType() == Token.STRING; } /** * Is this node an assignment expression statement? * * @param n The node * @return True if {@code n} is EXPR_RESULT and {@code n}'s * first child is ASSIGN */ static boolean isExprAssign(Node n) { return n.getType() == Token.EXPR_RESULT && n.getFirstChild().getType() == Token.ASSIGN; } /** * Is this an ASSIGN node? */ static boolean isAssign(Node n) { return n.getType() == Token.ASSIGN; } /** * Is this node a call expression statement? * * @param n The node * @return True if {@code n} is EXPR_RESULT and {@code n}'s * first child is CALL */ static boolean isExprCall(Node n) { return n.getType() == Token.EXPR_RESULT && n.getFirstChild().getType() == Token.CALL; } /** * @return Whether the node represents a FOR-IN loop. */ static boolean isForIn(Node n) { return n.getType() == Token.FOR && n.getChildCount() == 3; } /** - * Determines whether the given node is a FOR, DO, WHILE, WITH, or IF node. + * Determines whether the given node is a FOR, DO, or WHILE node. */ static boolean isLoopStructure(Node n) { switch (n.getType()) { case Token.FOR: case Token.DO: case Token.WHILE: return true; default: return false; } } /** * @param n The node to inspect. * @return If the node, is a FOR, WHILE, or DO, it returns the node for * the code BLOCK, null otherwise. */ static Node getLoopCodeBlock(Node n) { switch (n.getType()) { case Token.FOR: case Token.WHILE: return n.getLastChild(); case Token.DO: return n.getFirstChild(); default: return null; } } /** * Determines whether the given node is a FOR, DO, WHILE, WITH, or IF node. */ static boolean isControlStructure(Node n) { switch (n.getType()) { case Token.FOR: case Token.DO: case Token.WHILE: case Token.WITH: case Token.IF: case Token.LABEL: case Token.TRY: case Token.CATCH: case Token.SWITCH: case Token.CASE: case Token.DEFAULT: return true; default: return false; } } /** * Determines whether the given node is code node for FOR, DO, * WHILE, WITH, or IF node. */ static boolean isControlStructureCodeBlock(Node parent, Node n) { switch (parent.getType()) { case Token.FOR: case Token.WHILE: case Token.LABEL: case Token.WITH: return parent.getLastChild() == n; case Token.DO: return parent.getFirstChild() == n; case Token.IF: return parent.getFirstChild() != n; case Token.TRY: return parent.getFirstChild() == n || parent.getLastChild() == n; case Token.CATCH: return parent.getLastChild() == n; case Token.SWITCH: case Token.CASE: return parent.getFirstChild() != n; case Token.DEFAULT: return true; default: Preconditions.checkState(isControlStructure(parent)); return false; } } /** * Gets the condition of an ON_TRUE / ON_FALSE CFG edge. * @param n a node with an outgoing conditional CFG edge * @return the condition node or null if the condition is not obviously a node */ static Node getConditionExpression(Node n) { switch (n.getType()) { case Token.IF: case Token.WHILE: return n.getFirstChild(); case Token.DO: return n.getLastChild(); case Token.FOR: switch (n.getChildCount()) { case 3: return null; case 4: return n.getFirstChild().getNext(); } throw new IllegalArgumentException("malformed 'for' statement " + n); case Token.CASE: return null; } throw new IllegalArgumentException(n + " does not have a condition."); } /** * @return Whether the node is of a type that contain other statements. */ static boolean isStatementBlock(Node n) { return n.getType() == Token.SCRIPT || n.getType() == Token.BLOCK; } /** * @return Whether the node is used as a statement. */ static boolean isStatement(Node n) { Node parent = n.getParent(); // It is not possible to determine definitely if a node is a statement // or not if it is not part of the AST. A FUNCTION node, for instance, // is either part of an expression (as a anonymous function) or as // a statement. Preconditions.checkState(parent != null); switch (parent.getType()) { case Token.SCRIPT: case Token.BLOCK: case Token.LABEL: return true; default: return false; } } /** Whether the node is part of a switch statement. */ static boolean isSwitchCase(Node n) { return n.getType() == Token.CASE || n.getType() == Token.DEFAULT; } /** @return Whether the node is a label name. */ static boolean isLabelName(Node n) { if (n != null && n.getType() == Token.NAME) { Node parent = n.getParent(); switch (parent.getType()) { case Token.LABEL: case Token.BREAK: case Token.CONTINUE: if (n == parent.getFirstChild()) { return true; } } } return false; } /** Whether the child node is the FINALLY block of a try. */ static boolean isTryFinallyNode(Node parent, Node child) { return parent.getType() == Token.TRY && parent.getChildCount() == 3 && child == parent.getLastChild(); } /** Safely remove children while maintaining a valid node structure. */ static void removeChild(Node parent, Node node) { // Node parent = node.getParent(); if (isStatementBlock(parent) || isSwitchCase(node) || isTryFinallyNode(parent, node)) { // A statement in a block can simply be removed. parent.removeChild(node); } else if (parent.getType() == Token.VAR) { if (parent.hasMoreThanOneChild()) { parent.removeChild(node); } else { // Remove the node from the parent, so it can be reused. parent.removeChild(node); // This would leave an empty VAR, remove the VAR itself. removeChild(parent.getParent(), parent); } } else if (node.getType() == Token.BLOCK) { // Simply empty the block. This maintains source location and // "synthetic"-ness. node.detachChildren(); } else if (parent.getType() == Token.LABEL && node == parent.getLastChild()) { // Remove the node from the parent, so it can be reused. parent.removeChild(node); // A LABEL without children can not be referred to, remove it. removeChild(parent.getParent(), parent); } else if (parent.getType() == Token.FOR && parent.getChildCount() == 4) { // Only Token.FOR can have an Token.EMPTY other control structure // need something for the condition. Others need to be replaced // or the structure removed. parent.replaceChild(node, new Node(Token.EMPTY)); } else { throw new IllegalStateException("Invalid attempt to remove node: " + node.toString() + " of "+ parent.toString()); } } /** * Merge a block with its parent block. * @return Whether the block was removed. */ static boolean tryMergeBlock(Node block) { Preconditions.checkState(block.getType() == Token.BLOCK); Node parent = block.getParent(); // Try to remove the block if its parent is a block/script or if its // parent is label and it has exactly one child. if (NodeUtil.isStatementBlock(parent)) { Node previous = block; while (block.hasChildren()) { Node child = block.removeFirstChild(); parent.addChildAfter(child, previous); previous = child; } parent.removeChild(block); return true; } else if (parent.getType() == Token.LABEL && block.hasOneChild()) { parent.replaceChild(block, block.removeFirstChild()); return true; } else { return false; } } /** * Is this a CALL node? */ static boolean isCall(Node n) { return n.getType() == Token.CALL; } /** * Is this a FUNCTION node? */ static boolean isFunction(Node n) { return n.getType() == Token.FUNCTION; } /** * Return a BLOCK node for the given FUNCTION node. */ static Node getFunctionBody(Node fn) { Preconditions.checkArgument(isFunction(fn)); return fn.getLastChild(); } /** * Is this a THIS node? */ static boolean isThis(Node node) { return node.getType() == Token.THIS; } /** * Is this node or any of its children a CALL? */ static boolean containsCall(Node n) { return containsType(n, Token.CALL); } /** * Is this node a function declaration? A function declaration is a function * that has a name that is added to the current scope (i.e. a function that * is not anonymous; see {@link #isFunctionAnonymous}). */ static boolean isFunctionDeclaration(Node n) { return n.getType() == Token.FUNCTION && !isFunctionAnonymous(n); } /** * Is this node an anonymous function? An anonymous function is one that has * either no name or a name that is not added to the current scope (see * {@link #isFunctionAnonymous}). */ static boolean isAnonymousFunction(Node n) { return n.getType() == Token.FUNCTION && isFunctionAnonymous(n); } /** * Is a FUNCTION node an anonymous function? An anonymous function is one that * has either no name or a name that is not added to the current scope. * * <p>Some examples of anonymous functions: * <pre> * function () {} * (function f() {})() * [ function f() {} ] * var f = function f() {}; * for (function f() {};;) {} * </pre> * * <p>Some examples of functions that are <em>not</em> anonymous: * <pre> * function f() {} * if (x); else function f() {} * for (;;) { function f() {} } * </pre> * * @param n A FUNCTION node * @return Whether n is an anonymous function */ static boolean isFunctionAnonymous(Node n) { return !isStatement(n); } /** * Determines if a function takes a variable number of arguments by * looking for references to the "arguments" var_args object. */ static boolean isVarArgsFunction(Node function) { Preconditions.checkArgument(isFunction(function)); return NodeUtil.isNameReferenced( function.getLastChild(), "arguments", Predicates.<Node>not(new NodeUtil.MatchNodeType(Token.FUNCTION))); } /** * @return Whether node is a call to methodName. * a.f(...) * a['f'](...) */ static boolean isObjectCallMethod(Node callNode, String methodName) { if (callNode.getType() == Token.CALL) { Node functionIndentifyingExpression = callNode.getFirstChild(); if (NodeUtil.isGet(functionIndentifyingExpression)) { Node last = functionIndentifyingExpression.getLastChild(); if (last != null && last.getType() == Token.STRING) { String propName = last.getString(); return (propName.equals(methodName)); } } } return false; } /** * @return Whether the callNode represents an expression in the form of: * x.call(...) * x['call'](...) */ static boolean isFunctionObjectCall(Node callNode) { return isObjectCallMethod(callNode, "call"); } /** * @return Whether the callNode represents an expression in the form of: * x.apply(...) * x['apply'](...) */ static boolean isFunctionObjectApply(Node callNode) { return isObjectCallMethod(callNode, "apply"); } /** * @return Whether the callNode represents an expression in the form of: * x.call(...) * x['call'](...) * where x is a NAME node. */ static boolean isSimpleFunctionObjectCall(Node callNode) { if (isFunctionObjectCall(callNode)) { if (callNode.getFirstChild().getFirstChild().getType() == Token.NAME) { return true; } } return false; } /** * Determines whether this node is strictly on the left hand side of an assign * or var initialization. Notably, this does not include all L-values, only * statements where the node is used only as an L-value. * * @param n The node * @param parent Parent of the node * @return True if n is the left hand of an assign */ static boolean isLhs(Node n, Node parent) { return (parent.getType() == Token.ASSIGN && parent.getFirstChild() == n) || parent.getType() == Token.VAR; } /** * Determines whether a node represents an object literal key * (e.g. key1 in {key1: value1, key2: value2}). * * @param node A node * @param parent The node's parent */ static boolean isObjectLitKey(Node node, Node parent) { if (node.getType() == Token.STRING && parent.getType() == Token.OBJECTLIT) { int index = 0; for (Node current = parent.getFirstChild(); current != null; current = current.getNext()) { if (current == node) { return index % 2 == 0; } index++; } } return false; } /** * Converts an operator's token value (see {@link Token}) to a string * representation. * * @param operator the operator's token value to convert * @return the string representation or {@code null} if the token value is * not an operator */ static String opToStr(int operator) { switch (operator) { case Token.BITOR: return "|"; case Token.OR: return "||"; case Token.BITXOR: return "^"; case Token.AND: return "&&"; case Token.BITAND: return "&"; case Token.SHEQ: return "==="; case Token.EQ: return "=="; case Token.NOT: return "!"; case Token.NE: return "!="; case Token.SHNE: return "!=="; case Token.LSH: return "<<"; case Token.IN: return "in"; case Token.LE: return "<="; case Token.LT: return "<"; case Token.URSH: return ">>>"; case Token.RSH: return ">>"; case Token.GE: return ">="; case Token.GT: return ">"; case Token.MUL: return "*"; case Token.DIV: return "/"; case Token.MOD: return "%"; case Token.BITNOT: return "~"; case Token.ADD: return "+"; case Token.SUB: return "-"; case Token.POS: return "+"; case Token.NEG: return "-"; case Token.ASSIGN: return "="; case Token.ASSIGN_BITOR: return "|="; case Token.ASSIGN_BITXOR: return "^="; case Token.ASSIGN_BITAND: return "&="; case Token.ASSIGN_LSH: return "<<="; case Token.ASSIGN_RSH: return ">>="; case Token.ASSIGN_URSH: return ">>>="; case Token.ASSIGN_ADD: return "+="; case Token.ASSIGN_SUB: return "-="; case Token.ASSIGN_MUL: return "*="; case Token.ASSIGN_DIV: return "/="; case Token.ASSIGN_MOD: return "%="; case Token.VOID: return "void"; case Token.TYPEOF: return "typeof"; case Token.INSTANCEOF: return "instanceof"; default: return null; } } /** * Converts an operator's token value (see {@link Token}) to a string * representation or fails. * * @param operator the operator's token value to convert * @return the string representation * @throws Error if the token value is not an operator */ static String opToStrNoFail(int operator) { String res = opToStr(operator); if (res == null) { throw new Error("Unknown op " + operator + ": " + Token.name(operator)); } return res; } /** * @return true if n or any of its children are of the specified type */ static boolean containsType(Node node, int type, Predicate<Node> traverseChildrenPred) { return has(node, new MatchNodeType(type), traverseChildrenPred); } /** * @return true if n or any of its children are of the specified type */ static boolean containsType(Node node, int type) { return containsType(node, type, Predicates.<Node>alwaysTrue()); } /** * Given a node tree, finds all the VAR declarations in that tree that are * not in an inner scope. Then adds a new VAR node at the top of the current * scope that redeclares them, if necessary. */ static void redeclareVarsInsideBranch(Node branch) { Collection<Node> vars = getVarsDeclaredInBranch(branch); if (vars.isEmpty()) { return; } Node parent = getAddingRoot(branch); for (Node nameNode : vars) { Node var = new Node( Token.VAR, Node.newString(Token.NAME, nameNode.getString())); copyNameAnnotations(nameNode, var.getFirstChild()); parent.addChildToFront(var); } } /** * Copy any annotations that follow a named value. * @param source * @param destination */ static void copyNameAnnotations(Node source, Node destination) { if (source.getBooleanProp(Node.IS_CONSTANT_NAME)) { destination.putBooleanProp(Node.IS_CONSTANT_NAME, true); } } /** * Gets a Node at the top of the current scope where we can add new var * declarations as children. */ private static Node getAddingRoot(Node n) { Node addingRoot = null; Node ancestor = n; while (null != (ancestor = ancestor.getParent())) { int type = ancestor.getType(); if (type == Token.SCRIPT) { addingRoot = ancestor; break; } else if (type == Token.FUNCTION) { addingRoot = ancestor.getLastChild(); break; } } // make sure that the adding root looks ok Preconditions.checkState(addingRoot.getType() == Token.BLOCK || addingRoot.getType() == Token.SCRIPT); Preconditions.checkState(addingRoot.getFirstChild() == null || addingRoot.getFirstChild().getType() != Token.SCRIPT); return addingRoot; } /** Creates function name(params_0, ..., params_n) { body }. */ public static FunctionNode newFunctionNode(String name, List<Node> params, Node body, int lineno, int charno) { Node parameterParen = new Node(Token.LP, lineno, charno); for (Node param : params) { parameterParen.addChildToBack(param); } FunctionNode function = new FunctionNode(name, lineno, charno); function.addChildrenToBack( Node.newString(Token.NAME, name, lineno, charno)); function.addChildToBack(parameterParen); function.addChildToBack(body); return function; } /** * Creates a node representing a qualified name. * * @param name A qualified name (e.g. "foo" or "foo.bar.baz") * @param lineno The source line offset. * @param charno The source character offset from start of the line. * @return A NAME or GETPROP node */ public static Node newQualifiedNameNode(String name, int lineno, int charno) { int endPos = name.indexOf('.'); if (endPos == -1) { return Node.newString(Token.NAME, name, lineno, charno); } Node node = Node.newString(Token.NAME, name.substring(0, endPos), lineno, charno); int startPos; do { startPos = endPos + 1; endPos = name.indexOf('.', startPos); String part = (endPos == -1 ? name.substring(startPos) : name.substring(startPos, endPos)); node = new Node(Token.GETPROP, node, Node.newString(Token.STRING, part, lineno, charno), lineno, charno); } while (endPos != -1); return node; } /** * Creates a node representing a qualified name, copying over the source * location information from the basis node and assigning the given original * name to the node. * * @param name A qualified name (e.g. "foo" or "foo.bar.baz") * @param basisNode The node that represents the name as currently found in * the AST. * @param originalName The original name of the item being represented by the * NAME node. Used for debugging information. * * @return A NAME or GETPROP node */ static Node newQualifiedNameNode(String name, Node basisNode, String originalName) { Node node = newQualifiedNameNode(name, -1, -1); setDebugInformation(node, basisNode, originalName); return node; } /** * Sets the debug information (source file info and orignal name) * on the given node. * * @param node The node on which to set the debug information. * @param basisNode The basis node from which to copy the source file info. * @param originalName The original name of the node. */ static void setDebugInformation(Node node, Node basisNode, String originalName) { node.copyInformationFrom(basisNode); node.putProp(Node.ORIGINALNAME_PROP, originalName); } /** * Creates a new node representing an *existing* name, copying over the source * location information from the basis node. * * @param name The name for the new NAME node. * @param basisNode The node that represents the name as currently found in * the AST. * * @return The node created. */ static Node newName(String name, Node basisNode) { Node nameNode = Node.newString(Token.NAME, name); nameNode.copyInformationFrom(basisNode); return nameNode; } /** * Creates a new node representing an *existing* name, copying over the source * location information from the basis node and assigning the given original * name to the node. * * @param name The name for the new NAME node. * @param basisNode The node that represents the name as currently found in * the AST. * @param originalName The original name of the item being represented by the * NAME node. Used for debugging information. * * @return The node created. */ static Node newName(String name, Node basisNode, String originalName) { Node nameNode = newName(name, basisNode); nameNode.putProp(Node.ORIGINALNAME_PROP, originalName); return nameNode; } /** Test if all characters in the string are in the Basic Latin (aka ASCII) * character set - that they have UTF-16 values equal to or below 0x7f. * This check can find which identifiers with Unicode characters need to be * escaped in order to allow resulting files to be processed by non-Unicode * aware UNIX tools and editors. * * * See http://en.wikipedia.org/wiki/Latin_characters_in_Unicode * for more on Basic Latin. * * @param s The string to be checked for ASCII-goodness. * * @return True if all characters in the string are in Basic Latin set. */ static boolean isLatin(String s) { char LARGEST_BASIC_LATIN = 0x7f; int len = s.length(); for (int index = 0; index < len; index++) { char c = s.charAt(index); if (c > LARGEST_BASIC_LATIN) { return false; } } return true; } /** * Determines whether the given name can appear on the right side of * the dot operator. Many properties (like reserved words) cannot. */ static boolean isValidPropertyName(String name) { return TokenStream.isJSIdentifier(name) && !TokenStream.isKeyword(name) && // no Unicode escaped characters - some browsers are less tolerant // of Unicode characters that might be valid according to the // language spec. // Note that by this point, unicode escapes have been converted // to UTF-16 characters, so we're only searching for character // values, not escapes. NodeUtil.isLatin(name); } private static class VarCollector implements Visitor { final Map<String, Node> vars = Maps.newLinkedHashMap(); public void visit(Node n) { if (n.getType() == Token.NAME) { Node parent = n.getParent(); if (parent != null && parent.getType() == Token.VAR) { String name = n.getString(); if (!vars.containsKey(name)) { vars.put(name, n); } } } } } /** * Retrieves vars declared in the current node tree, excluding descent scopes. */ public static Collection<Node> getVarsDeclaredInBranch(Node root) { VarCollector collector = new VarCollector(); visitPreOrder( root, collector, Predicates.<Node>not(new NodeUtil.MatchNodeType(Token.FUNCTION))); return collector.vars.values(); } /** * @return {@code true} if the node an assignment to a prototype property of * some constructor. */ static boolean isPrototypePropertyDeclaration(Node n) { if (!NodeUtil.isExprAssign(n)) { return false; } return isPrototypeProperty(n.getFirstChild().getFirstChild()); } static boolean isPrototypeProperty(Node n) { String lhsString = n.getQualifiedName(); if (lhsString == null) { return false; } int prototypeIdx = lhsString.indexOf(".prototype."); return prototypeIdx != -1; } /** * @return The class name part of a qualified prototype name. */ static Node getPrototypeClassName(Node qName) { Node cur = qName; while (isGetProp(cur)) { if (cur.getLastChild().getString().equals("prototype")) { return cur.getFirstChild(); } else { cur = cur.getFirstChild(); } } return null; } /** * @return The string property name part of a qualified prototype name. */ static String getPrototypePropertyName(Node qName) { String qNameStr = qName.getQualifiedName(); int prototypeIdx = qNameStr.lastIndexOf(".prototype."); int memberIndex = prototypeIdx + ".prototype".length() + 1; return qNameStr.substring(memberIndex); } /** * Create a node for an empty result expression: * "void 0" */ static Node newUndefinedNode() { // TODO(johnlenz): Why this instead of the more common "undefined"? return new Node(Token.VOID, Node.newNumber(0)); } /** * Create a VAR node containing the given name and initial value expression. */ static Node newVarNode(String name, Node value) { Node nodeName = Node.newString(Token.NAME, name); if (value != null) { nodeName.addChildrenToBack(value); } Node var = new Node(Token.VAR, nodeName); return var; } /** * A predicate for matching name nodes with the specified node. */ private static class MatchNameNode implements Predicate<Node>{ final String name; MatchNameNode(String name){ this.name = name; } public boolean apply(Node n) { return n.getType() == Token.NAME && n.getString().equals(name); } } /** * A predicate for matching nodes with the specified type. */ static class MatchNodeType implements Predicate<Node>{ final int type; MatchNodeType(int type){ this.type = type; } public boolean apply(Node n) { return n.getType() == type; } } /** * Whether a Node type is within the node tree. */ static boolean isNodeTypeReferenced(Node node, int type) { return isNodeTypeReferenced(node, type, Predicates.<Node>alwaysTrue()); } /** * Whether a Node type is within the node tree. */ static boolean isNodeTypeReferenced( Node node, int type, Predicate<Node> traverseChildrenPred) { return has(node, new MatchNodeType(type), traverseChildrenPred); } /** * Finds the number of times a type is referenced within the node tree. */ static int getNodeTypeReferenceCount(Node node, int type) { return getCount(node, new MatchNodeType(type)); } /** * Whether a simple name is referenced within the node tree. */ static boolean isNameReferenced(Node node, String name, Predicate<Node> traverseChildrenPred) { return has(node, new MatchNameNode(name), traverseChildrenPred); } /** * Whether a simple name is referenced within the node tree. */ static boolean isNameReferenced(Node node, String name) { return isNameReferenced(node, name, Predicates.<Node>alwaysTrue()); } /** * Finds the number of times a simple name is referenced within the node tree. */ static int getNameReferenceCount(Node node, String name) { return getCount(node, new MatchNameNode(name) ); } /** * @return Whether the predicate is true for the node or any of its children. */ static boolean has(Node node, Predicate<Node> pred, Predicate<Node> traverseChildrenPred) { if (pred.apply(node)) { return true; } if (!traverseChildrenPred.apply(node)) { return false; } for (Node c = node.getFirstChild(); c != null; c = c.getNext()) { if (has(c, pred, traverseChildrenPred)) { return true; } } return false; } /** * @return The number of times the the predicate is true for the node * or any of its children. */ static int getCount(Node n, Predicate<Node> pred) { int total = 0; if (pred.apply(n)) { total++; } for (Node c = n.getFirstChild(); c != null; c = c.getNext()) { total += getCount(c, pred); } return total; } /** * Interface for use with the visit method. * @see #visit */ static interface Visitor { void visit(Node node); } /** * A pre-order traversal, calling Vistor.visit for each child matching * the predicate. */ static void visitPreOrder(Node node, Visitor vistor, Predicate<Node> traverseChildrenPred) { vistor.visit(node); if (traverseChildrenPred.apply(node)) { for (Node c = node.getFirstChild(); c != null; c = c.getNext()) { visitPreOrder(c, vistor, traverseChildrenPred); } } } /** * A post-order traversal, calling Vistor.visit for each child matching * the predicate. */ static void visitPostOrder(Node node, Visitor vistor, Predicate<Node> traverseChildrenPred) { if (traverseChildrenPred.apply(node)) { for (Node c = node.getFirstChild(); c != null; c = c.getNext()) { visitPostOrder(c, vistor, traverseChildrenPred); } } vistor.visit(node); } /** * @return Whether a TRY node has a finally block. */ static boolean hasFinally(Node n) { Preconditions.checkArgument(n.getType() == Token.TRY); return n.getChildCount() == 3; } /** * @return The BLOCK node containing the CATCH node (if any) * of a TRY. */ static Node getCatchBlock(Node n) { Preconditions.checkArgument(n.getType() == Token.TRY); return n.getFirstChild().getNext(); } /** * @return Whether BLOCK (from a TRY node) contains a CATCH. * @see NodeUtil#getCatchBlock */ static boolean hasCatchHandler(Node n) { Preconditions.checkArgument(n.getType() == Token.BLOCK); return n.hasChildren() && n.getFirstChild().getType() == Token.CATCH; } /** * @param fnNode The function. * @return The Node containing the Function parameters. */ static Node getFnParameters(Node fnNode) { // Function NODE: [ FUNCTION -> NAME, LP -> ARG1, ARG2, ... ] Preconditions.checkArgument(fnNode.getType() == Token.FUNCTION); return fnNode.getFirstChild().getNext(); } /** * Returns true if a name node represents a constant variable. * * <p>Determining whether a variable is constant has three steps: * <ol> * <li>In CodingConventionAnnotator, any name that matches the * {@link CodingConvention#isConstant(String)} is annotated with an * IS_CONSTANT_NAME property. * <li>The normalize pass renames any variable with the IS_CONSTANT_NAME * annotation and that is initialized to a constant value with * a variable name inlucding $$constant. * <li>Return true here if the variable includes $$constant in its name. * </ol> * * @param node A NAME or STRING node * @return True if the variable is constant */ static boolean isConstantName(Node node) { return node.getString().contains(CONSTANT_MARKER); } /** * @param nameNode A name node * @return The JSDocInfo for the name node */ static JSDocInfo getInfoForNameNode(Node nameNode) { JSDocInfo info = null; Node parent = null; if (nameNode != null) { info = nameNode.getJSDocInfo(); parent = nameNode.getParent(); } if (info == null && parent != null && ((parent.getType() == Token.VAR && parent.hasOneChild()) || parent.getType() == Token.FUNCTION)) { info = parent.getJSDocInfo(); } return info; } /** * @param n The node. * @return The source name property on the node or its ancestors. */ static String getSourceName(Node n) { String sourceName = null; while (sourceName == null && n != null) { sourceName = (String) n.getProp(Node.SOURCENAME_PROP); n = n.getParent(); } return sourceName; } } diff --git a/src/com/google/javascript/jscomp/SemanticReverseAbstractInterpreter.java b/src/com/google/javascript/jscomp/SemanticReverseAbstractInterpreter.java index 44305f722..f86ee8f68 100644 --- a/src/com/google/javascript/jscomp/SemanticReverseAbstractInterpreter.java +++ b/src/com/google/javascript/jscomp/SemanticReverseAbstractInterpreter.java @@ -1,548 +1,548 @@ /* * Copyright 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import static com.google.javascript.rhino.jstype.JSTypeNative.UNKNOWN_TYPE; import com.google.common.base.Function; import com.google.common.base.Pair; import com.google.javascript.rhino.jstype.FunctionType; import com.google.javascript.rhino.jstype.JSType; import com.google.javascript.rhino.jstype.JSTypeNative; import com.google.javascript.rhino.jstype.JSTypeRegistry; import com.google.javascript.rhino.jstype.ObjectType; import com.google.javascript.rhino.jstype.StaticSlot; import com.google.javascript.rhino.jstype.UnionType; import com.google.javascript.rhino.jstype.Visitor; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; /** * A reverse abstract interpreter using the semantics of the JavaScript * language as a means to reverse interpret computations. This interpreter * expects the parse tree inputs to be typed. * * */ class SemanticReverseAbstractInterpreter extends ChainableReverseAbstractInterpreter { /** * Merging function for equality between types. */ private static final Function<Pair<JSType, JSType>, Pair<JSType, JSType>> EQ = new Function<Pair<JSType, JSType>, Pair<JSType, JSType>>() { public Pair<JSType, JSType> apply(Pair<JSType, JSType> p) { if (p.first == null || p.second == null) { return null; } return p.first.getTypesUnderEquality(p.second); } }; /** * Merging function for non-equality between types. */ private static final Function<Pair<JSType, JSType>, Pair<JSType, JSType>> NE = new Function<Pair<JSType, JSType>, Pair<JSType, JSType>>() { public Pair<JSType, JSType> apply(Pair<JSType, JSType> p) { if (p.first == null || p.second == null) { return null; } return p.first.getTypesUnderInequality(p.second); } }; /** * Merging function for strict equality between types. */ private static final Function<Pair<JSType, JSType>, Pair<JSType, JSType>> SHEQ = new Function<Pair<JSType, JSType>, Pair<JSType, JSType>>() { public Pair<JSType, JSType> apply(Pair<JSType, JSType> p) { if (p.first == null || p.second == null) { return null; } return p.first.getTypesUnderShallowEquality(p.second); } }; /** * Merging function for strict non-equality between types. */ private static final Function<Pair<JSType, JSType>, Pair<JSType, JSType>> SHNE = new Function<Pair<JSType, JSType>, Pair<JSType, JSType>>() { public Pair<JSType, JSType> apply(Pair<JSType, JSType> p) { if (p.first == null || p.second == null) { return null; } return p.first.getTypesUnderShallowInequality(p.second); } }; /** * Merging function for inequality comparisons between types. */ private final Function<Pair<JSType, JSType>, Pair<JSType, JSType>> INEQ = new Function<Pair<JSType, JSType>, Pair<JSType, JSType>>() { public Pair<JSType, JSType> apply(Pair<JSType, JSType> p) { return new Pair<JSType, JSType>( getRestrictedWithoutUndefined(p.first), getRestrictedWithoutUndefined(p.second)); } }; /** * Creates a semantic reverse abstract interpreter. */ SemanticReverseAbstractInterpreter(CodingConvention convention, JSTypeRegistry typeRegistry) { super(convention, typeRegistry); } public FlowScope getPreciserScopeKnowingConditionOutcome(Node condition, FlowScope blindScope, boolean outcome) { // Check for the typeof operator. switch (condition.getType()) { case Token.EQ: case Token.NE: case Token.SHEQ: case Token.SHNE: Node left = condition.getFirstChild(); Node right = condition.getLastChild(); Node typeOfNode = null; Node stringNode = null; if (left.getType() == Token.TYPEOF && right.getType() == Token.STRING) { typeOfNode = left; stringNode = right; } else if (right.getType() == Token.TYPEOF && left.getType() == Token.STRING) { typeOfNode = right; stringNode = left; } if (typeOfNode != null && stringNode != null) { Node operandNode = typeOfNode.getFirstChild(); JSType operandType = getTypeIfRefinable(operandNode, blindScope); if (operandType != null) { boolean resultEqualsValue = condition.getType() == Token.EQ || condition.getType() == Token.SHEQ; if (!outcome) { resultEqualsValue = !resultEqualsValue; } return caseTypeOf(operandNode, operandType, stringNode.getString(), resultEqualsValue, blindScope); } } } switch (condition.getType()) { case Token.AND: if (outcome) { return caseAndOrNotShortCircuiting(condition.getFirstChild(), condition.getLastChild(), blindScope, true); } else { return caseAndOrMaybeShortCircuiting(condition.getFirstChild(), condition.getLastChild(), blindScope, true); } case Token.OR: if (!outcome) { return caseAndOrNotShortCircuiting(condition.getFirstChild(), condition.getLastChild(), blindScope, false); } else { return caseAndOrMaybeShortCircuiting(condition.getFirstChild(), condition.getLastChild(), blindScope, false); } case Token.EQ: if (outcome) { return caseEquality(condition, blindScope, EQ); } else { return caseEquality(condition, blindScope, NE); } case Token.NE: if (outcome) { return caseEquality(condition, blindScope, NE); } else { return caseEquality(condition, blindScope, EQ); } case Token.SHEQ: if (outcome) { return caseEquality(condition, blindScope, SHEQ); } else { return caseEquality(condition, blindScope, SHNE); } case Token.SHNE: if (outcome) { return caseEquality(condition, blindScope, SHNE); } else { return caseEquality(condition, blindScope, SHEQ); } case Token.NAME: case Token.GETPROP: return caseNameOrGetProp(condition, blindScope, outcome); case Token.ASSIGN: return firstPreciserScopeKnowingConditionOutcome( condition.getFirstChild(), firstPreciserScopeKnowingConditionOutcome( condition.getFirstChild().getNext(), blindScope, outcome), outcome); case Token.NOT: return firstPreciserScopeKnowingConditionOutcome( condition.getFirstChild(), blindScope, !outcome); case Token.LE: case Token.LT: case Token.GE: case Token.GT: if (outcome) { return caseEquality(condition, blindScope, INEQ); } break; case Token.INSTANCEOF: return caseInstanceOf( condition.getFirstChild(), condition.getLastChild(), blindScope, outcome); case Token.IN: if (outcome && condition.getFirstChild().getType() == Token.STRING) { return caseIn(condition.getLastChild(), condition.getFirstChild().getString(), blindScope); } break; } return nextPreciserScopeKnowingConditionOutcome( condition, blindScope, outcome); } private FlowScope caseEquality(Node condition, FlowScope blindScope, Function<Pair<JSType, JSType>, Pair<JSType, JSType>> merging) { Node left = condition.getFirstChild(); Node right = condition.getLastChild(); // left type JSType leftType = getTypeIfRefinable(left, blindScope); boolean leftIsRefineable; if (leftType != null) { leftIsRefineable = true; } else { leftIsRefineable = false; leftType = left.getJSType(); } // right type JSType rightType = getTypeIfRefinable(right, blindScope); boolean rightIsRefineable; if (rightType != null) { rightIsRefineable = true; } else { rightIsRefineable = false; rightType = right.getJSType(); } // merged types Pair<JSType, JSType> merged = merging.apply(Pair.of(leftType, rightType)); // creating new scope if (merged != null && ((leftIsRefineable && merged.first != null) || (rightIsRefineable && merged.second != null))) { FlowScope informed = blindScope.createChildFlowScope(); if (leftIsRefineable && merged.first != null) { declareNameInScope(informed, left, merged.first); } if (rightIsRefineable && merged.second != null) { declareNameInScope(informed, right, merged.second); } return informed; } return blindScope; } private FlowScope caseAndOrNotShortCircuiting(Node left, Node right, FlowScope blindScope, boolean condition) { // left type JSType leftType = getTypeIfRefinable(left, blindScope); boolean leftIsRefineable; if (leftType != null) { leftIsRefineable = true; } else { leftIsRefineable = false; leftType = left.getJSType(); blindScope = firstPreciserScopeKnowingConditionOutcome( left, blindScope, condition); } // restricting left type leftType = (leftType == null) ? null : leftType.getRestrictedTypeGivenToBooleanOutcome(condition); if (leftType == null) { return firstPreciserScopeKnowingConditionOutcome( right, blindScope, condition); } // right type JSType rightType = getTypeIfRefinable(right, blindScope); boolean rightIsRefineable; if (rightType != null) { rightIsRefineable = true; } else { rightIsRefineable = false; rightType = right.getJSType(); blindScope = firstPreciserScopeKnowingConditionOutcome( right, blindScope, condition); } if (condition) { rightType = (rightType == null) ? null : rightType.getRestrictedTypeGivenToBooleanOutcome(condition); // creating new scope if ((leftType != null && leftIsRefineable) || (rightType != null && rightIsRefineable)) { FlowScope informed = blindScope.createChildFlowScope(); if (leftIsRefineable && leftType != null) { declareNameInScope(informed, left, leftType); } if (rightIsRefineable && rightType != null) { declareNameInScope(informed, right, rightType); } return informed; } } return blindScope; } private FlowScope caseAndOrMaybeShortCircuiting(Node left, Node right, FlowScope blindScope, boolean condition) { FlowScope leftScope = firstPreciserScopeKnowingConditionOutcome( left, blindScope, !condition); StaticSlot<JSType> leftVar = leftScope.findUniqueRefinedSlot(blindScope); if (leftVar == null) { return blindScope; } FlowScope rightScope = firstPreciserScopeKnowingConditionOutcome( left, blindScope, condition); rightScope = firstPreciserScopeKnowingConditionOutcome( right, rightScope, !condition); StaticSlot<JSType> rightVar = rightScope.findUniqueRefinedSlot(blindScope); if (rightVar == null || !leftVar.getName().equals(rightVar.getName())) { return blindScope; } JSType type = leftVar.getType().getLeastSupertype(rightVar.getType()); FlowScope informed = blindScope.createChildFlowScope(); informed.inferSlotType(leftVar.getName(), type); return informed; } private FlowScope caseNameOrGetProp(Node name, FlowScope blindScope, boolean outcome) { JSType type = getTypeIfRefinable(name, blindScope); if (type != null) { JSType restrictedType = type.getRestrictedTypeGivenToBooleanOutcome(outcome); FlowScope informed = blindScope.createChildFlowScope(); declareNameInScope(informed, name, restrictedType); return informed; } return blindScope; } private FlowScope caseTypeOf(Node node, JSType type, String value, boolean resultEqualsValue, FlowScope blindScope) { JSType restrictedType = getRestrictedByTypeOfResult(type, value, resultEqualsValue); if (restrictedType == null) { return blindScope; } FlowScope informed = blindScope.createChildFlowScope(); declareNameInScope(informed, node, restrictedType); return informed; } private FlowScope caseInstanceOf(Node left, Node right, FlowScope blindScope, boolean outcome) { JSType leftType = getTypeIfRefinable(left, blindScope); if (leftType == null) { return blindScope; } JSType rightType = right.getJSType(); ObjectType targetType = typeRegistry.getNativeObjectType(JSTypeNative.UNKNOWN_TYPE); if (rightType instanceof FunctionType) { targetType = (FunctionType) rightType; } Visitor<JSType> visitor; if (outcome) { visitor = new RestrictByTrueInstanceOfResultVisitor(targetType); } else { visitor = new RestrictByFalseInstanceOfResultVisitor(targetType); } JSType restrictedLeftType = leftType.visit(visitor); if (restrictedLeftType != null && !restrictedLeftType.equals(leftType)) { FlowScope informed = blindScope.createChildFlowScope(); declareNameInScope(informed, left, restrictedLeftType); return informed; } return blindScope; } /** * Given 'property in object', ensures that the object has the property in the * informed scope by defining it as a qualified name if the object type lacks * the property and it's not in the blind scope. * @param object The node of the right-side of the in. * @param propertyName The string of the left-side of the in. */ private FlowScope caseIn(Node object, String propertyName, FlowScope blindScope) { JSType objectType = object.getJSType(); objectType = this.getRestrictedWithoutNull(objectType); objectType = this.getRestrictedWithoutUndefined(objectType); boolean hasProperty = false; if (objectType instanceof ObjectType) { hasProperty = ((ObjectType) objectType).hasProperty(propertyName); } if (!hasProperty) { String qualifiedName = object.getQualifiedName(); if (qualifiedName != null) { String propertyQualifiedName = qualifiedName + "." + propertyName; if (blindScope.getSlot(propertyQualifiedName) == null) { FlowScope informed = blindScope.createChildFlowScope(); JSType unknownType = typeRegistry.getNativeType( JSTypeNative.UNKNOWN_TYPE); informed.inferQualifiedSlot( propertyQualifiedName, unknownType, unknownType); return informed; } } } return blindScope; } /** * @see SemanticReverseAbstractInterpreter#caseInstanceOf */ private class RestrictByTrueInstanceOfResultVisitor extends RestrictByTrueTypeOfResultVisitor { private final ObjectType target; RestrictByTrueInstanceOfResultVisitor(ObjectType target) { this.target = target; } @Override - protected JSType caseTopType(JSType topType) { - return topType; + protected JSType caseTopType(JSType type) { + return applyCommonRestriction(type); } @Override public JSType caseUnknownType() { if (target instanceof FunctionType) { FunctionType funcTarget = (FunctionType) target; if (funcTarget.hasInstanceType()) { return funcTarget.getInstanceType(); } } return getNativeType(UNKNOWN_TYPE); } @Override public JSType caseObjectType(ObjectType type) { return applyCommonRestriction(type); } @Override public JSType caseUnionType(UnionType type) { return applyCommonRestriction(type); } @Override public JSType caseFunctionType(FunctionType type) { return caseObjectType(type); } private JSType applyCommonRestriction(JSType type) { if (target.isUnknownType()) { return type; } FunctionType funcTarget = (FunctionType) target; if (funcTarget.hasInstanceType()) { return type.getGreatestSubtype(funcTarget.getInstanceType()); } return null; } } /** * @see SemanticReverseAbstractInterpreter#caseInstanceOf */ private class RestrictByFalseInstanceOfResultVisitor extends RestrictByFalseTypeOfResultVisitor { private final ObjectType target; RestrictByFalseInstanceOfResultVisitor(ObjectType target) { this.target = target; } @Override public JSType caseObjectType(ObjectType type) { if (target.isUnknownType()) { return type; } FunctionType funcTarget = (FunctionType) target; if (funcTarget.hasInstanceType()) { if (type.isSubtype(funcTarget.getInstanceType())) { return null; } return type; } return null; } @Override public JSType caseUnionType(UnionType type) { if (target.isUnknownType()) { return type; } FunctionType funcTarget = (FunctionType) target; if (funcTarget.hasInstanceType()) { return type.getRestrictedUnion(funcTarget.getInstanceType()); } return null; } @Override public JSType caseFunctionType(FunctionType type) { return caseObjectType(type); } } }
false
false
null
null
diff --git a/SwipeBackLayout/src/main/java/me/imid/swipebacklayout/lib/SwipeBackLayout.java b/SwipeBackLayout/src/main/java/me/imid/swipebacklayout/lib/SwipeBackLayout.java index b2a236b..708dbfa 100644 --- a/SwipeBackLayout/src/main/java/me/imid/swipebacklayout/lib/SwipeBackLayout.java +++ b/SwipeBackLayout/src/main/java/me/imid/swipebacklayout/lib/SwipeBackLayout.java @@ -1,263 +1,276 @@ package me.imid.swipebacklayout.lib; import android.app.Activity; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Paint; +import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.support.v4.view.MotionEventCompat; import android.support.v4.view.ViewCompat; import android.util.AttributeSet; -import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; public class SwipeBackLayout extends FrameLayout { /** * Minimum velocity that will be detected as a fling */ private static final int MIN_FLING_VELOCITY = 400; // dips per second private static final int DEFAULT_SCRIM_COLOR = 0x99000000; // Cached ViewConfiguration and system-wide constant values private Activity mActivity; // Transient properties private boolean mEnable = true; private View mContentView; private ViewDragHelper mLeftDragHelper; private float mAnimationProgress; private Config mConfig; private OnScrollListener mOnScrollListener; private Drawable mShadow; private Paint mScrimPaint = new Paint(); private float mScrimOpacity; private int mScrimColor = DEFAULT_SCRIM_COLOR; + private Rect mChildRect = new Rect(); + + private Rect mLeftRect = new Rect(); + + private MotionEvent mCurEvent; + public SwipeBackLayout(Context context) { this(context, null); } public SwipeBackLayout(Context context, AttributeSet attrs) { super(context, attrs); final float density = getResources().getDisplayMetrics().density; final float minVel = MIN_FLING_VELOCITY * density; mLeftDragHelper = ViewDragHelper.create(this, new ViewDragCallback()); mLeftDragHelper.setEdgeTrackingEnabled(ViewDragHelper.EDGE_LEFT); mLeftDragHelper.setMinVelocity(minVel); setShadow(R.drawable.shadow); } public void setContentView(View view) { mContentView = view; } public void setEnableGesture(boolean enable) { mEnable = enable; } public void setOnScrollListener(OnScrollListener listener) { mOnScrollListener = listener; } public static interface OnScrollListener { public void onScroll(); public void onScrollEnd(); public void onReverseScroll(); public void onReverseScrollEnd(); } /** * Set a drawable used for edge shadow. * * @param shadow Drawable to use */ public void setShadow(Drawable shadow) { mShadow = shadow; invalidate(); } /** * Set a drawable used for edge shadow. * * @param resId Resource of drawable to use */ public void setShadow(int resId) { setShadow(getResources().getDrawable(resId)); } public static class Config { public static enum TouchMode { /** * Allow SwipeBackLayout to */ TOUCH_MODE_MARGIN, TOUCH_MODE_FULLSCREEN, TOUCH_MODE_PERCENTAGE } } @Override public boolean onInterceptTouchEvent(MotionEvent event) { if (!mEnable) { return false; } + mCurEvent = MotionEvent.obtain(event); final int action = MotionEventCompat.getActionMasked(event); final View contentView = mContentView; final boolean interceptForDrag = mLeftDragHelper.shouldInterceptTouchEvent(event); switch (action) { case MotionEvent.ACTION_DOWN: break; case MotionEvent.ACTION_MOVE: break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: break; default: break; } return interceptForDrag; } @Override public boolean onTouchEvent(MotionEvent event) { if (!mEnable) { return false; } - + mCurEvent = MotionEvent.obtain(event); mLeftDragHelper.processTouchEvent(event); final int action = MotionEventCompat.getActionMasked(event); final View contentView = mContentView; switch (action) { case MotionEvent.ACTION_DOWN: break; case MotionEvent.ACTION_UP: - case MotionEvent.ACTION_CANCEL: { - break; - } + case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_MOVE: break; } return true; } @Override protected boolean drawChild(Canvas canvas, View child, long drawingTime) { final boolean drawContent = child == mContentView; drawShadow(canvas, child); if (mScrimOpacity > 0 && drawContent && mLeftDragHelper.getViewDragState() != ViewDragHelper.STATE_IDLE) { drawScrim(canvas, child); } return super.drawChild(canvas, child, drawingTime); } private void drawScrim(Canvas canvas, View child) { final int restoreCount = canvas.save(); final int baseAlpha = (mScrimColor & 0xff000000) >>> 24; final int imag = (int) (baseAlpha * mScrimOpacity); final int color = imag << 24 | (mScrimColor & 0xffffff); mScrimPaint.setColor(color); canvas.clipRect(0, 0, child.getLeft(), getHeight()); canvas.drawRect(0, 0, getWidth(), getHeight(), mScrimPaint); canvas.restoreToCount(restoreCount); } private void drawShadow(Canvas canvas, View child) { final int shadowWidth = mShadow.getIntrinsicWidth(); final int childLeft = child.getLeft(); mShadow.setBounds(childLeft - shadowWidth, child.getTop(), childLeft, child.getBottom()); mShadow.draw(canvas); } public void attachToActivity(Activity activity) { mActivity = activity; TypedArray a = activity.getTheme().obtainStyledAttributes(new int[] { android.R.attr.windowBackground }); int background = a.getResourceId(0, 0); a.recycle(); ViewGroup decor = (ViewGroup) activity.getWindow().getDecorView(); ViewGroup decorChild = (ViewGroup) decor.getChildAt(0); decorChild.setBackgroundResource(background); decor.removeView(decorChild); addView(decorChild); setContentView(decorChild); decor.addView(this); } @Override public void computeScroll() { mScrimOpacity = 1 - mAnimationProgress; if (mLeftDragHelper.continueSettling(true)) { ViewCompat.postInvalidateOnAnimation(this); } } private class ViewDragCallback extends ViewDragHelper.Callback { @Override public boolean tryCaptureView(View view, int i) { - return view == mContentView; + final int x = (int) MotionEventCompat.getX(mCurEvent, i); + final int y = (int) MotionEventCompat.getY(mCurEvent, i); + mLeftRect.set(0, 0, getWidth() / 3, getHeight()); + return mLeftRect.contains(x, y); + } + + @Override + public int getViewHorizontalDragRange(View child) { + return 1; } @Override public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) { super.onViewPositionChanged(changedView, left, top, dx, dy); mAnimationProgress = (float) left / (mContentView.getWidth() + mShadow.getIntrinsicWidth()); invalidate(); } @Override public void onViewReleased(View releasedChild, float xvel, float yvel) { final int childWidth = releasedChild.getWidth(); final float offset = (float) releasedChild.getLeft() / releasedChild.getWidth(); int left; left = xvel > 0 || xvel == 0 && offset > 0.5f ? childWidth + mShadow.getIntrinsicWidth() : 0; mLeftDragHelper.settleCapturedViewAt(left, releasedChild.getTop()); invalidate(); } @Override public int clampViewPositionHorizontal(View child, int left, int dx) { return Math.min(child.getWidth(), Math.max(left, 0)); } @Override public void onViewDragStateChanged(int state) { super.onViewDragStateChanged(state); if (state == ViewDragHelper.STATE_IDLE) { if (mAnimationProgress == 1) { mActivity.finish(); } } } } }
false
false
null
null
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/FieldsProducer.java b/lucene/core/src/java/org/apache/lucene/codecs/FieldsProducer.java index d2862ad15..7ddc342b1 100644 --- a/lucene/core/src/java/org/apache/lucene/codecs/FieldsProducer.java +++ b/lucene/core/src/java/org/apache/lucene/codecs/FieldsProducer.java @@ -1,37 +1,35 @@ package org.apache.lucene.codecs; /** * 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.Closeable; import java.io.IOException; import org.apache.lucene.index.Fields; import org.apache.lucene.index.FieldsEnum; import org.apache.lucene.index.Terms; -/** Abstract API that consumes terms, doc, freq, prox and - * payloads postings. Concrete implementations of this - * actually do "something" with the postings (write it into - * the index in a specific format). +/** Abstract API that produces terms, doc, freq, prox and + * payloads postings. * * @lucene.experimental */ public abstract class FieldsProducer extends Fields implements Closeable { public abstract void close() throws IOException; }
true
false
null
null
diff --git a/src/java/grails/plugin/cloudfoundry/GrailsHttpRequestFactory.java b/src/java/grails/plugin/cloudfoundry/GrailsHttpRequestFactory.java index 4da7cb2..3a9ddb4 100644 --- a/src/java/grails/plugin/cloudfoundry/GrailsHttpRequestFactory.java +++ b/src/java/grails/plugin/cloudfoundry/GrailsHttpRequestFactory.java @@ -1,118 +1,123 @@ /* Copyright 2011 SpringSource. * * 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 grails.plugin.cloudfoundry; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.net.HttpURLConnection; import java.net.Proxy; import java.net.URI; import java.net.URL; import java.net.URLConnection; import net.sf.cglib.proxy.Callback; import net.sf.cglib.proxy.Enhancer; import net.sf.cglib.proxy.MethodInterceptor; import net.sf.cglib.proxy.MethodProxy; import org.apache.commons.io.input.ProxyInputStream; import org.springframework.http.HttpMethod; import org.springframework.http.client.ClientHttpRequest; import org.springframework.http.client.SimpleClientHttpRequestFactory; import org.springframework.util.Assert; /** * Extends SimpleClientHttpResponse to replace the HttpURLConnection's InputStream to one * that captures the response content. * * @author Burt Beckwith */ public class GrailsHttpRequestFactory extends SimpleClientHttpRequestFactory { private Proxy proxy; private static ByteArrayOutputStream bytes; /** * Get the content from the last request. Not thread-safe. * @return the content or null */ public static byte[] getLastResponse() { return bytes == null ? null : bytes.toByteArray(); } /** * Call before making a client call to reset any previous response. */ public static void resetResponse() { bytes = new ByteArrayOutputStream(); } /** * Sets the {@link Proxy} to use for this request factory. * @param proxy the proxy */ public void setProxy(Proxy proxy) { this.proxy = proxy; } @Override public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException { URL url = uri.toURL(); URLConnection urlConnection = proxy != null ? url.openConnection(proxy) : url.openConnection(); Assert.isInstanceOf(HttpURLConnection.class, urlConnection); prepareConnection((HttpURLConnection)urlConnection, httpMethod.name()); return new GrailsHttpRequest(wrap((HttpURLConnection)urlConnection)); } protected HttpURLConnection wrap(final HttpURLConnection connection) { Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(HttpURLConnection.class); enhancer.setInterceptDuringConstruction(false); Callback callback = new MethodInterceptor() { @SuppressWarnings("hiding") public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable { - Object value = method.invoke(connection, args); + try { + Object value = method.invoke(connection, args); - if ("getInputStream".equals(method.getName())) { - return wrap((InputStream)value); - } + if ("getInputStream".equals(method.getName())) { + return wrap((InputStream)value); + } - return value; + return value; + } + catch (java.lang.reflect.InvocationTargetException ex) { + throw ex.getCause(); + } } }; enhancer.setCallbacks(new Callback[] { callback }); enhancer.setCallbackTypes(new Class[] { callback.getClass() }); return (HttpURLConnection)enhancer.create( new Class[] { URL.class }, new Object[] { connection.getURL() }); } protected InputStream wrap(final InputStream inputStream) { return new ProxyInputStream(inputStream) { @Override public int read(byte[] bts, int st, int end) throws IOException { int count = super.read(bts, st, end); if (count > 0) { bytes.write(bts, st, st + count); } return count; } }; } -} \ No newline at end of file +}
false
false
null
null
diff --git a/src/MixxitListener.java b/src/MixxitListener.java index 16b53b7..7815d78 100644 --- a/src/MixxitListener.java +++ b/src/MixxitListener.java @@ -1,1612 +1,1616 @@ import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Random; import java.util.Timer; import java.util.logging.Logger; public class MixxitListener extends PluginListener { public PropertiesFile properties = new PropertiesFile("MixxitPlugin.properties"); public PropertiesFile guilds = new PropertiesFile("MixxitPlugin.guilds"); PropertiesFile configPlayers; static final Logger log = Logger.getLogger("Minecraft"); boolean pvp = false; boolean pvpteams = true; boolean dropinventory = true; boolean boomers = false; public int totaldmg = 0; public int totalplydmg = 0; public int countcompress2 = 0; public int countcompress3 = 0; public int countcompress4 = 0; public int countcompress5 = 0; int Combattimer = 700; int woodensword = 6; int stonesword = 7; int ironsword = 8; int goldsword = 10; int diamondsword = 20; int woodenspade = 4; int stonespade = 5; int ironspade = 6; int goldspade = 8; int diamondspade = 10; int woodenpickaxe = 4; int stonepickaxe = 5; int ironpickaxe = 6; int goldpickaxe = 8; int diamondpickaxe = 10; int woodenaxe = 5; int stoneaxe = 6; int ironaxe = 7; int goldaxe = 10; int diamondaxe = 18; int basedamage = 3; int goldenapple = 100; int friedbacon = 20; int apple = 10; int bread = 15; public Timer timer; public Timer saveTimer; public ArrayList<MixxitPlayer> playerList; public ArrayList<MixxitGuild> guildList; public MixxitListener() { this.timer = new Timer(); this.timer.scheduleAtFixedRate(new RemindTask(this), 0L, this.Combattimer); //System.out.println(getDateTime() + " [INFO] Melee Combat Task Scheduled."); log.info("Melee Combat Task Scheduled."); this.playerList = new ArrayList<MixxitPlayer>(); this.guildList = new ArrayList<MixxitGuild>(); loadPlayerList(); loadGuilds(); loadProperties(); } public void loadGuilds() { this.guilds = new PropertiesFile("MixxitPlugin.guilds"); this.guilds.load(); // max 1000 guilds for (int i = 1; i < 1001; i++) { try { String fileval = this.guilds.getString(Integer.toString(i), "0:Default Guild:Nobody"); if (fileval.equals("0:Default Guild:Nobody") == true) { // skip } else { String[] guilddata = fileval.split(":"); if (Integer.parseInt(guilddata[0]) > 0 && !guilddata[1].equals("") && !guilddata[1].equals("Default Guild") && !guilddata[2].equals("Nobody") && !guilddata[2].equals("")) { MixxitGuild newguild = new MixxitGuild(); newguild.guildid = Integer.parseInt(guilddata[0]); newguild.name = guilddata[1]; newguild.owner = guilddata[2]; newguild.home = guilddata[3]; System.out.println(getDateTime() + "[DEBUG] Guild Loaded: " + newguild.guildid + ":" + newguild.name); this.guildList.add(newguild); } } } catch (Exception localException) { } } } public void loadProperties() { this.properties = new PropertiesFile("MixxitPlugin.properties"); this.properties.load(); try { this.pvp = this.properties.getBoolean("pvp", false); this.pvpteams = this.properties.getBoolean("pvpteams", true); this.dropinventory = this.properties.getBoolean("drop-inventory", true); this.Combattimer = this.properties.getInt("combat-timer", 700); this.boomers = this.properties.getBoolean("boomers", false); this.woodensword = this.properties.getInt("wooden-sword", 6); this.stonesword = this.properties.getInt("stone-sword", 7); this.ironsword = this.properties.getInt("iron-sword", 8); this.goldsword = this.properties.getInt("gold-sword", 10); this.diamondsword = this.properties.getInt("diamond-sword", 20); this.woodenspade = this.properties.getInt("wooden-spade", 4); this.stonespade = this.properties.getInt("stone-spade", 5); this.ironspade = this.properties.getInt("iron-spade", 6); this.goldspade = this.properties.getInt("gold-spade", 8); this.diamondspade = this.properties.getInt("diamond-spade", 10); this.woodenpickaxe = this.properties.getInt("wooden-pickaxe", 4); this.stonepickaxe = this.properties.getInt("stone-pickaxe", 5); this.ironpickaxe = this.properties.getInt("iron-pickaxe", 6); this.goldpickaxe = this.properties.getInt("gold-pickaxe", 8); this.diamondpickaxe = this.properties.getInt("diamond-pickaxe", 10); this.woodenaxe = this.properties.getInt("wooden-axe", 5); this.stoneaxe = this.properties.getInt("stone-axe", 6); this.ironaxe = this.properties.getInt("iron-axe", 7); this.goldaxe = this.properties.getInt("gold-axe", 10); this.diamondaxe = this.properties.getInt("diamond-axe", 18); this.goldenapple = this.properties.getInt("goldenapple", 100); this.friedbacon = this.properties.getInt("friedbacon", 20); this.apple = this.properties.getInt("apple", 10); this.bread = this.properties.getInt("bread", 15); } catch (Exception localException) { } } public void loadPlayerList() { try { DataInputStream in = new DataInputStream(new FileInputStream("MixxitPlugin.txt")); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String line; while ((line = br.readLine()) != null) { if (line.substring(0, 1).matches("[#]")) { System.out.println(getDateTime() + " [DEBUG] Comment Skipped"); } else { String slashedstring = line.replace("\\:", ":"); String[] tokens = slashedstring.split("="); String[] params = tokens[1].split(":"); int curhp = 0; int curexp = 0; int curmelee = 0; int curlevel = 0; int curfaction = 0; int curguild = 0; int curstr = 0; int cursta = 0; int curagi = 0; int curdex = 0; int curint = 0; int curwis = 0; int curcha = 0; int curlck = 0; try { curhp = Integer.parseInt(params[0]); } catch (ArrayIndexOutOfBoundsException e) { } try { curexp = Integer.parseInt(params[1]); } catch (ArrayIndexOutOfBoundsException e) { } try { curmelee = Integer.parseInt(params[2]); } catch (ArrayIndexOutOfBoundsException e) { } try { curlevel = Integer.parseInt(params[3]); } catch (ArrayIndexOutOfBoundsException e) { } try { curfaction = Integer.parseInt(params[4]); } catch (ArrayIndexOutOfBoundsException e) { } try { curguild = Integer.parseInt(params[5]); } catch (ArrayIndexOutOfBoundsException e) { } try { curstr = Integer.parseInt(params[6]); } catch (ArrayIndexOutOfBoundsException e) { } try { cursta = Integer.parseInt(params[7]); } catch (ArrayIndexOutOfBoundsException e) { } try { curagi = Integer.parseInt(params[8]); } catch (ArrayIndexOutOfBoundsException e) { } try { curdex = Integer.parseInt(params[9]); } catch (ArrayIndexOutOfBoundsException e) { } try { curstr = Integer.parseInt(params[10]); } catch (ArrayIndexOutOfBoundsException e) { } try { curwis = Integer.parseInt(params[11]); } catch (ArrayIndexOutOfBoundsException e) { } try { curcha = Integer.parseInt(params[12]); } catch (ArrayIndexOutOfBoundsException e) { } try { curlck = Integer.parseInt(params[13]); } catch (ArrayIndexOutOfBoundsException e) { } MixxitPlayer curplayer = new MixxitPlayer(tokens[0], curhp); curplayer.exp = curexp; curplayer.melee = curmelee; curplayer.level = curlevel; curplayer.faction = curfaction; curplayer.guild = curguild; curplayer.stat_str = curstr; curplayer.stat_sta = cursta; curplayer.stat_agi = curagi; curplayer.stat_dex = curdex; curplayer.stat_int = curint; curplayer.stat_wis = curwis; curplayer.stat_cha = curcha; curplayer.stat_lck = curlck; this.playerList.add(curplayer); } } in.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public void packParameters() { System.out.println("Packing Parameters..."); } public void packGuilds() { System.out.println("Packing guilds..."); PropertiesFile configGuilds = new PropertiesFile("MixxitPlugin.guilds"); for (int i = 0; i < this.guildList.size(); i++) { String guildData = ((MixxitGuild)this.guildList.get(i)).guildid + ":" + ((MixxitGuild)this.guildList.get(i)).name + ":" + ((MixxitGuild)this.guildList.get(i)).owner + ":" + ((MixxitGuild)this.guildList.get(i)).home; System.out.println("Packing:" + guildData); configGuilds.setString(Integer.toString(((MixxitGuild)this.guildList.get(i)).guildid), guildData); } } public void packPlayers() { System.out.println("Packing players..."); configPlayers = new PropertiesFile("MixxitPlugin.txt"); for (int i = 0; i < this.playerList.size(); i++) { String playerData = ((MixxitPlayer)this.playerList.get(i)).hp + ":" + ((MixxitPlayer)this.playerList.get(i)).exp + ":" + ((MixxitPlayer)this.playerList.get(i)).melee + ":" + ((MixxitPlayer)this.playerList.get(i)).level + ":" + ((MixxitPlayer)this.playerList.get(i)).faction+ ":" + ((MixxitPlayer)this.playerList.get(i)).guild+ ":" + ((MixxitPlayer)this.playerList.get(i)).stat_str + ":" + ((MixxitPlayer)this.playerList.get(i)).stat_sta + ":" + ((MixxitPlayer)this.playerList.get(i)).stat_agi + ":" + ((MixxitPlayer)this.playerList.get(i)).stat_dex + ":" + ((MixxitPlayer)this.playerList.get(i)).stat_int + ":" + ((MixxitPlayer)this.playerList.get(i)).stat_wis + ":" + ((MixxitPlayer)this.playerList.get(i)).stat_cha + ":" + ((MixxitPlayer)this.playerList.get(i)).stat_lck; configPlayers.setString(((MixxitPlayer)this.playerList.get(i)).name, playerData); } } private String getDateTime() { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = new Date(); return dateFormat.format(date); } private double getDistance(Player a, Mob b) { double xPart = Math.pow(a.getX() - b.getX(), 2.0D); double yPart = Math.pow(a.getY() - b.getY(), 2.0D); double zPart = Math.pow(a.getZ() - b.getZ(), 2.0D); return Math.sqrt(xPart + yPart + zPart); // mixxit - doesnt work atm for some reason //return getRealDistance(a.getLocation(), new Location(b.getX(), b.getX(), b.getZ())); } private double getPlayerDistance(Player a, Player b) { return getRealDistance(a.getLocation(), b.getLocation()); } private double getRealDistance(Location a, Location b) { double xPart = Math.pow(a.x - b.x, 2.0D); double yPart = Math.pow(a.y - b.y, 2.0D); double zPart = Math.pow(a.z - b.z, 2.0D); return Math.sqrt(xPart + yPart + zPart); } public int getPlayerHP(Player player) { for (int i = 0; i < this.playerList.size(); i++) { if (this.playerList.get(i).name.equals(player.getName())) { return this.playerList.get(i).hp; } } return 0; } public void setPlayerHP(Player player, Integer newhp) { for (int i = 0; i < this.playerList.size(); i++) { if (!this.playerList.get(i).name.equals(player.getName())) continue; int finalhp; if (newhp.intValue() > getMaxBaseHealth(player)) { finalhp = getMaxBaseHealth(player); } else { finalhp = newhp.intValue(); } ((MixxitPlayer)this.playerList.get(i)).hp = finalhp; } } public int getPlayerMelee(Player player) { for (int i = 0; i < this.playerList.size(); i++) { if (this.playerList.get(i).name.equals(player.getName())) { return this.playerList.get(i).melee; } } return 0; } public void DoPanic(Mob m, Player p, int basedamage) { double dist = getDistance(p, m); if (dist <= 2.0D) { p.sendMessage("Distance check:" + dist); Random generator = new Random(); int index = generator.nextInt(basedamage); int thisdmg = index; if (getCombatLog(p) == 1) { p.sendMessage("The " + m.getName() + " hit you back! For " + thisdmg + " damage! (CurrHP: " + p.getHealth() + "/" + getMaxBaseHealth(p) + ")"); } if (p.getHealth() < thisdmg) { p.sendMessage("You have been slain!"); p.teleportTo(etc.getServer().getSpawnLocation()); } else { p.setHealth(p.getHealth() - thisdmg); } } } public int getPlayerLevel(Player player) { for (int i = 0; i < this.playerList.size(); i++) { if (this.playerList.get(i).name.equals(player.getName())) { return this.playerList.get(i).level; } } return -1; } public void setPlayerLevel(Player player, int level) { for (int i = 0; i < this.playerList.size(); i++) { if (((MixxitPlayer)this.playerList.get(i)).name.equals(player.getName())) { ((MixxitPlayer)this.playerList.get(i)).level = level; player.sendMessage("Congratulations, you reached Level " + level + "!"); this.playerList.get(i).stat_str++; this.playerList.get(i).stat_sta++; this.playerList.get(i).stat_agi++; this.playerList.get(i).stat_dex++; this.playerList.get(i).stat_int++; this.playerList.get(i).stat_wis++; this.playerList.get(i).stat_lck++; } } } public boolean isPlayerPVP(Player player) { for (int i = 0; i < this.playerList.size(); i++) { if (this.playerList.get(i).name.equals(player.getName())) { if (this.playerList.get(i).faction > 0) { return true; } } } return false; } public int getPlayerFaction(Player player) { for (int i = 0; i < this.playerList.size(); i++) { if (this.playerList.get(i).name.equals(player.getName())) { return this.playerList.get(i).faction; } } return -1; } public void setPlayerFaction(Player player, int faction) { for (int i = 0; i < this.playerList.size(); i++) { if (this.playerList.get(i).name.equals(player.getName())) { if (faction == 0) { this.playerList.get(i).faction = faction; player.sendMessage("Your have joined the ranks of the Civilians. Phew!"); } if (faction == 1) { this.playerList.get(i).faction = faction; player.sendMessage("Your have joined the ranks of the Villains!"); } if (faction == 2) { this.playerList.get(i).faction = faction; player.sendMessage("You have joined the ranks of the Heroes!"); } } } } public void setCombatLog(Player player, int value) { for (int i = 0; i < this.playerList.size(); i++) { if (!((MixxitPlayer)this.playerList.get(i)).name.equals(player.getName())) continue; this.playerList.get(i).combatlog = value; } } public int getCombatLog(Player player) { for (int i = 0; i < this.playerList.size(); i++) { if (((MixxitPlayer)this.playerList.get(i)).name.equals(player.getName())) { return this.playerList.get(i).combatlog; } } return -1; } public void setGuildOwner(String playername, int guildid) { for (int i = 0; i < this.guildList.size(); i++) { if (((MixxitGuild)this.guildList.get(i)).guildid == guildid) { this.guildList.get(i).owner = playername; } } } public void setGuild(Player player, int value) { for (int i = 0; i < this.playerList.size(); i++) { if (!((MixxitPlayer)this.playerList.get(i)).name.equals(player.getName())) continue; ((MixxitPlayer)this.playerList.get(i)).guild = value; player.sendMessage("Your guild (" + value + ") has been set."); } } public int getHighestGuildID() { int id = 0; for (int i = 0; i < this.guildList.size(); i++) { if (this.guildList.get(i).guildid > id) { id = this.guildList.get(i).guildid; } } return id; } public void createGuild(String name, String owner) { MixxitGuild newguild = new MixxitGuild(); newguild.guildid = getHighestGuildID() + 1; newguild.name = name; newguild.owner = owner; this.guildList.add(newguild); for (Player p : etc.getServer().getPlayerList()) { if (p.getName().equals(owner) == true) { setGuild(p,newguild.guildid); } } } public int getGuild(Player player) { for (int i = 0; i < this.playerList.size(); i++) { if (((MixxitPlayer)this.playerList.get(i)).name.equals(player.getName())) { return this.playerList.get(i).guild; } } return -1; } public String getPlayerGuildName(Player player) { return getGuildName(getGuild(player)); } public int getGuildID(String name) { for (int i = 0; i < this.guildList.size(); i++) { if (this.guildList.get(i).name.equals(name)) { return this.guildList.get(i).guildid; } } return 0; } public String getGuildOwner(String name) { for (int i = 0; i < this.guildList.size(); i++) { if (this.guildList.get(i).name.equals(name)) { return this.guildList.get(i).owner; } } return "Nobody"; } public String getGuildName(int id) { for (int i = 0; i < this.guildList.size(); i++) { if (this.guildList.get(i).guildid == id) { return this.guildList.get(i).name; } } return "Unguilded"; } public Player getPlayerByName(String name) { Player player = new Player(); for (Player p : etc.getServer().getPlayerList()) { if (p.getName().equals(name) == true) { player = p; } } return player; } public int getPlayerExperience(Player player) { for (int i = 0; i < this.playerList.size(); i++) { if (this.playerList.get(i).name.equals(player.getName())) { return this.playerList.get(i).exp; } } return 0; } public void getAllPlayers(Player player) { for (Player p : etc.getServer().getPlayerList()) { player.sendMessage(p.getName() + " - " + getPlayerGuildName(p) + " " + getFactionName(getPlayerFaction(p))); } } public String getFactionName(int faction) { if (faction == 0) { return "Civilian"; } if (faction == 1) { return "Villain"; } if (faction == 2) { return "Hero"; } return ""; } public int getMaxBaseHealth(Player player) { int bonus = (getPlayerByName(player).stat_sta + 5) * 5; return bonus; } public int getMaxBaseDamage(Player player) { int bonus = (getPlayerByName(player).stat_str + 5) * 5; return bonus; } public void setGuildHome(int guildid, String guildlocation) { for (int i = 0; i < this.guildList.size(); i++) { if (this.guildList.get(i).guildid == guildid) { this.guildList.get(i).home = guildlocation; } } } public String getGuildHome(int guildid) { String location = ""; for (int i = 0; i < this.guildList.size(); i++) { if (this.guildList.get(i).guildid == guildid) { return this.guildList.get(i).home; } } return location; } public void enableCombatLog(Player player) { player.sendMessage("Combat Log Enabled - to disable /disablecombatlog"); setCombatLog(player, 1); } public void disableCombatLog(Player player) { player.sendMessage("Combat Log Disabled - to enable /enablecombatlog"); setCombatLog(player, 0); } public void compressedCombatLog(Player player) { player.sendMessage("Combat Log Compressed"); setCombatLog(player, 2); } public boolean onCommand(Player player, String[] split) { if ((split[0].equalsIgnoreCase("/health")) && (player.canUseCommand("/health"))) { player.sendMessage("HP: " + getPlayerHP(player) + "/" + getMaxBaseHealth(player)); return true; } if ((split[0].equalsIgnoreCase("/enablecombatlog")) && (player.canUseCommand("/enablecombatlog"))) { enableCombatLog(player); return true; } if ((split[0].equalsIgnoreCase("/setguild")) && (player.canUseCommand("/setguild"))) { try { if (split[1].equals("") == true) { player.sendMessage("Syntax: <playername> <guildid>"); } else { setGuild(getPlayerByName(split[1]), Integer.parseInt(split[2])); player.sendMessage("Player set to guild."); } } catch (ArrayIndexOutOfBoundsException e) { player.sendMessage("Syntax: <playername> <guildid>"); } return true; } if ((split[0].equalsIgnoreCase("/createguild")) && (player.canUseCommand("/createguild"))) { try { if (split[1].equals("") == true) { player.sendMessage("Syntax: <playername> <guildname>"); } else { if (split[2].equals("") == true) { player.sendMessage("Syntax: <playername> <guildname>"); } else { createGuild(split[2],split[1]); } } } catch (ArrayIndexOutOfBoundsException e) { player.sendMessage("Syntax: <playername> <guildid>"); } return true; } if ((split[0].equalsIgnoreCase("/whoisguild")) && (player.canUseCommand("/whoisguild"))) { player.sendMessage(getGuildName(getPlayerGuildID(split[1])) + " Player Guild ID: "+ getPlayerGuildID(split[1])); return true; } if ((split[0].equalsIgnoreCase("/whois")) && (player.canUseCommand("/whois"))) { try { if (split[1].equals("") == true) { player.sendMessage("Syntax /whois <playername>"); } else { player.sendMessage("Level " + getPlayerLevel(getPlayerByName(split[1])) + " " + split[1] + " Faction: " + getFactionName(getPlayerFaction(getPlayerByName(split[1]))) + " Experience: " + getPlayerExperience(getPlayerByName(split[1]))); } } catch (ArrayIndexOutOfBoundsException e) { player.sendMessage("Syntax /whois <playername>"); } return true; } if ((split[0].equalsIgnoreCase("/setguildowner")) && (player.canUseCommand("/setguildowner"))) { setGuildOwner(split[1], Integer.parseInt(split[2])); return true; } if ((split[0].equalsIgnoreCase("/guilds")) && (player.canUseCommand("/guilds"))) { for (int i = 0; i < this.guildList.size(); i++) { int guildid = this.guildList.get(i).guildid; String guildname = this.guildList.get(i).name; player.sendMessage(guildid + " " + guildname); } return true; } if ((split[0].equalsIgnoreCase("/guild")) && (player.canUseCommand("/guild"))) { player.sendMessage("You are in guild: " + getPlayerGuildName(player)); return true; } if ((split[0].equalsIgnoreCase("/disablecombatlog")) && (player.canUseCommand("/disablecombatlog"))) { disableCombatLog(player); return true; } if ((split[0].equalsIgnoreCase("/compressedcombatlog")) && (player.canUseCommand("/compressedcombatlog"))) { compressedCombatLog(player); return true; } if ((split[0].equalsIgnoreCase("/pvpenable")) && (player.canUseCommand("/pvpenable"))) { this.pvp = true; player.sendMessage("PVP Free-for-all Enabled"); return true; } if ((split[0].equalsIgnoreCase("/pvpdisable")) && (player.canUseCommand("/pvpdisable"))) { this.pvp = false; player.sendMessage("PVP Disabled"); return true; } if ((split[0].equalsIgnoreCase("/heal")) && (player.canUseCommand("/heal"))) { setPlayerHP(player, Integer.valueOf(getMaxBaseHealth(player))); player.sendMessage("You have been fully healed. HP:" + getPlayerHP(player)+ "/" + getMaxBaseHealth(player) ); return true; } if ((split[0].equalsIgnoreCase("/MixxitDebug")) && (player.canUseCommand("/MixxitDebug"))) { player.sendMessage("You have been fully healed. HP: " + getPlayerHP(player)+ "/" + getMaxBaseHealth(player) ); player.sendMessage(" [DEBUG] MixxitPlugin - Properties Loader: pvp = " + this.pvp); player.sendMessage(" [DEBUG] MixxitPlugin - Properties Loader: drop inventory = " + this.dropinventory); player.sendMessage(" [DEBUG] MixxitPlugin - Properties Loader: combat timer = " + this.Combattimer); player.sendMessage(" [DEBUG] MixxitPlugin - Properties Loader: boomers = " + this.boomers); return true; } if ((split[0].equalsIgnoreCase("/level")) && (player.canUseCommand("/level"))) { player.sendMessage("Level: " + this.getPlayerLevel(player)); return true; } if ((split[0].equalsIgnoreCase("/enableboomers")) && (player.canUseCommand("/enableboomers"))) { player.sendMessage("Boomers enabled."); this.boomers = true; return true; } if ((split[0].equalsIgnoreCase("/disableboomers")) && (player.canUseCommand("/disableboomers"))) { player.sendMessage("Boomers disabled."); this.boomers = false; return true; } if ((split[0].equalsIgnoreCase("/setfaction")) && (player.canUseCommand("/setfaction"))) { String[] groups = { "default" }; groups[0] = "default"; if (split[1].equals(Integer.toString(1))) groups[0] = "evil"; if (split[1].equals(Integer.toString(2))) groups[0] = "good"; player.setGroups(groups); setPlayerFaction(player, Integer.parseInt(split[1])); return true; } if ((split[0].equalsIgnoreCase("/whoall")) && (player.canUseCommand("/whoall"))) { getAllPlayers(player); return true; } if ((split[0].equalsIgnoreCase("/setguildspawn")) && (player.canUseCommand("/setguildspawn"))) { player.sendMessage(getGuildOwner(getGuildName(getPlayerGuildID(player.getName())))); if (getGuildOwner(getGuildName(getPlayerGuildID(player.getName()))).equals(player.getName()) == true) { setGuildHome(getPlayerGuildID(player.getName()),player.getX() + "#"+player.getY() + "#"+ player.getZ()); player.sendMessage(getPlayerGuildID(player.getName())+ " Guild home set at your location " + player.getX() + ":"+player.getY() + ":"+ player.getZ()); } return true; } if ((split[0].equalsIgnoreCase("/guildspawn")) && (player.canUseCommand("/guildspawn"))) { for (int i = 0; i < this.guildList.size(); i++) { String guildData = ((MixxitGuild)this.guildList.get(i)).home; player.sendMessage(getPlayerGuildName(player) + " Home: " + guildData); if (!getGuildHome(getPlayerGuildID(player.getName())).equals("")) { String[] guildspawn = getGuildHome(getPlayerGuildID(player.getName())).split("[#]"); Location guildloc = new Location(); guildloc.x = Double.parseDouble(guildspawn[0]); guildloc.y = Double.parseDouble(guildspawn[1]); guildloc.z = Double.parseDouble(guildspawn[2]); player.teleportTo(guildloc); } } return true; } if ((split[0].equalsIgnoreCase("/guildlist")) && (player.canUseCommand("/guildlist"))) { try { if (split[1].equals("") == true) { player.sendMessage("Syntax /guildlist <guildname>"); } else { for (Player p : etc.getServer().getPlayerList()) { if (getGuildName(getGuild(p)).equals(split[1])) { player.sendMessage(p.getName() + " - " + getPlayerGuildName(p) + " " + getFactionName(getPlayerFaction(p))); } } } } catch (ArrayIndexOutOfBoundsException e) { player.sendMessage("Syntax /guildlist <guildname>"); } return true; } if ((split[0].equalsIgnoreCase("/stats")) && (player.canUseCommand("/stats"))) { for (int i = 0; i < this.playerList.size(); i++) { if (!((MixxitPlayer)this.playerList.get(i)).name.equals(player.getName())) continue; player.sendMessage("STR: " + Integer.toString(((MixxitPlayer)this.playerList.get(i)).stat_str)); player.sendMessage("STA: " + Integer.toString(((MixxitPlayer)this.playerList.get(i)).stat_sta)); player.sendMessage("AGI: " + Integer.toString(((MixxitPlayer)this.playerList.get(i)).stat_agi)); player.sendMessage("DEX: " + Integer.toString(((MixxitPlayer)this.playerList.get(i)).stat_dex)); player.sendMessage("INT: " + Integer.toString(((MixxitPlayer)this.playerList.get(i)).stat_int)); player.sendMessage("WIS: " + Integer.toString(((MixxitPlayer)this.playerList.get(i)).stat_wis)); player.sendMessage("CHA: " + Integer.toString(((MixxitPlayer)this.playerList.get(i)).stat_cha)); player.sendMessage("LCK: " + Integer.toString(((MixxitPlayer)this.playerList.get(i)).stat_lck)); } return true; } return false; } public void onLogin(Player player) { int exists = 0; for (int i = 0; i < this.playerList.size(); i++) { if (!((MixxitPlayer)this.playerList.get(i)).name.equals(player.getName())) continue; exists = 1; if (getPlayerHP(player) > getMaxBaseHealth(player)) { setPlayerHP(player,getMaxBaseHealth(player)); } player.sendMessage("Welcome back! HP: " + getPlayerHP(player)+ "/" + getMaxBaseHealth(player) ); player.sendMessage("PVP MODE: "+ this.pvp + " PVP Teams: " + this.pvpteams); player.sendMessage("Boomers: "+ this.boomers); } if (exists == 0) { MixxitPlayer play = new MixxitPlayer(player.getName(), 25); play.faction = 0; this.playerList.add(play); player.sendMessage("Welcome, you have been registered by the hp system! HP: " + getPlayerHP(player)+ "/" + getMaxBaseHealth(player) ); } } public void GiveExperience(Player player, int amount) { player.sendMessage("Pending experience..."); for (int i = 0; i < this.playerList.size(); i++) { if (!this.playerList.get(i).name.equals(player.getName())) { continue; } ((MixxitPlayer)this.playerList.get(i)).exp += amount; player.sendMessage("�eYou gain experience (" + this.playerList.get(i).exp + ")!"); - Random generator = new Random(); - int index = generator.nextInt(100); - - if (index != 1) - continue; - ((MixxitPlayer)this.playerList.get(i)).melee += 1; - player.sendMessage("�9You get better at melee! (" + this.playerList.get(i).melee + ")!"); + for (int ilevel = 1; ilevel < 41; ilevel++) { // c99koder - fix if (this.playerList.get(i).exp == (ilevel * 10) * ilevel) { setPlayerLevel(player, ilevel); } } + + Random generator = new Random(); + int index = generator.nextInt(100); + + if (index != 1) + continue; + ((MixxitPlayer)this.playerList.get(i)).melee += 1; + player.sendMessage("�9You get better at melee! (" + this.playerList.get(i).melee + ")!"); + + } } public int PlayerHasHit(Player player) { int melee = getPlayerMelee(player); Random generator = new Random(); int index = generator.nextInt(10); if (index + melee > 5) { return 1; } return 0; } public void DropPlayerItems(Player player) { for (int slot = 0; slot < 36; slot++) { try { Item item = player.getInventory().getItemFromSlot(slot); int itemid = item.getItemId(); int amount = item.getAmount(); player.giveItemDrop(itemid, amount); } catch (NullPointerException localNullPointerException) { } player.getInventory().removeItem(slot); } player.getInventory().updateInventory(); } public void DoPlayerDeath(Player player) { player.sendMessage("You have been slain"); if (this.dropinventory) { DropPlayerItems(player); } player.teleportTo(etc.getServer().getSpawnLocation()); setPlayerHP(player, Integer.valueOf(getMaxBaseHealth(player))); } public String getItemName(int itemId) { String itemname = "fashioned weapon"; if (itemId == 268) { itemname = "Wooden Sword"; } if (itemId == 272) { itemname = "Stone Sword"; } if (itemId == 267) { itemname = "Iron Sword"; } if (itemId == 283) { itemname = "Gold Sword"; } if (itemId == 276) { itemname = "Diamond Sword"; } return itemname; } public int getItemDamage(int itemId) { int itembasedamage = this.basedamage; if (itemId == 268) { itembasedamage = this.woodensword; } if (itemId == 269) { itembasedamage = this.woodenspade; } if (itemId == 270) { itembasedamage = this.woodenpickaxe; } if (itemId == 271) { itembasedamage = this.woodenaxe; } if (itemId == 272) { itembasedamage = this.stonesword; } if (itemId == 273) { itembasedamage = this.stonespade; } if (itemId == 274) { itembasedamage = this.stonepickaxe; } if (itemId == 275) { itembasedamage = this.stoneaxe; } if (itemId == 276) { itembasedamage = this.diamondsword; } if (itemId == 277) { itembasedamage = this.diamondspade; } if (itemId == 278) { itembasedamage = this.diamondpickaxe; } if (itemId == 279) { itembasedamage = this.diamondaxe; } if (itemId == 267) { itembasedamage = this.ironsword; } if (itemId == 256) { itembasedamage = this.ironspade; } if (itemId == 257) { itembasedamage = this.ironpickaxe; } if (itemId == 258) { itembasedamage = this.ironaxe; } if (itemId == 283) { itembasedamage = this.goldsword; } if (itemId == 284) { itembasedamage = this.goldspade; } if (itemId == 285) { itembasedamage = this.goldpickaxe; } if (itemId == 286) { itembasedamage = this.goldaxe; } return itembasedamage; } public MixxitPlayer getPlayerByName(Player player) { for (int i = 0; i < this.playerList.size(); i++) { if (!((MixxitPlayer)this.playerList.get(i)).name.equals(player.getName())) continue; return ((MixxitPlayer)this.playerList.get(i)); } return null; } public int getPlayerDamage(Player player) { int itemId = player.getItemInHand(); int damage = getItemDamage(itemId); damage += getPlayerMelee(player); Random generator = new Random(); int index = generator.nextInt(damage); index++; return index; } public int getPlayerGuildID(String name) { for (Player p : etc.getServer().getPlayerList()) { if (p.getName().equals(name) == true) { return getGuild(p); } } return 0; } public void onDisconnect(Player player) { SaveCombat saver = new SaveCombat(this); saver.run(); } public long getPlayerLastMove(Player player) { long lastmove = 0; for (int i = 0; i < this.playerList.size(); i++) { if (((MixxitPlayer)this.playerList.get(i)).name.equals(player.getName())) { return ((MixxitPlayer)this.playerList.get(i)).lastmove; } } return lastmove; } public long setPlayerLastMove(Player player) { long lastmove = 0; for (int i = 0; i < this.playerList.size(); i++) { if (this.playerList.get(i).name.equals(player.getName())) { return this.playerList.get(i).lastmove = System.currentTimeMillis()/1000; } } return lastmove; } public void onArmSwing(Player player) { // this prevents people from spamming attack too fast (defaults to combattimer (700)) if ((System.currentTimeMillis()/1000 - this.Combattimer/1000) <= getPlayerLastMove(player)) { //player.sendMessage("You must wait before making another attack." + (System.currentTimeMillis()/1000 - this.Combattimer/1000) + "<=" + getPlayerLastMove(player)); return; } //long lastmove = 0; // This was local? // records time of current armswing for (int i = 0; i < this.playerList.size(); i++) { if (((MixxitPlayer)this.playerList.get(i)).name.equals(player.getName())) { ((MixxitPlayer)this.playerList.get(i)).lastmove = System.currentTimeMillis()/1000; //player.sendMessage("lastmove set:" + getPlayerLastMove(player)); //lastmove = ((MixxitPlayer)this.playerList.get(i)).lastmove; } } int iteminhand = player.getItemInHand(); Inventory inv; if ((iteminhand == 297) || (iteminhand == 260) || (iteminhand == 320) || (iteminhand == 322)) { String item = ""; if (iteminhand == 322) { setPlayerHP(player, Integer.valueOf(getMaxBaseHealth(player))); player.sendMessage("The golden apple heals you to full health."); } if (iteminhand == 320) { setPlayerHP(player, Integer.valueOf(getPlayerHP(player) + 20)); item = "fried bacon"; } if (iteminhand == 260) { setPlayerHP(player, Integer.valueOf(getPlayerHP(player) + 10)); item = "apple"; } if (iteminhand == 297) { setPlayerHP(player, Integer.valueOf(getPlayerHP(player) + 15)); item = "bread"; } if (getPlayerHP(player) < getMaxBaseHealth(player)) { player.sendMessage("The " + item + " heals you to " + player.getHealth() + "."); } else { player.sendMessage("The " + item + " heals you to full health."); setPlayerHP(player, Integer.valueOf(getMaxBaseHealth(player))); } inv = player.getInventory(); // can't do this, it needs the slot id from getiteminhand //inv.removeItem(player.getItemInHand()); inv.removeItem(inv.getItemFromId(iteminhand).getSlot()); // Messy but works somewhat. inv.updateInventory(); } //player.sendMessage("Debug - checking mob list"); for (Mob m : etc.getServer().getMobList()) { if (m != null) { double dist = getDistance(player, m); if (dist >= 2.0D) continue; if (PlayerHasHit(player) == 0) { if (m.getHealth() < 1) { continue; } // player.sendMessage("Debug - missed"); if (getCombatLog(player) == 1) { player.sendMessage("�7You try to strike a " + m.getName() + " HP: (" + m.getHealth() + ") but miss! Your HP: " + getPlayerHP(player)+ "/" + getMaxBaseHealth(player) ); } else { if (getCombatLog(player) != 2) continue; if (this.countcompress3 == 6) { player.sendMessage("You have missed " + this.countcompress3 + " times. Current Health: " + getPlayerHP(player) + "."); this.countcompress3 = 0; } else { this.countcompress3 += 1; } } } else { if (m.getHealth() < 1) { continue; } //player.sendMessage("Debug - hit"); int thisdmg = getPlayerDamage(player); this.totaldmg += thisdmg; if (getCombatLog(player) == 1) { player.sendMessage("You strike " + m.getName() + " HP: (" + m.getHealth() + ") for " + thisdmg + " damage. Your HP: " + getPlayerHP(player)+ "/" + getMaxBaseHealth(player) ); } else if (getCombatLog(player) == 2) { if (this.countcompress2 == 4) { player.sendMessage("Total damage done " + this.totaldmg + ". Current Health: " + getPlayerHP(player) + "."); this.countcompress2 = 0; this.totaldmg = 0; } else { this.countcompress2 += 1; } } if (m.getHealth() <= thisdmg) { player.sendMessage("You have slain a " + m.getName() + "!"); m.setHealth(0); GiveExperience(player, 1); } else { m.setHealth(m.getHealth() - thisdmg); } } } } for (Player p : etc.getServer().getPlayerList()) { if ((p == null) || (p.getName() == player.getName())) { continue; } if (!this.pvp && !this.pvpteams) continue; if (pvpteams) { if (isPlayerPVP(p) == false) continue; if (isPlayerPVP(player) == false) continue; if (isPlayerPVP(player) == true && isPlayerPVP(p) == true) { if (getPlayerFaction(player) == getPlayerFaction(p)) { continue; } } else { continue; } } double dist = getPlayerDistance(player, p); if (dist > 2.0D) continue; if (PlayerHasHit(player) == 0) { if (getPlayerHP(p) < 1) { continue; } if (getCombatLog(player) != 1) continue; player.sendMessage("�7You try to strike a " + p.getName() + " HP: (" + getPlayerHP(p) + ") but miss! Your HP: " + getPlayerHP(player)+ "/" + getMaxBaseHealth(player) ); } else { int thisdmg = getPlayerDamage(player); this.totaldmg += thisdmg; if (getCombatLog(player) == 1) { player.sendMessage("You strike " + p.getName() + " for " + thisdmg + " damage. Your HP: " + getPlayerHP(player) + "/" + getMaxBaseHealth(player) + " Their HP: " + getPlayerHP(p)); } else if (getCombatLog(player) == 2) { if (this.countcompress4 == 4) { player.sendMessage("Total damage done " + this.totaldmg + ". Current Health: " + getPlayerHP(player) + "."); this.countcompress4 = 0; this.totaldmg = 0; } else { this.countcompress4 += 1; } } if (getPlayerHP(p) < thisdmg) { player.sendMessage("You have slain " + p.getName() + "!"); p.sendMessage("�cYou have been slain by " + player.getName() + "!"); DoPlayerDeath(p); } else { setPlayerHP(p, Integer.valueOf(getPlayerHP(p) - thisdmg)); this.totalplydmg += thisdmg; if (getCombatLog(p) == 1) { p.sendMessage("�cYou have been hit by " + player.getName() + " for " + thisdmg + " damage. Your HP: " + getPlayerHP(p) + "/" + getMaxBaseHealth(player) + " Their HP: " + getPlayerHP(player)); } else { if (getCombatLog(p) != 2) continue; if (this.countcompress5 == 4) { p.sendMessage("Total damage recieved " + this.totalplydmg + " from " + player.getName() + ". Current Health: " + getPlayerHP(p) + "."); this.countcompress5 = 0; this.totalplydmg = 0; } else { this.countcompress5 += 1; } } } } } } } \ No newline at end of file
false
false
null
null
diff --git a/tool/sakai-sdata-impl/src/main/java/org/sakaiproject/sdata/tool/functions/CHSPropertiesFunction.java b/tool/sakai-sdata-impl/src/main/java/org/sakaiproject/sdata/tool/functions/CHSPropertiesFunction.java index a88bc7d..4a7caba 100644 --- a/tool/sakai-sdata-impl/src/main/java/org/sakaiproject/sdata/tool/functions/CHSPropertiesFunction.java +++ b/tool/sakai-sdata-impl/src/main/java/org/sakaiproject/sdata/tool/functions/CHSPropertiesFunction.java @@ -1,199 +1,194 @@ /********************************************************************************** * $URL$ * $Id$ *********************************************************************************** * * Copyright (c) 2003, 2004, 2005, 2006, 2007 The Sakai Foundation. * * Licensed under the Educational Community License, Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl1.php * * 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.sakaiproject.sdata.tool.functions; import java.io.IOException; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.sakaiproject.content.api.ContentEntity; import org.sakaiproject.content.api.GroupAwareEdit; import org.sakaiproject.entity.api.ResourcePropertiesEdit; import org.sakaiproject.sdata.tool.model.CHSNodeMap; import org.sakaiproject.sdata.tool.api.Handler; import org.sakaiproject.sdata.tool.api.ResourceDefinition; import org.sakaiproject.sdata.tool.api.SDataException; /** * <p> * Set properties on the content entity. * </p> * <p> * Properties are specified in 4 request arrays associated in order. name, * value, action. These arrays must all be specified and the same length. * </p> * <p> * <b>item (optional)</b>: A list of item names, if this parameter is present * on a ContentCollection, the item specifies the target item as a child of the * ContentCollection. A blank string identifies the ContentCollection itself. * </p> * <p> * <b>name</b>: A list of request parameters of name <b>name</b> that specify * the name of each property in the value and action parameters. * </p> * <p> * <b>value</b>: A list of request parameters of name <b>value</b> that * specify the value of each property named in the name parameter. * </p> * <p> * <b>action</b>: A list of request parameters of name <b>acrtion</b> that * specifies what should be done with each name value pair. Action can be <b>a</a> * for add, <b>d</b> for remove or <b>r</b> for replace. * </p> * <ul> * <li> <b>add</b>: To add a property or to create a new property. </li> * <li> <b>remove</b>: To remove the property. </li> * <li> <b>replace</b>: To replace the property with the value specified, this * will be a single value property to start with, but if later (including in the * same request) it is converted into a list. </li> * </ul> * * @author ieb */ public class CHSPropertiesFunction extends CHSSDataFunction { public static final String ADD = "a"; public static final String REMOVE = "d"; public static final String REPLACE = "r"; public static final String NAME = "name"; public static final String VALUE = "value"; public static final String ACTION = "action"; private static final Log log = LogFactory.getLog(CHSPropertiesFunction.class); - private static final String ITEM = "item"; + private static final String ITEMS = "item"; /* * (non-Javadoc) * * @see org.sakaiproject.sdata.tool.api.SDataFunction#call(org.sakaiproject.sdata.tool.api.Handler, * javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse, java.lang.Object, * org.sakaiproject.sdata.tool.api.ResourceDefinition) */ public void call(Handler handler, HttpServletRequest request, HttpServletResponse response, Object target, ResourceDefinition rp) throws SDataException { SDataFunctionUtil.checkMethod(request.getMethod(), "POST"); GroupAwareEdit baseEdit = editEntity(handler, target, rp.getRepositoryPath()); ResourcePropertiesEdit baseProperties = baseEdit.getPropertiesEdit(); - String[] items = request.getParameterValues(ITEM); + String[] items = request.getParameterValues(ITEMS); String[] names = request.getParameterValues(NAME); String[] values = request.getParameterValues(VALUE); String[] actions = request.getParameterValues(ACTION); if (names == null || values == null || actions == null || names.length != values.length || names.length != actions.length) { throw new SDataException(HttpServletResponse.SC_BAD_REQUEST, "Request must contain the same number of name, value, and action parameters "); } GroupAwareEdit[] edit = new GroupAwareEdit[names.length]; ResourcePropertiesEdit[] properties = new ResourcePropertiesEdit[names.length]; for ( int i = 0; i < names.length; i++ ) { edit[i] = baseEdit; properties[i] = baseProperties; } if ( items != null ) { - String repositoryPath = rp.getRepositoryPath(); - if (!repositoryPath.endsWith("/")) - { - repositoryPath = repositoryPath + "/"; - } for ( int i = 0; i < items.length; i++ ) { if ( items[i].length() > 0 ) { - String p = repositoryPath+items[i]; - edit[i] = editEntity(handler, null, p); + edit[i] = editEntity(handler, target, rp.getRepositoryPath()+items[i]); properties[i] = edit[i].getPropertiesEdit(); } } } for (int i = 0; i < names.length; i++) { - if ( log.isDebugEnabled() ) { - log.debug("Property ref=["+edit[i].getId()+"] prop=["+names[i]+"] value=["+values[i]+"] action=["+actions[i]+"]"); - } + + + if (ADD.equals(actions[i])) { List<?> p = properties[i].getPropertyList(names[i]); + log.info("Got Property " + p); if (p == null || p.size() == 0) { properties[i].addProperty(names[i], values[i]); } else if (p.size() == 1) { String value = properties[i].getProperty(names[i]); properties[i].removeProperty(names[i]); properties[i].addPropertyToList(names[i], value); properties[i].addPropertyToList(names[i], values[i]); } else { properties[i].addPropertyToList(names[i], values[i]); } } else if (REMOVE.equals(actions[i])) { properties[i].removeProperty(names[i]); } else if (REPLACE.equals(actions[i])) { properties[i].removeProperty(names[i]); properties[i].addProperty(names[i], values[i]); } } for ( int i = 0; i < edit.length; i++) { commitEntity(edit[i]); } CHSNodeMap nm = new CHSNodeMap((ContentEntity) baseEdit, rp.getDepth(), rp); try { handler.sendMap(request, response, nm); } catch (IOException e) { throw new SDataException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "IO Error " + e.getMessage()); } } }
false
false
null
null
diff --git a/drools-core/src/main/java/org/drools/reteoo/PropagationQueuingNode.java b/drools-core/src/main/java/org/drools/reteoo/PropagationQueuingNode.java index 934b07d396..9bf9752ecd 100644 --- a/drools-core/src/main/java/org/drools/reteoo/PropagationQueuingNode.java +++ b/drools-core/src/main/java/org/drools/reteoo/PropagationQueuingNode.java @@ -1,571 +1,596 @@ /* * Copyright 2010 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.drools.reteoo; import static org.drools.core.util.BitMaskUtil.intersect; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.List; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicBoolean; import org.drools.RuleBaseConfiguration; import org.drools.RuntimeDroolsException; import org.drools.common.InternalFactHandle; import org.drools.common.InternalKnowledgeRuntime; import org.drools.common.InternalWorkingMemory; import org.drools.common.Memory; import org.drools.common.NodeMemory; import org.drools.common.WorkingMemoryAction; import org.drools.impl.StatefulKnowledgeSessionImpl; import org.drools.marshalling.impl.MarshallerReaderContext; import org.drools.marshalling.impl.MarshallerWriteContext; import org.drools.marshalling.impl.ProtobufMessages; import org.drools.reteoo.builder.BuildContext; import org.drools.rule.Pattern; import org.drools.rule.TypeDeclaration; import org.drools.spi.PropagationContext; /** * A node that will add the propagation to the working memory actions queue, * in order to allow multiple threads to concurrently assert objects to multiple * entry points. */ public class PropagationQueuingNode extends ObjectSource implements ObjectSinkNode, NodeMemory { private static final long serialVersionUID = 510l; // should we make this one configurable? private static final int PROPAGATION_SLICE_LIMIT = 1000; private ObjectSinkNode previousObjectSinkNode; private ObjectSinkNode nextObjectSinkNode; private PropagateAction action; public PropagationQueuingNode() { } /** * Construct a <code>PropagationQueuingNode</code> that will queue up * propagations until it the engine reaches a safe propagation point, * when all the queued facts are propagated. * * @param id Node's ID * @param objectSource Node's object source * @param context */ public PropagationQueuingNode(final int id, final ObjectSource objectSource, final BuildContext context) { super( id, context.getPartitionId(), context.getRuleBase().getConfiguration().isMultithreadEvaluation(), objectSource, context.getRuleBase().getConfiguration().getAlphaNodeHashingThreshold() ); this.action = new PropagateAction( this ); initDeclaredMask(context); } @Override public long calculateDeclaredMask(List<String> settableProperties) { return 0; } public void readExternal( ObjectInput in ) throws IOException, ClassNotFoundException { super.readExternal( in ); action = (PropagateAction) in.readObject(); } public void writeExternal( ObjectOutput out ) throws IOException { super.writeExternal( out ); out.writeObject( action ); } /** * @see org.drools.reteoo.ObjectSource#updateSink(org.drools.reteoo.ObjectSink, org.drools.spi.PropagationContext, org.drools.common.InternalWorkingMemory) */ public void updateSink( ObjectSink sink, PropagationContext context, InternalWorkingMemory workingMemory ) { final PropagationQueueingNodeMemory memory = (PropagationQueueingNodeMemory) workingMemory.getNodeMemory( this ); // this is just sanity code. We may remove it in the future, but keeping it for now. if ( !memory.isEmpty() ) { throw new RuntimeDroolsException( "Error updating sink. Not safe to update sink as the PropagatingQueueingNode memory is not empty at node: " + this.toString() ); } // as this node is simply a queue, ask object source to update the child sink directly this.source.updateSink( sink, context, workingMemory ); } public void attach( BuildContext context ) { this.source.addObjectSink( this ); // this node does not require update, so nothing else to do. } /** * @see org.drools.reteoo.ObjectSinkNode#getNextObjectSinkNode() */ public ObjectSinkNode getNextObjectSinkNode() { return this.nextObjectSinkNode; } /** * @see org.drools.reteoo.ObjectSinkNode#getPreviousObjectSinkNode() */ public ObjectSinkNode getPreviousObjectSinkNode() { return this.previousObjectSinkNode; } /** * @see org.drools.reteoo.ObjectSinkNode#setNextObjectSinkNode(org.drools.reteoo.ObjectSinkNode) */ public void setNextObjectSinkNode( ObjectSinkNode next ) { this.nextObjectSinkNode = next; } /** * @see org.drools.reteoo.ObjectSinkNode#setPreviousObjectSinkNode(org.drools.reteoo.ObjectSinkNode) */ public void setPreviousObjectSinkNode( ObjectSinkNode previous ) { this.previousObjectSinkNode = previous; } public boolean isObjectMemoryEnabled() { return true; } /** * @see org.drools.reteoo.ObjectSink#assertObject(InternalFactHandle, org.drools.spi.PropagationContext, org.drools.common.InternalWorkingMemory) */ public void assertObject( InternalFactHandle factHandle, PropagationContext context, InternalWorkingMemory workingMemory ) { final PropagationQueueingNodeMemory memory = (PropagationQueueingNodeMemory) workingMemory.getNodeMemory( this ); memory.addAction( new AssertAction( factHandle, context ) ); // if not queued yet, we need to queue it up if ( memory.isQueued().compareAndSet( false, true ) ) { workingMemory.queueWorkingMemoryAction( this.action ); } } public void retractObject( InternalFactHandle handle, PropagationContext context, InternalWorkingMemory workingMemory ) { final PropagationQueueingNodeMemory memory = (PropagationQueueingNodeMemory) workingMemory.getNodeMemory( this ); memory.addAction( new RetractAction( handle, context ) ); // if not queued yet, we need to queue it up if ( memory.isQueued().compareAndSet( false, true ) ) { workingMemory.queueWorkingMemoryAction( this.action ); } } public void modifyObject(InternalFactHandle factHandle, ModifyPreviousTuples modifyPreviousTuples, PropagationContext context, InternalWorkingMemory workingMemory) { final PropagationQueueingNodeMemory memory = (PropagationQueueingNodeMemory) workingMemory.getNodeMemory( this ); // for ( ObjectSink s : this.sink.getSinks() ) { // RightTuple rightTuple = modifyPreviousTuples.removeRightTuple( (RightTupleSink) s ); // if ( rightTuple != null ) { // rightTuple.reAdd(); // // RightTuple previously existed, so continue as modify // memory.addAction( new ModifyToSinkAction( rightTuple, // context, // (RightTupleSink) s ) ); // } else { // // RightTuple does not exist, so create and continue as assert // memory.addAction( new AssertToSinkAction( factHandle, // context, // s ) ); // } // } for ( ObjectSink s : this.sink.getSinks() ) { BetaNode betaNode = (BetaNode) s; RightTuple rightTuple = modifyPreviousTuples.peekRightTuple(); while ( rightTuple != null && ((BetaNode) rightTuple.getRightTupleSink()).getRightInputOtnId() < betaNode.getRightInputOtnId() ) { modifyPreviousTuples.removeRightTuple(); // we skipped this node, due to alpha hashing, so retract now rightTuple.getRightTupleSink().retractRightTuple( rightTuple, context, workingMemory ); rightTuple = modifyPreviousTuples.peekRightTuple(); } if ( rightTuple != null && ((BetaNode) rightTuple.getRightTupleSink()).getRightInputOtnId() == betaNode.getRightInputOtnId() ) { modifyPreviousTuples.removeRightTuple(); rightTuple.reAdd(); if ( intersect( context.getModificationMask(), betaNode.getRightInferredMask() ) ) { // RightTuple previously existed, so continue as modify memory.addAction( new ModifyToSinkAction( rightTuple, context, betaNode ) ); } } else { if ( intersect( context.getModificationMask(), betaNode.getRightInferredMask() ) ) { // RightTuple does not exist for this node, so create and continue as assert memory.addAction( new AssertToSinkAction( factHandle, context, betaNode ) ); } } } // if not queued yet, we need to queue it up if ( memory.isQueued().compareAndSet( false, true ) ) { workingMemory.queueWorkingMemoryAction( this.action ); } } public void byPassModifyToBetaNode (final InternalFactHandle factHandle, final ModifyPreviousTuples modifyPreviousTuples, final PropagationContext context, final InternalWorkingMemory workingMemory) { modifyObject( factHandle, modifyPreviousTuples, context, workingMemory ); } /** * Propagate all queued actions (asserts and retracts). * <p/> * This method implementation is based on optimistic behavior to avoid the * use of locks. There may eventually be a minimum wasted effort, but overall * it will be better than paying for the lock's cost. * * @param workingMemory */ public void propagateActions( InternalWorkingMemory workingMemory ) { final PropagationQueueingNodeMemory memory = (PropagationQueueingNodeMemory) workingMemory.getNodeMemory( this ); // first we clear up the action queued flag memory.isQueued().compareAndSet( true, false ); // we limit the propagation to avoid a hang when this queue is never empty Action next = memory.getNext(); for ( int counter = 0; next != null && counter < PROPAGATION_SLICE_LIMIT; next = memory.getNext(), counter++ ) { next.execute( this.sink, workingMemory ); } if ( memory.hasNext() && memory.isQueued().compareAndSet( false, true ) ) { // add action to the queue again. workingMemory.queueWorkingMemoryAction( this.action ); } } public void setObjectMemoryEnabled( boolean objectMemoryOn ) { throw new UnsupportedOperationException( "PropagationQueueingNode must have its node memory enabled." ); } public Memory createMemory( RuleBaseConfiguration config ) { return new PropagationQueueingNodeMemory(); } + + public int hashCode() { + return this.source.hashCode(); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + public boolean equals(final Object object) { + if ( this == object ) { + return true; + } + + if ( object == null || !(object instanceof PropagationQueuingNode) ) { + return false; + } + + final PropagationQueuingNode other = (PropagationQueuingNode) object; + + return this.source.equals( other.source ); + } + + /** * Memory implementation for the node */ public static class PropagationQueueingNodeMemory implements Externalizable, Memory { private static final long serialVersionUID = 7372028632974484023L; private ConcurrentLinkedQueue<Action> queue; // "singleton" action - there is one of this for each node in each working memory private AtomicBoolean isQueued; public PropagationQueueingNodeMemory() { super(); this.queue = new ConcurrentLinkedQueue<Action>(); this.isQueued = new AtomicBoolean( false ); } @SuppressWarnings("unchecked") public void readExternal( ObjectInput in ) throws IOException, ClassNotFoundException { queue = (ConcurrentLinkedQueue<Action>) in.readObject(); isQueued = (AtomicBoolean) in.readObject(); } public void writeExternal( ObjectOutput out ) throws IOException { out.writeObject( queue ); out.writeObject( isQueued ); } public boolean isEmpty() { return this.queue.isEmpty(); } public void addAction( Action action ) { this.queue.add( action ); } public Action getNext() { return this.queue.poll(); } public boolean hasNext() { return this.queue.peek() != null; } public AtomicBoolean isQueued() { return isQueued; } public long getSize() { return this.queue.size(); } public short getNodeType() { return NodeTypeEnums.PropagationQueueingNode; } } private static abstract class Action implements Externalizable { protected InternalFactHandle handle; protected PropagationContext context; public Action(InternalFactHandle handle, PropagationContext context) { super(); this.handle = handle; this.context = context; } public void readExternal( ObjectInput in ) throws IOException, ClassNotFoundException { handle = (InternalFactHandle) in.readObject(); context = (PropagationContext) in.readObject(); } public void writeExternal( ObjectOutput out ) throws IOException { out.writeObject( handle ); out.writeObject( context ); } public abstract void execute( final ObjectSinkPropagator sink, final InternalWorkingMemory workingMemory ); } private static class AssertAction extends Action { private static final long serialVersionUID = -8478488926430845209L; public AssertAction(final InternalFactHandle handle, final PropagationContext context) { super( handle, context ); } public void execute( final ObjectSinkPropagator sink, final InternalWorkingMemory workingMemory ) { sink.propagateAssertObject( this.handle, this.context, workingMemory ); context.evaluateActionQueue( workingMemory ); } } private static class AssertToSinkAction extends Action { private static final long serialVersionUID = -8478488926430845209L; private ObjectSink nodeSink; public AssertToSinkAction(final InternalFactHandle handle, final PropagationContext context, final ObjectSink sink) { super( handle, context ); nodeSink = sink; } public void execute( final ObjectSinkPropagator sink, final InternalWorkingMemory workingMemory ) { nodeSink.assertObject( this.handle, this.context, workingMemory ); context.evaluateActionQueue( workingMemory ); } @Override public void readExternal( ObjectInput in ) throws IOException, ClassNotFoundException { super.readExternal( in ); nodeSink = (ObjectSink) in.readObject(); } @Override public void writeExternal( ObjectOutput out ) throws IOException { super.writeExternal( out ); out.writeObject( nodeSink ); } } private static class RetractAction extends Action { private static final long serialVersionUID = -84784886430845209L; public RetractAction(final InternalFactHandle handle, final PropagationContext context) { super( handle, context ); } public void execute( final ObjectSinkPropagator sink, final InternalWorkingMemory workingMemory ) { for ( RightTuple rightTuple = this.handle.getFirstRightTuple(); rightTuple != null; rightTuple = rightTuple.getHandleNext() ) { rightTuple.getRightTupleSink().retractRightTuple( rightTuple, context, workingMemory ); } this.handle.clearRightTuples(); for ( LeftTuple leftTuple = this.handle.getLastLeftTuple(); leftTuple != null; leftTuple = leftTuple.getLeftParentNext() ) { leftTuple.getLeftTupleSink().retractLeftTuple( leftTuple, context, workingMemory ); } this.handle.clearLeftTuples(); context.evaluateActionQueue( workingMemory ); } } private static class ModifyToSinkAction extends Action { private static final long serialVersionUID = -8478488926430845209L; private RightTupleSink nodeSink; private RightTuple rightTuple; public ModifyToSinkAction(final RightTuple rightTuple, final PropagationContext context, final RightTupleSink nodeSink) { super( rightTuple.getFactHandle(), context ); this.nodeSink = nodeSink; this.rightTuple = rightTuple; } public void execute( final ObjectSinkPropagator sink, final InternalWorkingMemory workingMemory ) { nodeSink.modifyRightTuple( rightTuple, context, workingMemory ); context.evaluateActionQueue( workingMemory ); } @Override public void readExternal( ObjectInput in ) throws IOException, ClassNotFoundException { super.readExternal( in ); nodeSink = (RightTupleSink) in.readObject(); rightTuple = (RightTuple) in.readObject(); } @Override public void writeExternal( ObjectOutput out ) throws IOException { super.writeExternal( out ); out.writeObject( nodeSink ); out.writeObject( rightTuple ); } } /** * This is the action that is added to the working memory actions queue, so that * this node propagation can be triggered at a safe point */ public static class PropagateAction implements WorkingMemoryAction { private static final long serialVersionUID = 6765029029501617115L; private PropagationQueuingNode node; public PropagateAction() { } public PropagateAction(PropagationQueuingNode node) { this.node = node; } public PropagateAction(MarshallerReaderContext context) throws IOException { this.node = (PropagationQueuingNode) context.sinks.get( context.readInt() ); } public PropagateAction(MarshallerReaderContext context, ProtobufMessages.ActionQueue.Action _action) { this.node = (PropagationQueuingNode) context.sinks.get( _action.getPropagate().getNodeId() ); } public void write( MarshallerWriteContext context ) throws IOException { context.writeShort( WorkingMemoryAction.PropagateAction ); context.write( node.getId() ); } public ProtobufMessages.ActionQueue.Action serialize( MarshallerWriteContext context ) { return ProtobufMessages.ActionQueue.Action.newBuilder() .setType( ProtobufMessages.ActionQueue.ActionType.PROPAGATE ) .setPropagate( ProtobufMessages.ActionQueue.Propagate.newBuilder() .setNodeId( node.getId() ) .build() ) .build(); } public void readExternal( ObjectInput in ) throws IOException, ClassNotFoundException { node = (PropagationQueuingNode) in.readObject(); } public void writeExternal( ObjectOutput out ) throws IOException { out.writeObject( node ); } public void execute( InternalWorkingMemory workingMemory ) { this.node.propagateActions( workingMemory ); } public void execute( InternalKnowledgeRuntime kruntime ) { execute( ((StatefulKnowledgeSessionImpl) kruntime).getInternalWorkingMemory() ); } } }
true
false
null
null
diff --git a/src/com/warrows/plugins/TreeSpirit/PlayerMoveListener.java b/src/com/warrows/plugins/TreeSpirit/PlayerMoveListener.java index e760882..b72d242 100644 --- a/src/com/warrows/plugins/TreeSpirit/PlayerMoveListener.java +++ b/src/com/warrows/plugins/TreeSpirit/PlayerMoveListener.java @@ -1,25 +1,27 @@ package com.warrows.plugins.TreeSpirit; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerMoveEvent; public class PlayerMoveListener implements Listener { @EventHandler(ignoreCancelled = true) public void onPlayerMoveEvent(PlayerMoveEvent event) { Player player = event.getPlayer(); GreatTree tree = TreeSpiritPlugin.getGreatTree(player); + if (tree == null) + return; if (tree.isAtProximity(event.getTo().getBlock())) { } else { event.setCancelled(true); } } }
true
true
public void onPlayerMoveEvent(PlayerMoveEvent event) { Player player = event.getPlayer(); GreatTree tree = TreeSpiritPlugin.getGreatTree(player); if (tree.isAtProximity(event.getTo().getBlock())) { } else { event.setCancelled(true); } }
public void onPlayerMoveEvent(PlayerMoveEvent event) { Player player = event.getPlayer(); GreatTree tree = TreeSpiritPlugin.getGreatTree(player); if (tree == null) return; if (tree.isAtProximity(event.getTo().getBlock())) { } else { event.setCancelled(true); } }
diff --git a/src/testopia/API/Lookup.java b/src/testopia/API/Lookup.java index 283ad6b..29a2b1b 100644 --- a/src/testopia/API/Lookup.java +++ b/src/testopia/API/Lookup.java @@ -1,156 +1,156 @@ /* * 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 the Bugzilla Testopia Java API. * * The Initial Developer of the Original Code is Andrew Nelson. * Portions created by Andrew Nelson are Copyright (C) 2006 * Novell. All Rights Reserved. * * Contributor(s): Andrew Nelson <[email protected]> * */ package testopia.API; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.StringTokenizer; import java.util.Map.Entry; public class Lookup { public static URL url; public static void main(String args[]) throws Exception { //declare variables url = new URL("https://testopia-01.lab.bos.redhat.com/bugzilla/tr_xmlrpc.cgi"); //get username and password System.out.println("Welcome to Testopia Lookup tool 1.0"); StringBuilder command = new StringBuilder(); StringBuilder object = new StringBuilder(); System.out.println("Please Eneter your bugzilla username"); StringBuilder userNameStringBuilder = new StringBuilder(); processInput(userNameStringBuilder, null, null); System.out.println("Please enter your bugzilla password"); StringBuilder passwordStringBuilder = new StringBuilder(); processInput(passwordStringBuilder, null, null); System.out.println("You may now enter a command query"); System.out.println("To see a list of supported queries, please"); System.out.println("read the lookupHelp.txt"); //begin query loop String username = userNameStringBuilder.toString(); String password = passwordStringBuilder.toString(); StringBuilder secondObject; Session session = new Session(username, password, url); session.login(); while(true) { command = new StringBuilder(); object = new StringBuilder(); secondObject = new StringBuilder(); //get input from console processInput(command, object, null); System.out.println("Query Result:"); if(command.toString().equals("build")) { Build build = new Build(session); int buildId = build.getBuildIDByName(object.toString()); System.out.println(buildId); } else if(command.toString().equals("component")) { - TestPlan testPlan = new TestPlan(username, password, url, new Integer(object.toString())); + TestPlan testPlan = new TestPlan(session, new Integer(object.toString())); Object[] objects = testPlan.getComponents(); for(Object o : objects) System.out.println(o.toString()); } else if(command.toString().equals("environmentByProduct")) { Environment environment = new Environment(username, password, url); HashMap<String, Object> map = environment.listEnvironments(object.toString(), null); System.out.println("Environment Name: " + map.get("name")); System.out.println("Environment ID: " + map.get("environment_id")); } else if(command.toString().equals("environmentByName")) { Environment environment = new Environment(username, password, url); HashMap<String, Object> map = environment.listEnvironments(object.toString(), null); System.out.println("Environment Name: " + map.get("name")); System.out.println("Environment ID: " + map.get("environment_id")); } else if(command.toString().equals("exit")) { System.out.println("Thanks For Using the Lookup Tool"); break; } else { System.out.println("unrecognized command"); } System.out.println("You may now enter another command query, or type exit to exit"); } } /** * Helper method to take input from console * @param command - first parameter * @param object - second parameter */ public static void processInput(StringBuilder command, StringBuilder object, StringBuilder secondObject) { InputStream in = System.in; BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringTokenizer token = null; try { token = new StringTokenizer(reader.readLine(), ":"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(token.hasMoreTokens()) command.append(token.nextToken()); if(token.hasMoreTokens() && object != null) object.append(token.nextToken()); if(token.hasMoreTokens() && secondObject != null) secondObject.append(token.nextToken()); } }
true
true
public static void main(String args[]) throws Exception { //declare variables url = new URL("https://testopia-01.lab.bos.redhat.com/bugzilla/tr_xmlrpc.cgi"); //get username and password System.out.println("Welcome to Testopia Lookup tool 1.0"); StringBuilder command = new StringBuilder(); StringBuilder object = new StringBuilder(); System.out.println("Please Eneter your bugzilla username"); StringBuilder userNameStringBuilder = new StringBuilder(); processInput(userNameStringBuilder, null, null); System.out.println("Please enter your bugzilla password"); StringBuilder passwordStringBuilder = new StringBuilder(); processInput(passwordStringBuilder, null, null); System.out.println("You may now enter a command query"); System.out.println("To see a list of supported queries, please"); System.out.println("read the lookupHelp.txt"); //begin query loop String username = userNameStringBuilder.toString(); String password = passwordStringBuilder.toString(); StringBuilder secondObject; Session session = new Session(username, password, url); session.login(); while(true) { command = new StringBuilder(); object = new StringBuilder(); secondObject = new StringBuilder(); //get input from console processInput(command, object, null); System.out.println("Query Result:"); if(command.toString().equals("build")) { Build build = new Build(session); int buildId = build.getBuildIDByName(object.toString()); System.out.println(buildId); } else if(command.toString().equals("component")) { TestPlan testPlan = new TestPlan(username, password, url, new Integer(object.toString())); Object[] objects = testPlan.getComponents(); for(Object o : objects) System.out.println(o.toString()); } else if(command.toString().equals("environmentByProduct")) { Environment environment = new Environment(username, password, url); HashMap<String, Object> map = environment.listEnvironments(object.toString(), null); System.out.println("Environment Name: " + map.get("name")); System.out.println("Environment ID: " + map.get("environment_id")); } else if(command.toString().equals("environmentByName")) { Environment environment = new Environment(username, password, url); HashMap<String, Object> map = environment.listEnvironments(object.toString(), null); System.out.println("Environment Name: " + map.get("name")); System.out.println("Environment ID: " + map.get("environment_id")); } else if(command.toString().equals("exit")) { System.out.println("Thanks For Using the Lookup Tool"); break; } else { System.out.println("unrecognized command"); } System.out.println("You may now enter another command query, or type exit to exit"); } }
public static void main(String args[]) throws Exception { //declare variables url = new URL("https://testopia-01.lab.bos.redhat.com/bugzilla/tr_xmlrpc.cgi"); //get username and password System.out.println("Welcome to Testopia Lookup tool 1.0"); StringBuilder command = new StringBuilder(); StringBuilder object = new StringBuilder(); System.out.println("Please Eneter your bugzilla username"); StringBuilder userNameStringBuilder = new StringBuilder(); processInput(userNameStringBuilder, null, null); System.out.println("Please enter your bugzilla password"); StringBuilder passwordStringBuilder = new StringBuilder(); processInput(passwordStringBuilder, null, null); System.out.println("You may now enter a command query"); System.out.println("To see a list of supported queries, please"); System.out.println("read the lookupHelp.txt"); //begin query loop String username = userNameStringBuilder.toString(); String password = passwordStringBuilder.toString(); StringBuilder secondObject; Session session = new Session(username, password, url); session.login(); while(true) { command = new StringBuilder(); object = new StringBuilder(); secondObject = new StringBuilder(); //get input from console processInput(command, object, null); System.out.println("Query Result:"); if(command.toString().equals("build")) { Build build = new Build(session); int buildId = build.getBuildIDByName(object.toString()); System.out.println(buildId); } else if(command.toString().equals("component")) { TestPlan testPlan = new TestPlan(session, new Integer(object.toString())); Object[] objects = testPlan.getComponents(); for(Object o : objects) System.out.println(o.toString()); } else if(command.toString().equals("environmentByProduct")) { Environment environment = new Environment(username, password, url); HashMap<String, Object> map = environment.listEnvironments(object.toString(), null); System.out.println("Environment Name: " + map.get("name")); System.out.println("Environment ID: " + map.get("environment_id")); } else if(command.toString().equals("environmentByName")) { Environment environment = new Environment(username, password, url); HashMap<String, Object> map = environment.listEnvironments(object.toString(), null); System.out.println("Environment Name: " + map.get("name")); System.out.println("Environment ID: " + map.get("environment_id")); } else if(command.toString().equals("exit")) { System.out.println("Thanks For Using the Lookup Tool"); break; } else { System.out.println("unrecognized command"); } System.out.println("You may now enter another command query, or type exit to exit"); } }
diff --git a/src/main/java/org/apache/hadoop/mapred/MesosScheduler.java b/src/main/java/org/apache/hadoop/mapred/MesosScheduler.java index e5894e9..6b3583a 100644 --- a/src/main/java/org/apache/hadoop/mapred/MesosScheduler.java +++ b/src/main/java/org/apache/hadoop/mapred/MesosScheduler.java @@ -1,996 +1,996 @@ package org.apache.hadoop.mapred; import com.google.protobuf.ByteString; import org.apache.commons.httpclient.HttpHost; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.mapreduce.TaskType; import org.apache.hadoop.mapreduce.server.jobtracker.TaskTracker; import org.apache.hadoop.mapreduce.TaskType; import org.apache.mesos.MesosSchedulerDriver; import org.apache.mesos.Protos; import org.apache.mesos.Protos.*; import org.apache.mesos.Protos.TaskID; import org.apache.mesos.Scheduler; import org.apache.mesos.SchedulerDriver; import java.io.*; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import static org.apache.hadoop.util.StringUtils.join; public class MesosScheduler extends TaskScheduler implements Scheduler { public static final Log LOG = LogFactory.getLog(MesosScheduler.class); // This is the memory overhead for a jvm process. This needs to be added // to a jvm process's resource requirement, in addition to its heap size. private static final double JVM_MEM_OVERHEAD_PERCENT_DEFAULT = 0.1; // 10%. // NOTE: It appears that there's no real resource requirements for a // map / reduce slot. We therefore define a default slot as: // 1 cores. // 1024 MB memory. // 1 GB of disk space. private static final double SLOT_CPUS_DEFAULT = 1; // 1 cores. private static final int SLOT_DISK_DEFAULT = 1024; // 1 GB. private static final int SLOT_JVM_HEAP_DEFAULT = 1024; // 1024MB. private static final double TASKTRACKER_CPUS = 1.0; // 1 core. private static final int TASKTRACKER_MEM_DEFAULT = 1024; // 1 GB. // The default behavior in Hadoop is to use 4 slots per TaskTracker: private static final int MAP_SLOTS_DEFAULT = 2; private static final int REDUCE_SLOTS_DEFAULT = 2; // The amount of time to wait for task trackers to launch before // giving up. private static final long LAUNCH_TIMEOUT_MS = 300000; // 5 minutes private SchedulerDriver driver; private TaskScheduler taskScheduler; private JobTracker jobTracker; private Configuration conf; private File stateFile; // Count of the launched trackers for TaskID generation. private long launchedTrackers = 0; // Use a fixed slot allocation policy? private boolean policyIsFixed = false; private ResourcePolicy policy; // Maintains a mapping from {tracker host:port -> MesosTracker}. // Used for tracking the slots of each TaskTracker and the corresponding // Mesos TaskID. private Map<HttpHost, MesosTracker> mesosTrackers = new ConcurrentHashMap<HttpHost, MesosTracker>(); private JobInProgressListener jobListener = new JobInProgressListener() { @Override public void jobAdded(JobInProgress job) throws IOException { LOG.info("Added job " + job.getJobID()); } @Override public void jobRemoved(JobInProgress job) { LOG.info("Removed job " + job.getJobID()); } @Override public void jobUpdated(JobChangeEvent event) { synchronized (MesosScheduler.this) { JobInProgress job = event.getJobInProgress(); // If we have flaky tasktrackers, kill them. final List<String> flakyTrackers = job.getBlackListedTrackers(); // Remove the task from the map. This is O(n^2), but there's no better // way to do it, AFAIK. The flakyTrackers list should usually be // small, so this is probably not bad. for (String hostname : flakyTrackers) { for (MesosTracker mesosTracker : mesosTrackers.values()) { if (mesosTracker.host.getHostName().startsWith(hostname)) { LOG.info("Killing Mesos task: " + mesosTracker.taskId + " on host " + mesosTracker.host + " because it has been marked as flaky"); killTracker(mesosTracker); } } } // If the job is complete, kill all the corresponding idle TaskTrackers. if (!job.isComplete()) { return; } LOG.info("Completed job : " + job.getJobID()); // Remove the task from the map. final Set<HttpHost> trackers = new HashSet<HttpHost>(mesosTrackers.keySet()); for (HttpHost tracker : trackers) { MesosTracker mesosTracker = mesosTrackers.get(tracker); mesosTracker.jobs.remove(job.getJobID()); // If the TaskTracker doesn't have any running tasks, kill it. if (mesosTracker.jobs.isEmpty() && mesosTracker.active) { LOG.info("Killing Mesos task: " + mesosTracker.taskId + " on host " + mesosTracker.host + " because it is no longer needed"); killTracker(mesosTracker); } } } } }; public MesosScheduler() { } // TaskScheduler methods. @Override public synchronized void start() throws IOException { conf = getConf(); String taskTrackerClass = conf.get("mapred.mesos.taskScheduler", "org.apache.hadoop.mapred.JobQueueTaskScheduler"); try { taskScheduler = (TaskScheduler) Class.forName(taskTrackerClass).newInstance(); taskScheduler.setConf(conf); taskScheduler.setTaskTrackerManager(taskTrackerManager); } catch (ClassNotFoundException e) { LOG.fatal("Failed to initialize the TaskScheduler", e); System.exit(1); } catch (InstantiationException e) { LOG.fatal("Failed to initialize the TaskScheduler", e); System.exit(1); } catch (IllegalAccessException e) { LOG.fatal("Failed to initialize the TaskScheduler", e); System.exit(1); } // Add the job listener to get job related updates. taskTrackerManager.addJobInProgressListener(jobListener); LOG.info("Starting MesosScheduler"); jobTracker = (JobTracker) super.taskTrackerManager; String master = conf.get("mapred.mesos.master", "local"); try { FrameworkInfo frameworkInfo = FrameworkInfo .newBuilder() .setUser("") // Let Mesos fill in the user. .setCheckpoint(conf.getBoolean("mapred.mesos.checkpoint", false)) .setRole(conf.get("mapred.mesos.role", "*")) .setName("Hadoop: (RPC port: " + jobTracker.port + "," + " WebUI port: " + jobTracker.infoPort + ")").build(); driver = new MesosSchedulerDriver(this, frameworkInfo, master); driver.start(); } catch (Exception e) { // If the MesosScheduler can't be loaded, the JobTracker won't be useful // at all, so crash it now so that the user notices. LOG.fatal("Failed to start MesosScheduler", e); System.exit(1); } String file = conf.get("mapred.mesos.state.file", ""); if (!file.equals("")) { this.stateFile = new File(file); } policyIsFixed = conf.getBoolean("mapred.mesos.scheduler.policy.fixed", policyIsFixed); if (policyIsFixed) { policy = new ResourcePolicyFixed(this); } else { policy = new ResourcePolicyVariable(this); } taskScheduler.start(); } @Override public synchronized void terminate() throws IOException { try { LOG.info("Stopping MesosScheduler"); driver.stop(); } catch (Exception e) { LOG.error("Failed to stop Mesos scheduler", e); } taskScheduler.terminate(); } @Override public List<Task> assignTasks(TaskTracker taskTracker) throws IOException { HttpHost tracker = new HttpHost(taskTracker.getStatus().getHost(), taskTracker.getStatus().getHttpPort()); // Let the underlying task scheduler do the actual task scheduling. List<Task> tasks = taskScheduler.assignTasks(taskTracker); // The Hadoop Fair Scheduler is known to return null. if (tasks == null) { return null; } // Keep track of which TaskTracker contains which tasks. for (Task task : tasks) { if (mesosTrackers.containsKey(tracker)) { mesosTrackers.get(tracker).jobs.add(task.getJobID()); } else { LOG.info("Unknown/exited TaskTracker: " + tracker + ". "); } } return tasks; } @Override public synchronized Collection<JobInProgress> getJobs(String queueName) { return taskScheduler.getJobs(queueName); } @Override public synchronized void refresh() throws IOException { taskScheduler.refresh(); } // Mesos Scheduler methods. // These are synchronized, where possible. Some of these methods need to access the // JobTracker, which can lead to a deadlock: // See: https://issues.apache.org/jira/browse/MESOS-429 // The workaround employed here is to unsynchronize those methods needing access to // the JobTracker state and use explicit synchronization instead as appropriate. // TODO(bmahler): Provide a cleaner solution to this issue. One solution is to // split up the Scheduler and TaskScheduler implementations in order to break the // locking cycle. This would require a synchronized class to store the shared // state across our Scheduler and TaskScheduler implementations, and provide // atomic operations as needed. @Override public synchronized void registered(SchedulerDriver schedulerDriver, FrameworkID frameworkID, MasterInfo masterInfo) { LOG.info("Registered as " + frameworkID.getValue() + " with master " + masterInfo); } @Override public synchronized void reregistered(SchedulerDriver schedulerDriver, MasterInfo masterInfo) { LOG.info("Re-registered with master " + masterInfo); } public synchronized void killTracker(MesosTracker tracker) { driver.killTask(tracker.taskId); mesosTrackers.remove(tracker.host); } // For some reason, pendingMaps() and pendingReduces() doesn't return the // values we expect. We observed negative values, which may be related to // https://issues.apache.org/jira/browse/MAPREDUCE-1238. Below is the // algorithm that is used to calculate the pending tasks within the Hadoop // JobTracker sources (see 'printTaskSummary' in // src/org/apache/hadoop/mapred/jobdetails_jsp.java). private int getPendingTasks(TaskInProgress[] tasks) { int totalTasks = tasks.length; int runningTasks = 0; int finishedTasks = 0; int killedTasks = 0; for (int i = 0; i < totalTasks; ++i) { TaskInProgress task = tasks[i]; if (task == null) { continue; } if (task.isComplete()) { finishedTasks += 1; } else if (task.isRunning()) { runningTasks += 1; } else if (task.wasKilled()) { killedTasks += 1; } } int pendingTasks = totalTasks - runningTasks - killedTasks - finishedTasks; return pendingTasks; } // This method uses explicit synchronization in order to avoid deadlocks when // accessing the JobTracker. @Override public void resourceOffers(SchedulerDriver schedulerDriver, List<Offer> offers) { policy.resourceOffers(schedulerDriver, offers); } @Override public synchronized void offerRescinded(SchedulerDriver schedulerDriver, OfferID offerID) { LOG.warn("Rescinded offer: " + offerID.getValue()); } @Override public synchronized void statusUpdate(SchedulerDriver schedulerDriver, Protos.TaskStatus taskStatus) { LOG.info("Status update of " + taskStatus.getTaskId().getValue() + " to " + taskStatus.getState().name() + " with message " + taskStatus.getMessage()); // Remove the TaskTracker if the corresponding Mesos task has reached a // terminal state. switch (taskStatus.getState()) { case TASK_FINISHED: case TASK_FAILED: case TASK_KILLED: case TASK_LOST: // Make a copy to iterate over keys and delete values. Set<HttpHost> trackers = new HashSet<HttpHost>(mesosTrackers.keySet()); // Remove the task from the map. for (HttpHost tracker : trackers) { if (mesosTrackers.get(tracker).taskId.equals(taskStatus.getTaskId())) { LOG.info("Removing terminated TaskTracker: " + tracker); mesosTrackers.get(tracker).timer.cancel(); mesosTrackers.remove(tracker); } } break; case TASK_STAGING: case TASK_STARTING: case TASK_RUNNING: break; default: LOG.error("Unexpected TaskStatus: " + taskStatus.getState().name()); break; } } @Override public synchronized void frameworkMessage(SchedulerDriver schedulerDriver, ExecutorID executorID, SlaveID slaveID, byte[] bytes) { LOG.info("Framework Message of " + bytes.length + " bytes" + " from executor " + executorID.getValue() + " on slave " + slaveID.getValue()); } @Override public synchronized void disconnected(SchedulerDriver schedulerDriver) { LOG.warn("Disconnected from Mesos master."); } @Override public synchronized void slaveLost(SchedulerDriver schedulerDriver, SlaveID slaveID) { LOG.warn("Slave lost: " + slaveID.getValue()); } @Override public synchronized void executorLost(SchedulerDriver schedulerDriver, ExecutorID executorID, SlaveID slaveID, int status) { LOG.warn("Executor " + executorID.getValue() + " lost with status " + status + " on slave " + slaveID); } @Override public synchronized void error(SchedulerDriver schedulerDriver, String s) { LOG.error("Error from scheduler driver: " + s); } private class ResourcePolicy { public volatile MesosScheduler scheduler; public int neededMapSlots; public int neededReduceSlots; public long slots, mapSlots, reduceSlots; public int mapSlotsMax, reduceSlotsMax; double slotCpus; double slotDisk; int slotMem; long slotJVMHeap; int tasktrackerMem; long tasktrackerJVMHeap; // Minimum resource requirements for the container (TaskTracker + map/red // tasks). double containerCpus; double containerMem; double containerDisk; double cpus; double mem; double disk; public ResourcePolicy(MesosScheduler scheduler) { this.scheduler = scheduler; mapSlotsMax = conf.getInt("mapred.tasktracker.map.tasks.maximum", MAP_SLOTS_DEFAULT); reduceSlotsMax = conf.getInt("mapred.tasktracker.reduce.tasks.maximum", REDUCE_SLOTS_DEFAULT); slotCpus = conf.getFloat("mapred.mesos.slot.cpus", (float) SLOT_CPUS_DEFAULT); slotDisk = conf.getInt("mapred.mesos.slot.disk", SLOT_DISK_DEFAULT); slotMem = conf.getInt("mapred.mesos.slot.mem", SLOT_JVM_HEAP_DEFAULT); slotJVMHeap = Math.round((double) slotMem / (JVM_MEM_OVERHEAD_PERCENT_DEFAULT + 1)); tasktrackerMem = conf.getInt("mapred.mesos.tasktracker.mem", TASKTRACKER_MEM_DEFAULT); tasktrackerJVMHeap = Math.round((double) tasktrackerMem / (JVM_MEM_OVERHEAD_PERCENT_DEFAULT + 1)); containerCpus = TASKTRACKER_CPUS; containerMem = tasktrackerMem; containerDisk = 0; } public void computeNeededSlots(List<JobInProgress> jobsInProgress, Collection<TaskTrackerStatus> taskTrackers) { // Compute the number of pending maps and reduces. int pendingMaps = 0; int pendingReduces = 0; int runningMaps = 0; int runningReduces = 0; for (JobInProgress progress : jobsInProgress) { // JobStatus.pendingMaps/Reduces may return the wrong value on // occasion. This seems to be safer. pendingMaps += getPendingTasks(progress.getTasks(TaskType.MAP)); pendingReduces += getPendingTasks(progress.getTasks(TaskType.REDUCE)); runningMaps += progress.runningMaps(); runningReduces += progress.runningReduces(); } // Mark active (heartbeated) TaskTrackers and compute idle slots. int idleMapSlots = 0; int idleReduceSlots = 0; int unhealthyTrackers = 0; for (TaskTrackerStatus status : taskTrackers) { if (!status.getHealthStatus().isNodeHealthy()) { // Skip this node if it's unhealthy. ++unhealthyTrackers; continue; } HttpHost host = new HttpHost(status.getHost(), status.getHttpPort()); if (mesosTrackers.containsKey(host)) { mesosTrackers.get(host).active = true; mesosTrackers.get(host).timer.cancel(); idleMapSlots += status.getAvailableMapSlots(); idleReduceSlots += status.getAvailableReduceSlots(); } } // Consider the TaskTrackers that have yet to become active as being idle, // otherwise we will launch excessive TaskTrackers. int inactiveMapSlots = 0; int inactiveReduceSlots = 0; for (MesosTracker tracker : mesosTrackers.values()) { if (!tracker.active) { inactiveMapSlots += tracker.mapSlots; inactiveReduceSlots += tracker.reduceSlots; } } // To ensure Hadoop jobs begin promptly, we can specify a minimum number // of 'hot slots' to be available for use. This addresses the // TaskTracker spin up delay that exists with Hadoop on Mesos. This can // be a nuisance with lower latency applications, such as ad-hoc Hive // queries. int minimumMapSlots = conf.getInt("mapred.mesos.total.map.slots.minimum", 0); int minimumReduceSlots = conf.getInt("mapred.mesos.total.reduce.slots.minimum", 0); // Compute how many slots we need to allocate. neededMapSlots = Math.max( minimumMapSlots - (idleMapSlots + inactiveMapSlots), pendingMaps - (idleMapSlots + inactiveMapSlots)); neededReduceSlots = Math.max( minimumReduceSlots - (idleReduceSlots + inactiveReduceSlots), pendingReduces - (idleReduceSlots + inactiveReduceSlots)); LOG.info(join("\n", Arrays.asList( "JobTracker Status", " Pending Map Tasks: " + pendingMaps, " Pending Reduce Tasks: " + pendingReduces, " Running Map Tasks: " + runningMaps, " Running Reduce Tasks: " + runningReduces, " Idle Map Slots: " + idleMapSlots, " Idle Reduce Slots: " + idleReduceSlots, " Inactive Map Slots: " + inactiveMapSlots + " (launched but no hearbeat yet)", " Inactive Reduce Slots: " + inactiveReduceSlots + " (launched but no hearbeat yet)", " Needed Map Slots: " + neededMapSlots, " Needed Reduce Slots: " + neededReduceSlots, " Unhealthy Trackers: " + unhealthyTrackers))); if (stateFile != null) { // Update state file synchronized (this) { Set<String> hosts = new HashSet<String>(); for (MesosTracker tracker : mesosTrackers.values()) { hosts.add(tracker.host.getHostName()); } try { File tmp = new File(stateFile.getAbsoluteFile() + ".tmp"); FileWriter fstream = new FileWriter(tmp); fstream.write(join("\n", Arrays.asList( "time=" + System.currentTimeMillis(), "pendingMaps=" + pendingMaps, "pendingReduces=" + pendingReduces, "runningMaps=" + runningMaps, "runningReduces=" + runningReduces, "idleMapSlots=" + idleMapSlots, "idleReduceSlots=" + idleReduceSlots, "inactiveMapSlots=" + inactiveMapSlots, "inactiveReduceSlots=" + inactiveReduceSlots, "neededMapSlots=" + neededMapSlots, "neededReduceSlots=" + neededReduceSlots, "unhealthyTrackers=" + unhealthyTrackers, "hosts=" + join(",", hosts), ""))); fstream.close(); tmp.renameTo(stateFile); } catch (Exception e) { LOG.error("Can't write state file: " + e.getMessage()); } } } } // This method computes the number of slots to launch for this offer, and // returns true if the offer is sufficient. // Must be overridden. public boolean computeSlots() { return false; } public void resourceOffers(SchedulerDriver schedulerDriver, List<Offer> offers) { // Before synchronizing, we pull all needed information from the JobTracker. final HttpHost jobTrackerAddress = new HttpHost(jobTracker.getHostname(), jobTracker.getTrackerPort()); final Collection<TaskTrackerStatus> taskTrackers = jobTracker.taskTrackers(); final List<JobInProgress> jobsInProgress = new ArrayList<JobInProgress>(); for (JobStatus status : jobTracker.jobsToComplete()) { jobsInProgress.add(jobTracker.getJob(status.getJobID())); } computeNeededSlots(jobsInProgress, taskTrackers); synchronized (scheduler) { // Launch TaskTrackers to satisfy the slot requirements. for (Offer offer : offers) { if (neededMapSlots <= 0 && neededReduceSlots <= 0) { schedulerDriver.declineOffer(offer.getId()); continue; } // Ensure these values aren't < 0. neededMapSlots = Math.max(0, neededMapSlots); neededReduceSlots = Math.max(0, neededReduceSlots); cpus = -1.0; mem = -1.0; disk = -1.0; Set<Integer> ports = new HashSet<Integer>(); String cpuRole = new String("*"); String memRole = cpuRole; String diskRole = cpuRole; String portsRole = cpuRole; // Pull out the cpus, memory, disk, and 2 ports from the offer. for (Resource resource : offer.getResourcesList()) { if (resource.getName().equals("cpus") && resource.getType() == Value.Type.SCALAR) { cpus = resource.getScalar().getValue(); cpuRole = resource.getRole(); } else if (resource.getName().equals("mem") && resource.getType() == Value.Type.SCALAR) { mem = resource.getScalar().getValue(); memRole = resource.getRole(); } else if (resource.getName().equals("disk") && resource.getType() == Value.Type.SCALAR) { disk = resource.getScalar().getValue(); diskRole = resource.getRole(); } else if (resource.getName().equals("ports") && resource.getType() == Value.Type.RANGES) { portsRole = resource.getRole(); for (Value.Range range : resource.getRanges().getRangeList()) { Integer begin = (int)range.getBegin(); Integer end = (int)range.getEnd(); if (end < begin) { LOG.warn("Ignoring invalid port range: begin=" + begin + " end=" + end); continue; } while (begin <= end && ports.size() < 2) { ports.add(begin); begin += 1; } } } } final boolean sufficient = computeSlots(); double taskCpus = (mapSlots + reduceSlots) * slotCpus + containerCpus; double taskMem = (mapSlots + reduceSlots) * slotMem + containerMem; double taskDisk = (mapSlots + reduceSlots) * slotDisk + containerDisk; if (!sufficient || ports.size() < 2) { LOG.info(join("\n", Arrays.asList( "Declining offer with insufficient resources for a TaskTracker: ", " cpus: offered " + cpus + " needed at least " + taskCpus, " mem : offered " + mem + " needed at least " + taskMem, " disk: offered " + disk + " needed at least " + taskDisk, " ports: " + (ports.size() < 2 ? " less than 2 offered" : " at least 2 (sufficient)")))); schedulerDriver.declineOffer(offer.getId()); continue; } Iterator<Integer> portIter = ports.iterator(); HttpHost httpAddress = new HttpHost(offer.getHostname(), portIter.next()); HttpHost reportAddress = new HttpHost(offer.getHostname(), portIter.next()); // Check that this tracker is not already launched. This problem was // observed on a few occasions, but not reliably. The main symptom was // that entries in `mesosTrackers` were being lost, and task trackers // would be 'lost' mysteriously (probably because the ports were in // use). This problem has since gone away with a rewrite of the port // selection code, but the check + logging is left here. // TODO(brenden): Diagnose this to determine root cause. if (mesosTrackers.containsKey(httpAddress)) { LOG.info(join("\n", Arrays.asList( "Declining offer because host/port combination is in use: ", " cpus: offered " + cpus + " needed " + taskCpus, " mem : offered " + mem + " needed " + taskMem, " disk: offered " + disk + " needed " + taskDisk, " ports: " + ports))); schedulerDriver.declineOffer(offer.getId()); continue; } TaskID taskId = TaskID.newBuilder() .setValue("Task_Tracker_" + launchedTrackers++).build(); LOG.info("Launching task " + taskId.getValue() + " on " + httpAddress.toString() + " with mapSlots=" + mapSlots + " reduceSlots=" + reduceSlots); // Add this tracker to Mesos tasks. mesosTrackers.put(httpAddress, new MesosTracker(httpAddress, taskId, mapSlots, reduceSlots, scheduler)); // Set up the environment for running the TaskTracker. Protos.Environment.Builder envBuilder = Protos.Environment .newBuilder() .addVariables( Protos.Environment.Variable.newBuilder() .setName("HADOOP_HEAPSIZE") .setValue("" + tasktrackerJVMHeap)); // Set java specific environment, appropriately. Map<String, String> env = System.getenv(); if (env.containsKey("JAVA_HOME")) { envBuilder.addVariables(Protos.Environment.Variable.newBuilder() .setName("JAVA_HOME") .setValue(env.get("JAVA_HOME"))); } if (env.containsKey("JAVA_LIBRARY_PATH")) { envBuilder.addVariables(Protos.Environment.Variable.newBuilder() .setName("JAVA_LIBRARY_PATH") .setValue(env.get("JAVA_LIBRARY_PATH"))); } // Command info differs when performing a local run. CommandInfo commandInfo = null; String master = conf.get("mapred.mesos.master"); if (master == null) { throw new RuntimeException( "Expecting configuration property 'mapred.mesos.master'"); } else if (master == "local") { throw new RuntimeException( "Can not use 'local' for 'mapred.mesos.executor'"); } String uri = conf.get("mapred.mesos.executor.uri"); if (uri == null) { throw new RuntimeException( "Expecting configuration property 'mapred.mesos.executor'"); } String directory = conf.get("mapred.mesos.executor.directory"); if (directory == null || directory.equals("")) { LOG.info("URI: " + uri + ", name: " + new File(uri).getName()); directory = new File(uri).getName().split("\\.")[0] + "*"; } String command = conf.get("mapred.mesos.executor.command"); if (command == null || command.equals("")) { command = "echo $(env) ; " + " ./bin/hadoop org.apache.hadoop.mapred.MesosExecutor"; } commandInfo = CommandInfo.newBuilder() .setEnvironment(envBuilder) .setValue(String.format("cd %s && %s", directory, command)) .addUris(CommandInfo.URI.newBuilder().setValue(uri)).build(); // Create a configuration from the current configuration and // override properties as appropriate for the TaskTracker. Configuration overrides = new Configuration(conf); overrides.set("mapred.job.tracker", jobTrackerAddress.getHostName() + ':' + jobTrackerAddress.getPort()); overrides.set("mapred.task.tracker.http.address", httpAddress.getHostName() + ':' + httpAddress.getPort()); overrides.set("mapred.task.tracker.report.address", reportAddress.getHostName() + ':' + reportAddress.getPort()); overrides.set("mapred.child.java.opts", conf.get("mapred.child.java.opts") + " -XX:+UseParallelGC -Xmx" + slotJVMHeap + "m"); overrides.set("mapred.map.child.java.opts", conf.get("mapred.map.child.java.opts") + " -XX:+UseParallelGC -Xmx" + slotJVMHeap + "m"); overrides.set("mapred.reduce.child.java.opts", conf.get("mapred.reduce.child.java.opts") + " -XX:+UseParallelGC -Xmx" + slotJVMHeap + "m"); overrides.setLong("mapred.tasktracker.map.tasks.maximum", mapSlots); overrides.setLong("mapred.tasktracker.reduce.tasks.maximum", reduceSlots); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { overrides.write(new DataOutputStream(baos)); baos.flush(); } catch (IOException e) { LOG.warn("Failed to serialize configuration.", e); System.exit(1); } byte[] bytes = baos.toByteArray(); TaskInfo info = TaskInfo .newBuilder() .setName(taskId.getValue()) .setTaskId(taskId) .setSlaveId(offer.getSlaveId()) .addResources( Resource .newBuilder() .setName("cpus") .setType(Value.Type.SCALAR) .setRole(cpuRole) .setScalar(Value.Scalar.newBuilder().setValue(taskCpus - containerCpus))) .addResources( Resource .newBuilder() .setName("mem") .setType(Value.Type.SCALAR) .setRole(memRole) .setScalar(Value.Scalar.newBuilder().setValue(taskMem - containerMem))) .addResources( Resource .newBuilder() .setName("disk") .setType(Value.Type.SCALAR) .setRole(diskRole) .setScalar(Value.Scalar.newBuilder().setValue(taskDisk - containerDisk))) .addResources( Resource .newBuilder() .setName("ports") .setType(Value.Type.RANGES) .setRole(portsRole) .setRanges( Value.Ranges .newBuilder() .addRange(Value.Range.newBuilder() .setBegin(httpAddress.getPort()) .setEnd(httpAddress.getPort())) .addRange(Value.Range.newBuilder() .setBegin(reportAddress.getPort()) .setEnd(reportAddress.getPort())))) .setExecutor( ExecutorInfo .newBuilder() .setExecutorId(ExecutorID.newBuilder().setValue( "executor_" + taskId.getValue())) .setName("Hadoop TaskTracker") .setSource(taskId.getValue()) .addResources( Resource .newBuilder() .setName("cpus") .setType(Value.Type.SCALAR) .setRole(cpuRole) .setScalar(Value.Scalar.newBuilder().setValue( (containerCpus)))) .addResources( Resource .newBuilder() .setName("mem") .setType(Value.Type.SCALAR) .setRole(memRole) - .setScalar(Value.Scalar.newBuilder().setValue(containerMem)))) - .setCommand(commandInfo) + .setScalar(Value.Scalar.newBuilder().setValue(containerMem))) + .setCommand(commandInfo)) .setData(ByteString.copyFrom(bytes)) .build(); schedulerDriver.launchTasks(offer.getId(), Arrays.asList(info)); neededMapSlots -= mapSlots; neededReduceSlots -= reduceSlots; } if (neededMapSlots <= 0 && neededReduceSlots <= 0) { LOG.info("Satisfied map and reduce slots needed."); } else { LOG.info("Unable to fully satisfy needed map/reduce slots: " + (neededMapSlots > 0 ? neededMapSlots + " map slots " : "") + (neededReduceSlots > 0 ? neededReduceSlots + " reduce slots " : "") + "remaining"); } } } } private class ResourcePolicyFixed extends ResourcePolicy { public ResourcePolicyFixed(MesosScheduler scheduler) { super(scheduler); } // This method computes the number of slots to launch for this offer, and // returns true if the offer is sufficient. @Override public boolean computeSlots() { mapSlots = mapSlotsMax; reduceSlots = reduceSlotsMax; slots = Integer.MAX_VALUE; slots = (int) Math.min(slots, (cpus - containerCpus) / slotCpus); slots = (int) Math.min(slots, (mem - containerMem) / slotMem); slots = (int) Math.min(slots, (disk - containerDisk) / slotDisk); // Is this offer too small for even the minimum slots? if (slots < mapSlots + reduceSlots || slots < 1) { return false; } return true; } } private class ResourcePolicyVariable extends ResourcePolicy { public ResourcePolicyVariable(MesosScheduler scheduler) { super(scheduler); } // This method computes the number of slots to launch for this offer, and // returns true if the offer is sufficient. @Override public boolean computeSlots() { // What's the minimum number of map and reduce slots we should try to // launch? mapSlots = 0; reduceSlots = 0; // Determine how many slots we can allocate. int slots = mapSlotsMax + reduceSlotsMax; slots = (int) Math.min(slots, (cpus - containerCpus) / slotCpus); slots = (int) Math.min(slots, (mem - containerMem) / slotMem); slots = (int) Math.min(slots, (disk - containerDisk) / slotDisk); // Is this offer too small for even the minimum slots? if (slots < 1) { return false; } // Is the number of slots we need sufficiently small? If so, we can // allocate exactly the number we need. if (slots >= neededMapSlots + neededReduceSlots && neededMapSlots < mapSlotsMax && neededReduceSlots < reduceSlotsMax) { mapSlots = neededMapSlots; reduceSlots = neededReduceSlots; } else { // Allocate slots fairly for this resource offer. double mapFactor = (double) neededMapSlots / (neededMapSlots + neededReduceSlots); double reduceFactor = (double) neededReduceSlots / (neededMapSlots + neededReduceSlots); // To avoid map/reduce slot starvation, don't allow more than 50% // spread between map/reduce slots when we need both mappers and // reducers. if (neededMapSlots > 0 && neededReduceSlots > 0) { if (mapFactor < 0.25) { mapFactor = 0.25; } else if (mapFactor > 0.75) { mapFactor = 0.75; } if (reduceFactor < 0.25) { reduceFactor = 0.25; } else if (reduceFactor > 0.75) { reduceFactor = 0.75; } } mapSlots = Math.min(Math.min((long)Math.round(mapFactor * slots), mapSlotsMax), neededMapSlots); // The remaining slots are allocated for reduces. slots -= mapSlots; reduceSlots = Math.min(Math.min(slots, reduceSlotsMax), neededReduceSlots); } return true; } } /** * Used to track the our launched TaskTrackers. */ private class MesosTracker { public volatile HttpHost host; public TaskID taskId; public long mapSlots; public long reduceSlots; public volatile boolean active = false; // Set once tracked by the JobTracker. public Timer timer; public volatile MesosScheduler scheduler; // Tracks Hadoop jobs running on the tracker. public Set<JobID> jobs = new HashSet<JobID>(); public MesosTracker(HttpHost host, TaskID taskId, long mapSlots, long reduceSlots, MesosScheduler scheduler) { this.host = host; this.taskId = taskId; this.mapSlots = mapSlots; this.reduceSlots = reduceSlots; this.scheduler = scheduler; this.timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { synchronized (MesosTracker.this.scheduler) { // If the tracker activated while we were awaiting to acquire the // lock, return. if (MesosTracker.this.active) return; // When the scheduler is busy or doesn't receive offers, it may // fail to mark some TaskTrackers as active even though they are. // Here we do a final check with the JobTracker to make sure this // TaskTracker is really not there before we kill it. final Collection<TaskTrackerStatus> taskTrackers = MesosTracker.this.scheduler.jobTracker.taskTrackers(); for (TaskTrackerStatus status : taskTrackers) { HttpHost host = new HttpHost(status.getHost(), status.getHttpPort()); if (MesosTracker.this.host.equals(host)) { return; } } LOG.warn("Tracker " + MesosTracker.this.host + " failed to launch within " + LAUNCH_TIMEOUT_MS / 1000 + " seconds, killing it"); MesosTracker.this.scheduler.killTracker(MesosTracker.this); } } }, LAUNCH_TIMEOUT_MS); } } }
true
true
public void resourceOffers(SchedulerDriver schedulerDriver, List<Offer> offers) { // Before synchronizing, we pull all needed information from the JobTracker. final HttpHost jobTrackerAddress = new HttpHost(jobTracker.getHostname(), jobTracker.getTrackerPort()); final Collection<TaskTrackerStatus> taskTrackers = jobTracker.taskTrackers(); final List<JobInProgress> jobsInProgress = new ArrayList<JobInProgress>(); for (JobStatus status : jobTracker.jobsToComplete()) { jobsInProgress.add(jobTracker.getJob(status.getJobID())); } computeNeededSlots(jobsInProgress, taskTrackers); synchronized (scheduler) { // Launch TaskTrackers to satisfy the slot requirements. for (Offer offer : offers) { if (neededMapSlots <= 0 && neededReduceSlots <= 0) { schedulerDriver.declineOffer(offer.getId()); continue; } // Ensure these values aren't < 0. neededMapSlots = Math.max(0, neededMapSlots); neededReduceSlots = Math.max(0, neededReduceSlots); cpus = -1.0; mem = -1.0; disk = -1.0; Set<Integer> ports = new HashSet<Integer>(); String cpuRole = new String("*"); String memRole = cpuRole; String diskRole = cpuRole; String portsRole = cpuRole; // Pull out the cpus, memory, disk, and 2 ports from the offer. for (Resource resource : offer.getResourcesList()) { if (resource.getName().equals("cpus") && resource.getType() == Value.Type.SCALAR) { cpus = resource.getScalar().getValue(); cpuRole = resource.getRole(); } else if (resource.getName().equals("mem") && resource.getType() == Value.Type.SCALAR) { mem = resource.getScalar().getValue(); memRole = resource.getRole(); } else if (resource.getName().equals("disk") && resource.getType() == Value.Type.SCALAR) { disk = resource.getScalar().getValue(); diskRole = resource.getRole(); } else if (resource.getName().equals("ports") && resource.getType() == Value.Type.RANGES) { portsRole = resource.getRole(); for (Value.Range range : resource.getRanges().getRangeList()) { Integer begin = (int)range.getBegin(); Integer end = (int)range.getEnd(); if (end < begin) { LOG.warn("Ignoring invalid port range: begin=" + begin + " end=" + end); continue; } while (begin <= end && ports.size() < 2) { ports.add(begin); begin += 1; } } } } final boolean sufficient = computeSlots(); double taskCpus = (mapSlots + reduceSlots) * slotCpus + containerCpus; double taskMem = (mapSlots + reduceSlots) * slotMem + containerMem; double taskDisk = (mapSlots + reduceSlots) * slotDisk + containerDisk; if (!sufficient || ports.size() < 2) { LOG.info(join("\n", Arrays.asList( "Declining offer with insufficient resources for a TaskTracker: ", " cpus: offered " + cpus + " needed at least " + taskCpus, " mem : offered " + mem + " needed at least " + taskMem, " disk: offered " + disk + " needed at least " + taskDisk, " ports: " + (ports.size() < 2 ? " less than 2 offered" : " at least 2 (sufficient)")))); schedulerDriver.declineOffer(offer.getId()); continue; } Iterator<Integer> portIter = ports.iterator(); HttpHost httpAddress = new HttpHost(offer.getHostname(), portIter.next()); HttpHost reportAddress = new HttpHost(offer.getHostname(), portIter.next()); // Check that this tracker is not already launched. This problem was // observed on a few occasions, but not reliably. The main symptom was // that entries in `mesosTrackers` were being lost, and task trackers // would be 'lost' mysteriously (probably because the ports were in // use). This problem has since gone away with a rewrite of the port // selection code, but the check + logging is left here. // TODO(brenden): Diagnose this to determine root cause. if (mesosTrackers.containsKey(httpAddress)) { LOG.info(join("\n", Arrays.asList( "Declining offer because host/port combination is in use: ", " cpus: offered " + cpus + " needed " + taskCpus, " mem : offered " + mem + " needed " + taskMem, " disk: offered " + disk + " needed " + taskDisk, " ports: " + ports))); schedulerDriver.declineOffer(offer.getId()); continue; } TaskID taskId = TaskID.newBuilder() .setValue("Task_Tracker_" + launchedTrackers++).build(); LOG.info("Launching task " + taskId.getValue() + " on " + httpAddress.toString() + " with mapSlots=" + mapSlots + " reduceSlots=" + reduceSlots); // Add this tracker to Mesos tasks. mesosTrackers.put(httpAddress, new MesosTracker(httpAddress, taskId, mapSlots, reduceSlots, scheduler)); // Set up the environment for running the TaskTracker. Protos.Environment.Builder envBuilder = Protos.Environment .newBuilder() .addVariables( Protos.Environment.Variable.newBuilder() .setName("HADOOP_HEAPSIZE") .setValue("" + tasktrackerJVMHeap)); // Set java specific environment, appropriately. Map<String, String> env = System.getenv(); if (env.containsKey("JAVA_HOME")) { envBuilder.addVariables(Protos.Environment.Variable.newBuilder() .setName("JAVA_HOME") .setValue(env.get("JAVA_HOME"))); } if (env.containsKey("JAVA_LIBRARY_PATH")) { envBuilder.addVariables(Protos.Environment.Variable.newBuilder() .setName("JAVA_LIBRARY_PATH") .setValue(env.get("JAVA_LIBRARY_PATH"))); } // Command info differs when performing a local run. CommandInfo commandInfo = null; String master = conf.get("mapred.mesos.master"); if (master == null) { throw new RuntimeException( "Expecting configuration property 'mapred.mesos.master'"); } else if (master == "local") { throw new RuntimeException( "Can not use 'local' for 'mapred.mesos.executor'"); } String uri = conf.get("mapred.mesos.executor.uri"); if (uri == null) { throw new RuntimeException( "Expecting configuration property 'mapred.mesos.executor'"); } String directory = conf.get("mapred.mesos.executor.directory"); if (directory == null || directory.equals("")) { LOG.info("URI: " + uri + ", name: " + new File(uri).getName()); directory = new File(uri).getName().split("\\.")[0] + "*"; } String command = conf.get("mapred.mesos.executor.command"); if (command == null || command.equals("")) { command = "echo $(env) ; " + " ./bin/hadoop org.apache.hadoop.mapred.MesosExecutor"; } commandInfo = CommandInfo.newBuilder() .setEnvironment(envBuilder) .setValue(String.format("cd %s && %s", directory, command)) .addUris(CommandInfo.URI.newBuilder().setValue(uri)).build(); // Create a configuration from the current configuration and // override properties as appropriate for the TaskTracker. Configuration overrides = new Configuration(conf); overrides.set("mapred.job.tracker", jobTrackerAddress.getHostName() + ':' + jobTrackerAddress.getPort()); overrides.set("mapred.task.tracker.http.address", httpAddress.getHostName() + ':' + httpAddress.getPort()); overrides.set("mapred.task.tracker.report.address", reportAddress.getHostName() + ':' + reportAddress.getPort()); overrides.set("mapred.child.java.opts", conf.get("mapred.child.java.opts") + " -XX:+UseParallelGC -Xmx" + slotJVMHeap + "m"); overrides.set("mapred.map.child.java.opts", conf.get("mapred.map.child.java.opts") + " -XX:+UseParallelGC -Xmx" + slotJVMHeap + "m"); overrides.set("mapred.reduce.child.java.opts", conf.get("mapred.reduce.child.java.opts") + " -XX:+UseParallelGC -Xmx" + slotJVMHeap + "m"); overrides.setLong("mapred.tasktracker.map.tasks.maximum", mapSlots); overrides.setLong("mapred.tasktracker.reduce.tasks.maximum", reduceSlots); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { overrides.write(new DataOutputStream(baos)); baos.flush(); } catch (IOException e) { LOG.warn("Failed to serialize configuration.", e); System.exit(1); } byte[] bytes = baos.toByteArray(); TaskInfo info = TaskInfo .newBuilder() .setName(taskId.getValue()) .setTaskId(taskId) .setSlaveId(offer.getSlaveId()) .addResources( Resource .newBuilder() .setName("cpus") .setType(Value.Type.SCALAR) .setRole(cpuRole) .setScalar(Value.Scalar.newBuilder().setValue(taskCpus - containerCpus))) .addResources( Resource .newBuilder() .setName("mem") .setType(Value.Type.SCALAR) .setRole(memRole) .setScalar(Value.Scalar.newBuilder().setValue(taskMem - containerMem))) .addResources( Resource .newBuilder() .setName("disk") .setType(Value.Type.SCALAR) .setRole(diskRole) .setScalar(Value.Scalar.newBuilder().setValue(taskDisk - containerDisk))) .addResources( Resource .newBuilder() .setName("ports") .setType(Value.Type.RANGES) .setRole(portsRole) .setRanges( Value.Ranges .newBuilder() .addRange(Value.Range.newBuilder() .setBegin(httpAddress.getPort()) .setEnd(httpAddress.getPort())) .addRange(Value.Range.newBuilder() .setBegin(reportAddress.getPort()) .setEnd(reportAddress.getPort())))) .setExecutor( ExecutorInfo .newBuilder() .setExecutorId(ExecutorID.newBuilder().setValue( "executor_" + taskId.getValue())) .setName("Hadoop TaskTracker") .setSource(taskId.getValue()) .addResources( Resource .newBuilder() .setName("cpus") .setType(Value.Type.SCALAR) .setRole(cpuRole) .setScalar(Value.Scalar.newBuilder().setValue( (containerCpus)))) .addResources( Resource .newBuilder() .setName("mem") .setType(Value.Type.SCALAR) .setRole(memRole) .setScalar(Value.Scalar.newBuilder().setValue(containerMem)))) .setCommand(commandInfo) .setData(ByteString.copyFrom(bytes)) .build(); schedulerDriver.launchTasks(offer.getId(), Arrays.asList(info)); neededMapSlots -= mapSlots; neededReduceSlots -= reduceSlots; } if (neededMapSlots <= 0 && neededReduceSlots <= 0) { LOG.info("Satisfied map and reduce slots needed."); } else { LOG.info("Unable to fully satisfy needed map/reduce slots: " + (neededMapSlots > 0 ? neededMapSlots + " map slots " : "") + (neededReduceSlots > 0 ? neededReduceSlots + " reduce slots " : "") + "remaining"); } } }
public void resourceOffers(SchedulerDriver schedulerDriver, List<Offer> offers) { // Before synchronizing, we pull all needed information from the JobTracker. final HttpHost jobTrackerAddress = new HttpHost(jobTracker.getHostname(), jobTracker.getTrackerPort()); final Collection<TaskTrackerStatus> taskTrackers = jobTracker.taskTrackers(); final List<JobInProgress> jobsInProgress = new ArrayList<JobInProgress>(); for (JobStatus status : jobTracker.jobsToComplete()) { jobsInProgress.add(jobTracker.getJob(status.getJobID())); } computeNeededSlots(jobsInProgress, taskTrackers); synchronized (scheduler) { // Launch TaskTrackers to satisfy the slot requirements. for (Offer offer : offers) { if (neededMapSlots <= 0 && neededReduceSlots <= 0) { schedulerDriver.declineOffer(offer.getId()); continue; } // Ensure these values aren't < 0. neededMapSlots = Math.max(0, neededMapSlots); neededReduceSlots = Math.max(0, neededReduceSlots); cpus = -1.0; mem = -1.0; disk = -1.0; Set<Integer> ports = new HashSet<Integer>(); String cpuRole = new String("*"); String memRole = cpuRole; String diskRole = cpuRole; String portsRole = cpuRole; // Pull out the cpus, memory, disk, and 2 ports from the offer. for (Resource resource : offer.getResourcesList()) { if (resource.getName().equals("cpus") && resource.getType() == Value.Type.SCALAR) { cpus = resource.getScalar().getValue(); cpuRole = resource.getRole(); } else if (resource.getName().equals("mem") && resource.getType() == Value.Type.SCALAR) { mem = resource.getScalar().getValue(); memRole = resource.getRole(); } else if (resource.getName().equals("disk") && resource.getType() == Value.Type.SCALAR) { disk = resource.getScalar().getValue(); diskRole = resource.getRole(); } else if (resource.getName().equals("ports") && resource.getType() == Value.Type.RANGES) { portsRole = resource.getRole(); for (Value.Range range : resource.getRanges().getRangeList()) { Integer begin = (int)range.getBegin(); Integer end = (int)range.getEnd(); if (end < begin) { LOG.warn("Ignoring invalid port range: begin=" + begin + " end=" + end); continue; } while (begin <= end && ports.size() < 2) { ports.add(begin); begin += 1; } } } } final boolean sufficient = computeSlots(); double taskCpus = (mapSlots + reduceSlots) * slotCpus + containerCpus; double taskMem = (mapSlots + reduceSlots) * slotMem + containerMem; double taskDisk = (mapSlots + reduceSlots) * slotDisk + containerDisk; if (!sufficient || ports.size() < 2) { LOG.info(join("\n", Arrays.asList( "Declining offer with insufficient resources for a TaskTracker: ", " cpus: offered " + cpus + " needed at least " + taskCpus, " mem : offered " + mem + " needed at least " + taskMem, " disk: offered " + disk + " needed at least " + taskDisk, " ports: " + (ports.size() < 2 ? " less than 2 offered" : " at least 2 (sufficient)")))); schedulerDriver.declineOffer(offer.getId()); continue; } Iterator<Integer> portIter = ports.iterator(); HttpHost httpAddress = new HttpHost(offer.getHostname(), portIter.next()); HttpHost reportAddress = new HttpHost(offer.getHostname(), portIter.next()); // Check that this tracker is not already launched. This problem was // observed on a few occasions, but not reliably. The main symptom was // that entries in `mesosTrackers` were being lost, and task trackers // would be 'lost' mysteriously (probably because the ports were in // use). This problem has since gone away with a rewrite of the port // selection code, but the check + logging is left here. // TODO(brenden): Diagnose this to determine root cause. if (mesosTrackers.containsKey(httpAddress)) { LOG.info(join("\n", Arrays.asList( "Declining offer because host/port combination is in use: ", " cpus: offered " + cpus + " needed " + taskCpus, " mem : offered " + mem + " needed " + taskMem, " disk: offered " + disk + " needed " + taskDisk, " ports: " + ports))); schedulerDriver.declineOffer(offer.getId()); continue; } TaskID taskId = TaskID.newBuilder() .setValue("Task_Tracker_" + launchedTrackers++).build(); LOG.info("Launching task " + taskId.getValue() + " on " + httpAddress.toString() + " with mapSlots=" + mapSlots + " reduceSlots=" + reduceSlots); // Add this tracker to Mesos tasks. mesosTrackers.put(httpAddress, new MesosTracker(httpAddress, taskId, mapSlots, reduceSlots, scheduler)); // Set up the environment for running the TaskTracker. Protos.Environment.Builder envBuilder = Protos.Environment .newBuilder() .addVariables( Protos.Environment.Variable.newBuilder() .setName("HADOOP_HEAPSIZE") .setValue("" + tasktrackerJVMHeap)); // Set java specific environment, appropriately. Map<String, String> env = System.getenv(); if (env.containsKey("JAVA_HOME")) { envBuilder.addVariables(Protos.Environment.Variable.newBuilder() .setName("JAVA_HOME") .setValue(env.get("JAVA_HOME"))); } if (env.containsKey("JAVA_LIBRARY_PATH")) { envBuilder.addVariables(Protos.Environment.Variable.newBuilder() .setName("JAVA_LIBRARY_PATH") .setValue(env.get("JAVA_LIBRARY_PATH"))); } // Command info differs when performing a local run. CommandInfo commandInfo = null; String master = conf.get("mapred.mesos.master"); if (master == null) { throw new RuntimeException( "Expecting configuration property 'mapred.mesos.master'"); } else if (master == "local") { throw new RuntimeException( "Can not use 'local' for 'mapred.mesos.executor'"); } String uri = conf.get("mapred.mesos.executor.uri"); if (uri == null) { throw new RuntimeException( "Expecting configuration property 'mapred.mesos.executor'"); } String directory = conf.get("mapred.mesos.executor.directory"); if (directory == null || directory.equals("")) { LOG.info("URI: " + uri + ", name: " + new File(uri).getName()); directory = new File(uri).getName().split("\\.")[0] + "*"; } String command = conf.get("mapred.mesos.executor.command"); if (command == null || command.equals("")) { command = "echo $(env) ; " + " ./bin/hadoop org.apache.hadoop.mapred.MesosExecutor"; } commandInfo = CommandInfo.newBuilder() .setEnvironment(envBuilder) .setValue(String.format("cd %s && %s", directory, command)) .addUris(CommandInfo.URI.newBuilder().setValue(uri)).build(); // Create a configuration from the current configuration and // override properties as appropriate for the TaskTracker. Configuration overrides = new Configuration(conf); overrides.set("mapred.job.tracker", jobTrackerAddress.getHostName() + ':' + jobTrackerAddress.getPort()); overrides.set("mapred.task.tracker.http.address", httpAddress.getHostName() + ':' + httpAddress.getPort()); overrides.set("mapred.task.tracker.report.address", reportAddress.getHostName() + ':' + reportAddress.getPort()); overrides.set("mapred.child.java.opts", conf.get("mapred.child.java.opts") + " -XX:+UseParallelGC -Xmx" + slotJVMHeap + "m"); overrides.set("mapred.map.child.java.opts", conf.get("mapred.map.child.java.opts") + " -XX:+UseParallelGC -Xmx" + slotJVMHeap + "m"); overrides.set("mapred.reduce.child.java.opts", conf.get("mapred.reduce.child.java.opts") + " -XX:+UseParallelGC -Xmx" + slotJVMHeap + "m"); overrides.setLong("mapred.tasktracker.map.tasks.maximum", mapSlots); overrides.setLong("mapred.tasktracker.reduce.tasks.maximum", reduceSlots); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { overrides.write(new DataOutputStream(baos)); baos.flush(); } catch (IOException e) { LOG.warn("Failed to serialize configuration.", e); System.exit(1); } byte[] bytes = baos.toByteArray(); TaskInfo info = TaskInfo .newBuilder() .setName(taskId.getValue()) .setTaskId(taskId) .setSlaveId(offer.getSlaveId()) .addResources( Resource .newBuilder() .setName("cpus") .setType(Value.Type.SCALAR) .setRole(cpuRole) .setScalar(Value.Scalar.newBuilder().setValue(taskCpus - containerCpus))) .addResources( Resource .newBuilder() .setName("mem") .setType(Value.Type.SCALAR) .setRole(memRole) .setScalar(Value.Scalar.newBuilder().setValue(taskMem - containerMem))) .addResources( Resource .newBuilder() .setName("disk") .setType(Value.Type.SCALAR) .setRole(diskRole) .setScalar(Value.Scalar.newBuilder().setValue(taskDisk - containerDisk))) .addResources( Resource .newBuilder() .setName("ports") .setType(Value.Type.RANGES) .setRole(portsRole) .setRanges( Value.Ranges .newBuilder() .addRange(Value.Range.newBuilder() .setBegin(httpAddress.getPort()) .setEnd(httpAddress.getPort())) .addRange(Value.Range.newBuilder() .setBegin(reportAddress.getPort()) .setEnd(reportAddress.getPort())))) .setExecutor( ExecutorInfo .newBuilder() .setExecutorId(ExecutorID.newBuilder().setValue( "executor_" + taskId.getValue())) .setName("Hadoop TaskTracker") .setSource(taskId.getValue()) .addResources( Resource .newBuilder() .setName("cpus") .setType(Value.Type.SCALAR) .setRole(cpuRole) .setScalar(Value.Scalar.newBuilder().setValue( (containerCpus)))) .addResources( Resource .newBuilder() .setName("mem") .setType(Value.Type.SCALAR) .setRole(memRole) .setScalar(Value.Scalar.newBuilder().setValue(containerMem))) .setCommand(commandInfo)) .setData(ByteString.copyFrom(bytes)) .build(); schedulerDriver.launchTasks(offer.getId(), Arrays.asList(info)); neededMapSlots -= mapSlots; neededReduceSlots -= reduceSlots; } if (neededMapSlots <= 0 && neededReduceSlots <= 0) { LOG.info("Satisfied map and reduce slots needed."); } else { LOG.info("Unable to fully satisfy needed map/reduce slots: " + (neededMapSlots > 0 ? neededMapSlots + " map slots " : "") + (neededReduceSlots > 0 ? neededReduceSlots + " reduce slots " : "") + "remaining"); } } }
diff --git a/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/aspect/general/PageNotFoundTransformer.java b/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/aspect/general/PageNotFoundTransformer.java index bea8978f7..e11ab7f89 100644 --- a/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/aspect/general/PageNotFoundTransformer.java +++ b/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/aspect/general/PageNotFoundTransformer.java @@ -1,309 +1,316 @@ /* * PageNotFoundTransformer.java * * Version: $Revision: 1.2 $ * * Date: $Date: 2006/06/02 21:38:18 $ * * Copyright (c) 2002, Hewlett-Packard Company and Massachusetts * Institute of Technology. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of the Hewlett-Packard Company nor the name of the * Massachusetts Institute of Technology nor the names of their * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */ package org.dspace.app.xmlui.aspect.general; import java.io.IOException; import java.io.Serializable; import java.sql.SQLException; +import javax.servlet.http.HttpServletResponse; + import org.apache.cocoon.caching.CacheableProcessingComponent; import org.apache.cocoon.environment.ObjectModelHelper; import org.apache.cocoon.environment.Request; +import org.apache.cocoon.environment.http.HttpEnvironment; import org.apache.cocoon.util.HashUtil; import org.apache.excalibur.source.SourceValidity; import org.apache.excalibur.source.impl.validity.NOPValidity; import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer; import org.dspace.app.xmlui.utils.UIException; import org.dspace.app.xmlui.wing.Message; import org.dspace.app.xmlui.wing.WingConstants; import org.dspace.app.xmlui.wing.WingException; import org.dspace.app.xmlui.wing.element.Body; import org.dspace.app.xmlui.wing.element.Division; import org.dspace.app.xmlui.wing.element.PageMeta; import org.dspace.authorize.AuthorizeException; import org.xml.sax.Attributes; import org.xml.sax.SAXException; /** * This special comonent checks to see if the body element is empty (has no sub elements) and if * it is then displays some page not found text. * * @author Scott Phillips */ public class PageNotFoundTransformer extends AbstractDSpaceTransformer implements CacheableProcessingComponent { /** Language Strings */ private static final Message T_title = message("xmlui.PageNotFound.title"); private static final Message T_head = message("xmlui.PageNotFound.head"); private static final Message T_para1 = message("xmlui.PageNotFound.para1"); private static final Message T_go_home = message("xmlui.general.go_home"); private static final Message T_dspace_home = message("xmlui.general.dspace_home"); /** Where the body element is stored while we wait to see if it is empty */ private SAXEvent bodyEvent; /** Have we determined that the body is empty, and hence a we should generate a page not found. */ private boolean bodyEmpty; /** * Generate the unique caching key. * This key must be unique inside the space of this component. */ public Serializable getKey() { Request request = ObjectModelHelper.getRequest(objectModel); return HashUtil.hash(request.getSitemapURI()); } /** * Generate the cache validity object. * * The cache is always valid. */ public SourceValidity getValidity() { return NOPValidity.SHARED_INSTANCE; } /** * Receive notification of the beginning of a document. */ public void startDocument() throws SAXException { // Reset our parameters before starting a new document. this.bodyEvent = null; this.bodyEmpty = false; super.startDocument(); } /** * Process the SAX event. * @see org.xml.sax.ContentHandler#startElement */ public void startElement(String namespaceURI, String localName, String qName, Attributes attributes) throws SAXException { if (this.bodyEvent != null) { // If we have recorded the startElement for body and we are // recieving another start event, then there must be something // inside the body element, so we send the held body and carry // on as normal. sendEvent(this.bodyEvent); this.bodyEvent = null; } if (WingConstants.DRI.URI.equals(namespaceURI)) { if (Body.E_BODY.equals(localName)) { // Save the element and see if there is anything inside the body. this.bodyEvent = SAXEvent.startElement(namespaceURI,localName,qName,attributes); return; } } super.startElement(namespaceURI, localName, qName, attributes); } /** * Process the SAX event. * @see org.xml.sax.ContentHandler#endElement */ public void endElement(String namespaceURI, String localName, String qName) throws SAXException { if (WingConstants.DRI.URI.equals(namespaceURI)) { if (Body.E_BODY.equals(localName)) { if (this.bodyEvent != null) { // If we are recieving an endElement event for body while we // still have a startElement body event recorded then // the body element must have been empty. In this case, record // that the body is empty, and send both the start and end body events. this.bodyEmpty = true; // Sending the body will trigger the Wing framework to ask // us if we want to add a body to the page. sendEvent(this.bodyEvent); this.bodyEvent = null; } } } super.endElement(namespaceURI, localName, qName); } /** What to add at the end of the body */ public void addBody(Body body) throws SAXException, WingException, UIException, SQLException, IOException, AuthorizeException { if (this.bodyEmpty) { Division notFound = body.addDivision("page-not-found","primary"); notFound.setHead(T_head); notFound.addPara(T_para1); notFound.addPara().addXref(contextPath,T_go_home); + + HttpServletResponse response = (HttpServletResponse)objectModel + .get(HttpEnvironment.HTTP_RESPONSE_OBJECT); + response.setStatus(HttpServletResponse.SC_NOT_FOUND); } } /** What page metadata to add to the document */ public void addPageMeta(PageMeta pageMeta) throws SAXException, WingException, UIException, SQLException, IOException, AuthorizeException { if (this.bodyEmpty) { // Set the page title pageMeta.addMetadata("title").addContent(T_title); // Give theme a base trail pageMeta.addTrailLink(contextPath + "/",T_dspace_home); } } /** * Send the given recorded sax event. */ public void sendEvent(SAXEvent event) throws SAXException { if (event.type == SAXEvent.EventType.START) { super.startElement(event.namespaceURI,event.localName,event.qName,event.attributes); } else if (event.type == SAXEvent.EventType.END) { super.endElement(event.namespaceURI,event.localName,event.qName); } } /** * This private class remembers start and end element SAX events. */ private static class SAXEvent { public enum EventType { START, END }; protected EventType type = null; protected String namespaceURI = null; protected String localName = null; protected String qName = null; protected Attributes attributes = null; /** * Create a new StartElement recorded sax event. */ public static SAXEvent startElement(String namespaceURI, String localName, String qName, Attributes attributes) { SAXEvent event = new SAXEvent(); event.type = EventType.START; event.namespaceURI = namespaceURI; event.localName = localName; event.qName = qName; event.attributes = attributes; return event; } /** * Create a new EndElement recorded sax event. */ public static SAXEvent endElement(String namespaceURI, String localName, String qName) { SAXEvent event = new SAXEvent(); event.type = EventType.END; event.namespaceURI = namespaceURI; event.localName = localName; event.qName = qName; return event; } } }
false
false
null
null
diff --git a/src/com/android/phone/PhoneApp.java b/src/com/android/phone/PhoneApp.java index cb7e6c76..b79fd880 100644 --- a/src/com/android/phone/PhoneApp.java +++ b/src/com/android/phone/PhoneApp.java @@ -1,1745 +1,1744 @@ /* * Copyright (C) 2006 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.phone; import android.app.Activity; import android.app.Application; import android.app.KeyguardManager; import android.app.ProgressDialog; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothHeadset; import android.bluetooth.BluetoothProfile; import android.content.ActivityNotFoundException; import android.content.BroadcastReceiver; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.res.Configuration; import android.media.AudioManager; import android.net.Uri; import android.os.AsyncResult; import android.os.Binder; import android.os.Handler; import android.os.IBinder; import android.os.IPowerManager; import android.os.LocalPowerManager; import android.os.Message; import android.os.PowerManager; import android.os.RemoteException; import android.os.ServiceManager; import android.os.SystemClock; import android.os.SystemProperties; import android.preference.PreferenceManager; import android.provider.Settings.System; import android.telephony.ServiceState; import android.text.TextUtils; import android.util.Log; import android.view.KeyEvent; import com.android.internal.telephony.Call; import com.android.internal.telephony.CallManager; import com.android.internal.telephony.IccCard; import com.android.internal.telephony.MmiCode; import com.android.internal.telephony.Phone; import com.android.internal.telephony.PhoneFactory; import com.android.internal.telephony.TelephonyIntents; import com.android.internal.telephony.cdma.TtyIntent; import com.android.phone.OtaUtils.CdmaOtaScreenState; import com.android.server.sip.SipService; /** * Top-level Application class for the Phone app. */ public class PhoneApp extends Application implements AccelerometerListener.OrientationListener { /* package */ static final String LOG_TAG = "PhoneApp"; /** * Phone app-wide debug level: * 0 - no debug logging * 1 - normal debug logging if ro.debuggable is set (which is true in * "eng" and "userdebug" builds but not "user" builds) * 2 - ultra-verbose debug logging * * Most individual classes in the phone app have a local DBG constant, * typically set to * (PhoneApp.DBG_LEVEL >= 1) && (SystemProperties.getInt("ro.debuggable", 0) == 1) * or else * (PhoneApp.DBG_LEVEL >= 2) * depending on the desired verbosity. * * ***** DO NOT SUBMIT WITH DBG_LEVEL > 0 ************* */ /* package */ static final int DBG_LEVEL = 0; private static final boolean DBG = (PhoneApp.DBG_LEVEL >= 1) && (SystemProperties.getInt("ro.debuggable", 0) == 1); private static final boolean VDBG = (PhoneApp.DBG_LEVEL >= 2); // Message codes; see mHandler below. private static final int EVENT_SIM_NETWORK_LOCKED = 3; private static final int EVENT_WIRED_HEADSET_PLUG = 7; private static final int EVENT_SIM_STATE_CHANGED = 8; private static final int EVENT_UPDATE_INCALL_NOTIFICATION = 9; private static final int EVENT_DATA_ROAMING_DISCONNECTED = 10; private static final int EVENT_DATA_ROAMING_OK = 11; private static final int EVENT_UNSOL_CDMA_INFO_RECORD = 12; private static final int EVENT_DOCK_STATE_CHANGED = 13; private static final int EVENT_TTY_PREFERRED_MODE_CHANGED = 14; private static final int EVENT_TTY_MODE_GET = 15; private static final int EVENT_TTY_MODE_SET = 16; private static final int EVENT_START_SIP_SERVICE = 17; // The MMI codes are also used by the InCallScreen. public static final int MMI_INITIATE = 51; public static final int MMI_COMPLETE = 52; public static final int MMI_CANCEL = 53; // Don't use message codes larger than 99 here; those are reserved for // the individual Activities of the Phone UI. /** * Allowable values for the poke lock code (timeout between a user activity and the * going to sleep), please refer to {@link com.android.server.PowerManagerService} * for additional reference. * SHORT uses the short delay for the timeout (SHORT_KEYLIGHT_DELAY, 6 sec) * MEDIUM uses the medium delay for the timeout (MEDIUM_KEYLIGHT_DELAY, 15 sec) * DEFAULT is the system-wide default delay for the timeout (1 min) */ public enum ScreenTimeoutDuration { SHORT, MEDIUM, DEFAULT } /** * Allowable values for the wake lock code. * SLEEP means the device can be put to sleep. * PARTIAL means wake the processor, but we display can be kept off. * FULL means wake both the processor and the display. */ public enum WakeState { SLEEP, PARTIAL, FULL } private static PhoneApp sMe; // A few important fields we expose to the rest of the package // directly (rather than thru set/get methods) for efficiency. Phone phone; CallController callController; InCallUiState inCallUiState; CallNotifier notifier; NotificationMgr notificationMgr; Ringer ringer; BluetoothHandsfree mBtHandsfree; PhoneInterfaceManager phoneMgr; CallManager mCM; int mBluetoothHeadsetState = BluetoothProfile.STATE_DISCONNECTED; int mBluetoothHeadsetAudioState = BluetoothHeadset.STATE_AUDIO_DISCONNECTED; boolean mShowBluetoothIndication = false; static int mDockState = Intent.EXTRA_DOCK_STATE_UNDOCKED; static boolean sVoiceCapable = true; // Internal PhoneApp Call state tracker CdmaPhoneCallState cdmaPhoneCallState; // The InCallScreen instance (or null if the InCallScreen hasn't been // created yet.) private InCallScreen mInCallScreen; // The currently-active PUK entry activity and progress dialog. // Normally, these are the Emergency Dialer and the subsequent // progress dialog. null if there is are no such objects in // the foreground. private Activity mPUKEntryActivity; private ProgressDialog mPUKEntryProgressDialog; private boolean mIsSimPinEnabled; private String mCachedSimPin; // True if a wired headset is currently plugged in, based on the state // from the latest Intent.ACTION_HEADSET_PLUG broadcast we received in // mReceiver.onReceive(). private boolean mIsHeadsetPlugged; // True if the keyboard is currently *not* hidden // Gets updated whenever there is a Configuration change private boolean mIsHardKeyboardOpen; // True if we are beginning a call, but the phone state has not changed yet private boolean mBeginningCall; // Last phone state seen by updatePhoneState() Phone.State mLastPhoneState = Phone.State.IDLE; private WakeState mWakeState = WakeState.SLEEP; private ScreenTimeoutDuration mScreenTimeoutDuration = ScreenTimeoutDuration.DEFAULT; private boolean mIgnoreTouchUserActivity = false; private IBinder mPokeLockToken = new Binder(); private IPowerManager mPowerManagerService; private PowerManager.WakeLock mWakeLock; private PowerManager.WakeLock mPartialWakeLock; private PowerManager.WakeLock mProximityWakeLock; private KeyguardManager mKeyguardManager; private AccelerometerListener mAccelerometerListener; private int mOrientation = AccelerometerListener.ORIENTATION_UNKNOWN; // Broadcast receiver for various intent broadcasts (see onCreate()) private final BroadcastReceiver mReceiver = new PhoneAppBroadcastReceiver(); // Broadcast receiver purely for ACTION_MEDIA_BUTTON broadcasts private final BroadcastReceiver mMediaButtonReceiver = new MediaButtonBroadcastReceiver(); /** boolean indicating restoring mute state on InCallScreen.onResume() */ private boolean mShouldRestoreMuteOnInCallResume; /** * The singleton OtaUtils instance used for OTASP calls. * * The OtaUtils instance is created lazily the first time we need to * make an OTASP call, regardless of whether it's an interactive or * non-interactive OTASP call. */ public OtaUtils otaUtils; // Following are the CDMA OTA information Objects used during OTA Call. // cdmaOtaProvisionData object store static OTA information that needs // to be maintained even during Slider open/close scenarios. // cdmaOtaConfigData object stores configuration info to control visiblity // of each OTA Screens. // cdmaOtaScreenState object store OTA Screen State information. public OtaUtils.CdmaOtaProvisionData cdmaOtaProvisionData; public OtaUtils.CdmaOtaConfigData cdmaOtaConfigData; public OtaUtils.CdmaOtaScreenState cdmaOtaScreenState; public OtaUtils.CdmaOtaInCallScreenUiState cdmaOtaInCallScreenUiState; // TTY feature enabled on this platform private boolean mTtyEnabled; // Current TTY operating mode selected by user private int mPreferredTtyMode = Phone.TTY_MODE_OFF; /** * Set the restore mute state flag. Used when we are setting the mute state * OUTSIDE of user interaction {@link PhoneUtils#startNewCall(Phone)} */ /*package*/void setRestoreMuteOnInCallResume (boolean mode) { mShouldRestoreMuteOnInCallResume = mode; } /** * Get the restore mute state flag. * This is used by the InCallScreen {@link InCallScreen#onResume()} to figure * out if we need to restore the mute state for the current active call. */ /*package*/boolean getRestoreMuteOnInCallResume () { return mShouldRestoreMuteOnInCallResume; } Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { Phone.State phoneState; switch (msg.what) { // Starts the SIP service. It's a no-op if SIP API is not supported // on the deivce. // TODO: Having the phone process host the SIP service is only // temporary. Will move it to a persistent communication process // later. case EVENT_START_SIP_SERVICE: SipService.start(getApplicationContext()); break; // TODO: This event should be handled by the lock screen, just // like the "SIM missing" and "Sim locked" cases (bug 1804111). case EVENT_SIM_NETWORK_LOCKED: if (getResources().getBoolean(R.bool.ignore_sim_network_locked_events)) { // Some products don't have the concept of a "SIM network lock" Log.i(LOG_TAG, "Ignoring EVENT_SIM_NETWORK_LOCKED event; " + "not showing 'SIM network unlock' PIN entry screen"); } else { // Normal case: show the "SIM network unlock" PIN entry screen. // The user won't be able to do anything else until // they enter a valid SIM network PIN. Log.i(LOG_TAG, "show sim depersonal panel"); IccNetworkDepersonalizationPanel ndpPanel = new IccNetworkDepersonalizationPanel(PhoneApp.getInstance()); ndpPanel.show(); } break; case EVENT_UPDATE_INCALL_NOTIFICATION: // Tell the NotificationMgr to update the "ongoing // call" icon in the status bar, if necessary. // Currently, this is triggered by a bluetooth headset // state change (since the status bar icon needs to // turn blue when bluetooth is active.) if (DBG) Log.d (LOG_TAG, "- updating in-call notification from handler..."); notificationMgr.updateInCallNotification(); break; case EVENT_DATA_ROAMING_DISCONNECTED: notificationMgr.showDataDisconnectedRoaming(); break; case EVENT_DATA_ROAMING_OK: notificationMgr.hideDataDisconnectedRoaming(); break; case MMI_COMPLETE: onMMIComplete((AsyncResult) msg.obj); break; case MMI_CANCEL: PhoneUtils.cancelMmiCode(phone); break; case EVENT_WIRED_HEADSET_PLUG: // Since the presence of a wired headset or bluetooth affects the // speakerphone, update the "speaker" state. We ONLY want to do // this on the wired headset connect / disconnect events for now // though, so we're only triggering on EVENT_WIRED_HEADSET_PLUG. phoneState = mCM.getState(); // Do not change speaker state if phone is not off hook if (phoneState == Phone.State.OFFHOOK) { if (mBtHandsfree == null || !mBtHandsfree.isAudioOn()) { if (!isHeadsetPlugged()) { // if the state is "not connected", restore the speaker state. PhoneUtils.restoreSpeakerMode(getApplicationContext()); } else { // if the state is "connected", force the speaker off without // storing the state. PhoneUtils.turnOnSpeaker(getApplicationContext(), false, false); } } } // Update the Proximity sensor based on headset state updateProximitySensorMode(phoneState); // Force TTY state update according to new headset state if (mTtyEnabled) { sendMessage(obtainMessage(EVENT_TTY_PREFERRED_MODE_CHANGED, 0)); } break; case EVENT_SIM_STATE_CHANGED: // Marks the event where the SIM goes into ready state. // Right now, this is only used for the PUK-unlocking // process. if (msg.obj.equals(IccCard.INTENT_VALUE_ICC_READY)) { // when the right event is triggered and there // are UI objects in the foreground, we close // them to display the lock panel. if (mPUKEntryActivity != null) { mPUKEntryActivity.finish(); mPUKEntryActivity = null; } if (mPUKEntryProgressDialog != null) { mPUKEntryProgressDialog.dismiss(); mPUKEntryProgressDialog = null; } } break; case EVENT_UNSOL_CDMA_INFO_RECORD: //TODO: handle message here; break; case EVENT_DOCK_STATE_CHANGED: // If the phone is docked/undocked during a call, and no wired or BT headset // is connected: turn on/off the speaker accordingly. boolean inDockMode = false; - if (mDockState == Intent.EXTRA_DOCK_STATE_DESK || - mDockState == Intent.EXTRA_DOCK_STATE_CAR) { + if (mDockState != Intent.EXTRA_DOCK_STATE_UNDOCKED) { inDockMode = true; } if (VDBG) Log.d(LOG_TAG, "received EVENT_DOCK_STATE_CHANGED. Phone inDock = " + inDockMode); phoneState = mCM.getState(); if (phoneState == Phone.State.OFFHOOK && !isHeadsetPlugged() && !(mBtHandsfree != null && mBtHandsfree.isAudioOn())) { PhoneUtils.turnOnSpeaker(getApplicationContext(), inDockMode, true); updateInCallScreen(); // Has no effect if the InCallScreen isn't visible } break; case EVENT_TTY_PREFERRED_MODE_CHANGED: // TTY mode is only applied if a headset is connected int ttyMode; if (isHeadsetPlugged()) { ttyMode = mPreferredTtyMode; } else { ttyMode = Phone.TTY_MODE_OFF; } phone.setTTYMode(ttyMode, mHandler.obtainMessage(EVENT_TTY_MODE_SET)); break; case EVENT_TTY_MODE_GET: handleQueryTTYModeResponse(msg); break; case EVENT_TTY_MODE_SET: handleSetTTYModeResponse(msg); break; } } }; public PhoneApp() { sMe = this; } @Override public void onCreate() { if (VDBG) Log.v(LOG_TAG, "onCreate()..."); ContentResolver resolver = getContentResolver(); // Cache the "voice capable" flag. // This flag currently comes from a resource (which is // overrideable on a per-product basis): sVoiceCapable = getResources().getBoolean(com.android.internal.R.bool.config_voice_capable); // ...but this might eventually become a PackageManager "system // feature" instead, in which case we'd do something like: // sVoiceCapable = // getPackageManager().hasSystemFeature(PackageManager.FEATURE_TELEPHONY_VOICE_CALLS); if (phone == null) { // Initialize the telephony framework PhoneFactory.makeDefaultPhones(this); // Get the default phone phone = PhoneFactory.getDefaultPhone(); mCM = CallManager.getInstance(); mCM.registerPhone(phone); // Create the NotificationMgr singleton, which is used to display // status bar icons and control other status bar behavior. notificationMgr = NotificationMgr.init(this); phoneMgr = PhoneInterfaceManager.init(this, phone); mHandler.sendEmptyMessage(EVENT_START_SIP_SERVICE); int phoneType = phone.getPhoneType(); if (phoneType == Phone.PHONE_TYPE_CDMA) { // Create an instance of CdmaPhoneCallState and initialize it to IDLE cdmaPhoneCallState = new CdmaPhoneCallState(); cdmaPhoneCallState.CdmaPhoneCallStateInit(); } if (BluetoothAdapter.getDefaultAdapter() != null) { // Start BluetoothHandsree even if device is not voice capable. // The device can still support VOIP. mBtHandsfree = BluetoothHandsfree.init(this, mCM); startService(new Intent(this, BluetoothHeadsetService.class)); } else { // Device is not bluetooth capable mBtHandsfree = null; } ringer = Ringer.init(this); // before registering for phone state changes PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); mWakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, LOG_TAG); // lock used to keep the processor awake, when we don't care for the display. mPartialWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, LOG_TAG); // Wake lock used to control proximity sensor behavior. if ((pm.getSupportedWakeLockFlags() & PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) != 0x0) { mProximityWakeLock = pm.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, LOG_TAG); } if (DBG) Log.d(LOG_TAG, "onCreate: mProximityWakeLock: " + mProximityWakeLock); // create mAccelerometerListener only if we are using the proximity sensor if (proximitySensorModeEnabled()) { mAccelerometerListener = new AccelerometerListener(this, this); } mKeyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE); // get a handle to the service so that we can use it later when we // want to set the poke lock. mPowerManagerService = IPowerManager.Stub.asInterface( ServiceManager.getService("power")); // Create the CallController singleton, which is the interface // to the telephony layer for user-initiated telephony functionality // (like making outgoing calls.) callController = CallController.init(this); // ...and also the InCallUiState instance, used by the CallController to // keep track of some "persistent state" of the in-call UI. inCallUiState = InCallUiState.init(this); // Create the CallNotifer singleton, which handles // asynchronous events from the telephony layer (like // launching the incoming-call UI when an incoming call comes // in.) notifier = CallNotifier.init(this, phone, ringer, mBtHandsfree, new CallLogAsync()); // register for ICC status IccCard sim = phone.getIccCard(); if (sim != null) { if (VDBG) Log.v(LOG_TAG, "register for ICC status"); sim.registerForNetworkLocked(mHandler, EVENT_SIM_NETWORK_LOCKED, null); } // register for MMI/USSD mCM.registerForMmiComplete(mHandler, MMI_COMPLETE, null); // register connection tracking to PhoneUtils PhoneUtils.initializeConnectionHandler(mCM); // Read platform settings for TTY feature mTtyEnabled = getResources().getBoolean(R.bool.tty_enabled); // Register for misc other intent broadcasts. IntentFilter intentFilter = new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED); intentFilter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED); intentFilter.addAction(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED); intentFilter.addAction(TelephonyIntents.ACTION_ANY_DATA_CONNECTION_STATE_CHANGED); intentFilter.addAction(Intent.ACTION_HEADSET_PLUG); intentFilter.addAction(Intent.ACTION_DOCK_EVENT); intentFilter.addAction(Intent.ACTION_BATTERY_LOW); intentFilter.addAction(TelephonyIntents.ACTION_SIM_STATE_CHANGED); intentFilter.addAction(TelephonyIntents.ACTION_RADIO_TECHNOLOGY_CHANGED); intentFilter.addAction(TelephonyIntents.ACTION_SERVICE_STATE_CHANGED); intentFilter.addAction(TelephonyIntents.ACTION_EMERGENCY_CALLBACK_MODE_CHANGED); if (mTtyEnabled) { intentFilter.addAction(TtyIntent.TTY_PREFERRED_MODE_CHANGE_ACTION); } intentFilter.addAction(AudioManager.RINGER_MODE_CHANGED_ACTION); registerReceiver(mReceiver, intentFilter); // Use a separate receiver for ACTION_MEDIA_BUTTON broadcasts, // since we need to manually adjust its priority (to make sure // we get these intents *before* the media player.) IntentFilter mediaButtonIntentFilter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON); // // Make sure we're higher priority than the media player's // MediaButtonIntentReceiver (which currently has the default // priority of zero; see apps/Music/AndroidManifest.xml.) mediaButtonIntentFilter.setPriority(1); // registerReceiver(mMediaButtonReceiver, mediaButtonIntentFilter); //set the default values for the preferences in the phone. PreferenceManager.setDefaultValues(this, R.xml.network_setting, false); PreferenceManager.setDefaultValues(this, R.xml.call_feature_setting, false); // Make sure the audio mode (along with some // audio-mode-related state of our own) is initialized // correctly, given the current state of the phone. PhoneUtils.setAudioMode(mCM); } if (TelephonyCapabilities.supportsOtasp(phone)) { cdmaOtaProvisionData = new OtaUtils.CdmaOtaProvisionData(); cdmaOtaConfigData = new OtaUtils.CdmaOtaConfigData(); cdmaOtaScreenState = new OtaUtils.CdmaOtaScreenState(); cdmaOtaInCallScreenUiState = new OtaUtils.CdmaOtaInCallScreenUiState(); } // XXX pre-load the SimProvider so that it's ready resolver.getType(Uri.parse("content://icc/adn")); // start with the default value to set the mute state. mShouldRestoreMuteOnInCallResume = false; // TODO: Register for Cdma Information Records // phone.registerCdmaInformationRecord(mHandler, EVENT_UNSOL_CDMA_INFO_RECORD, null); // Read TTY settings and store it into BP NV. // AP owns (i.e. stores) the TTY setting in AP settings database and pushes the setting // to BP at power up (BP does not need to make the TTY setting persistent storage). // This way, there is a single owner (i.e AP) for the TTY setting in the phone. if (mTtyEnabled) { mPreferredTtyMode = android.provider.Settings.Secure.getInt( phone.getContext().getContentResolver(), android.provider.Settings.Secure.PREFERRED_TTY_MODE, Phone.TTY_MODE_OFF); mHandler.sendMessage(mHandler.obtainMessage(EVENT_TTY_PREFERRED_MODE_CHANGED, 0)); } // Read HAC settings and configure audio hardware if (getResources().getBoolean(R.bool.hac_enabled)) { int hac = android.provider.Settings.System.getInt(phone.getContext().getContentResolver(), android.provider.Settings.System.HEARING_AID, 0); AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); audioManager.setParameter(CallFeaturesSetting.HAC_KEY, hac != 0 ? CallFeaturesSetting.HAC_VAL_ON : CallFeaturesSetting.HAC_VAL_OFF); } } @Override public void onConfigurationChanged(Configuration newConfig) { if (newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO) { mIsHardKeyboardOpen = true; } else { mIsHardKeyboardOpen = false; } // Update the Proximity sensor based on keyboard state updateProximitySensorMode(mCM.getState()); super.onConfigurationChanged(newConfig); } /** * Returns the singleton instance of the PhoneApp. */ static PhoneApp getInstance() { return sMe; } /** * Returns the Phone associated with this instance */ static Phone getPhone() { return getInstance().phone; } Ringer getRinger() { return ringer; } BluetoothHandsfree getBluetoothHandsfree() { return mBtHandsfree; } /** * Returns an Intent that can be used to go to the "Call log" * UI (aka CallLogActivity) in the Contacts app. * * Watch out: there's no guarantee that the system has any activity to * handle this intent. (In particular there may be no "Call log" at * all on on non-voice-capable devices.) */ /* package */ static Intent createCallLogIntent() { Intent intent = new Intent(Intent.ACTION_VIEW, null); intent.setType("vnd.android.cursor.dir/calls"); return intent; } /** * Return an Intent that can be used to bring up the in-call screen. * * This intent can only be used from within the Phone app, since the * InCallScreen is not exported from our AndroidManifest. */ /* package */ static Intent createInCallIntent() { Intent intent = new Intent(Intent.ACTION_MAIN, null); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS | Intent.FLAG_ACTIVITY_NO_USER_ACTION); intent.setClassName("com.android.phone", getCallScreenClassName()); return intent; } /** * Variation of createInCallIntent() that also specifies whether the * DTMF dialpad should be initially visible when the InCallScreen * comes up. */ /* package */ static Intent createInCallIntent(boolean showDialpad) { Intent intent = createInCallIntent(); intent.putExtra(InCallScreen.SHOW_DIALPAD_EXTRA, showDialpad); return intent; } // TODO(InCallScreen redesign): This should be made private once // we fix PhoneInterfaceManager.java to *not* manually launch // the InCallScreen from its call() method. static String getCallScreenClassName() { return InCallScreen.class.getName(); } /** * Starts the InCallScreen Activity. */ /* package */ void displayCallScreen() { if (VDBG) Log.d(LOG_TAG, "displayCallScreen()..."); // On non-voice-capable devices we shouldn't ever be trying to // bring up the InCallScreen in the first place. if (!sVoiceCapable) { Log.w(LOG_TAG, "displayCallScreen() not allowed: non-voice-capable device", new Throwable("stack dump")); // Include a stack trace since this warning // indicates a bug in our caller return; } try { startActivity(createInCallIntent()); } catch (ActivityNotFoundException e) { // It's possible that the in-call UI might not exist (like on // non-voice-capable devices), so don't crash if someone // accidentally tries to bring it up... Log.w(LOG_TAG, "displayCallScreen: transition to InCallScreen failed: " + e); } Profiler.callScreenRequested(); } boolean isSimPinEnabled() { return mIsSimPinEnabled; } boolean authenticateAgainstCachedSimPin(String pin) { return (mCachedSimPin != null && mCachedSimPin.equals(pin)); } void setCachedSimPin(String pin) { mCachedSimPin = pin; } void setInCallScreenInstance(InCallScreen inCallScreen) { mInCallScreen = inCallScreen; } /** * @return true if the in-call UI is running as the foreground * activity. (In other words, from the perspective of the * InCallScreen activity, return true between onResume() and * onPause().) * * Note this method will return false if the screen is currently off, * even if the InCallScreen *was* in the foreground just before the * screen turned off. (This is because the foreground activity is * always "paused" while the screen is off.) */ boolean isShowingCallScreen() { if (mInCallScreen == null) return false; return mInCallScreen.isForegroundActivity(); } /** * Dismisses the in-call UI. * * This also ensures that you won't be able to get back to the in-call * UI via the BACK button (since this call removes the InCallScreen * from the activity history.) * For OTA Call, it call InCallScreen api to handle OTA Call End scenario * to display OTA Call End screen. */ /* package */ void dismissCallScreen() { if (mInCallScreen != null) { if ((TelephonyCapabilities.supportsOtasp(phone)) && (mInCallScreen.isOtaCallInActiveState() || mInCallScreen.isOtaCallInEndState() || ((cdmaOtaScreenState != null) && (cdmaOtaScreenState.otaScreenState != CdmaOtaScreenState.OtaScreenState.OTA_STATUS_UNDEFINED)))) { // TODO: During OTA Call, display should not become dark to // allow user to see OTA UI update. Phone app needs to hold // a SCREEN_DIM_WAKE_LOCK wake lock during the entire OTA call. wakeUpScreen(); // If InCallScreen is not in foreground we resume it to show the OTA call end screen // Fire off the InCallScreen intent displayCallScreen(); mInCallScreen.handleOtaCallEnd(); return; } else { mInCallScreen.finish(); } } } /** * Handles OTASP-related events from the telephony layer. * * While an OTASP call is active, the CallNotifier forwards * OTASP-related telephony events to this method. */ void handleOtaspEvent(Message msg) { if (DBG) Log.d(LOG_TAG, "handleOtaspEvent(message " + msg + ")..."); if (otaUtils == null) { // We shouldn't be getting OTASP events without ever // having started the OTASP call in the first place! Log.w(LOG_TAG, "handleOtaEvents: got an event but otaUtils is null! " + "message = " + msg); return; } otaUtils.onOtaProvisionStatusChanged((AsyncResult) msg.obj); } /** * Similarly, handle the disconnect event of an OTASP call * by forwarding it to the OtaUtils instance. */ /* package */ void handleOtaspDisconnect() { if (DBG) Log.d(LOG_TAG, "handleOtaspDisconnect()..."); if (otaUtils == null) { // We shouldn't be getting OTASP events without ever // having started the OTASP call in the first place! Log.w(LOG_TAG, "handleOtaspDisconnect: otaUtils is null!"); return; } otaUtils.onOtaspDisconnect(); } /** * Sets the activity responsible for un-PUK-blocking the device * so that we may close it when we receive a positive result. * mPUKEntryActivity is also used to indicate to the device that * we are trying to un-PUK-lock the phone. In other words, iff * it is NOT null, then we are trying to unlock and waiting for * the SIM to move to READY state. * * @param activity is the activity to close when PUK has * finished unlocking. Can be set to null to indicate the unlock * or SIM READYing process is over. */ void setPukEntryActivity(Activity activity) { mPUKEntryActivity = activity; } Activity getPUKEntryActivity() { return mPUKEntryActivity; } /** * Sets the dialog responsible for notifying the user of un-PUK- * blocking - SIM READYing progress, so that we may dismiss it * when we receive a positive result. * * @param dialog indicates the progress dialog informing the user * of the state of the device. Dismissed upon completion of * READYing process */ void setPukEntryProgressDialog(ProgressDialog dialog) { mPUKEntryProgressDialog = dialog; } ProgressDialog getPUKEntryProgressDialog() { return mPUKEntryProgressDialog; } /** * Controls how quickly the screen times out. * * The poke lock controls how long it takes before the screen powers * down, and therefore has no immediate effect when the current * WakeState (see {@link PhoneApp#requestWakeState}) is FULL. * If we're in a state where the screen *is* allowed to turn off, * though, the poke lock will determine the timeout interval (long or * short). * * @param shortPokeLock tells the device the timeout duration to use * before going to sleep * {@link com.android.server.PowerManagerService#SHORT_KEYLIGHT_DELAY}. */ /* package */ void setScreenTimeout(ScreenTimeoutDuration duration) { if (VDBG) Log.d(LOG_TAG, "setScreenTimeout(" + duration + ")..."); // make sure we don't set the poke lock repeatedly so that we // avoid triggering the userActivity calls in // PowerManagerService.setPokeLock(). if (duration == mScreenTimeoutDuration) { return; } // stick with default timeout if we are using the proximity sensor if (proximitySensorModeEnabled()) { return; } mScreenTimeoutDuration = duration; updatePokeLock(); } /** * Update the state of the poke lock held by the phone app, * based on the current desired screen timeout and the * current "ignore user activity on touch" flag. */ private void updatePokeLock() { // This is kind of convoluted, but the basic thing to remember is // that the poke lock just sends a message to the screen to tell // it to stay on for a while. // The default is 0, for a long timeout and should be set that way // when we are heading back into a the keyguard / screen off // state, and also when we're trying to keep the screen alive // while ringing. We'll also want to ignore the cheek events // regardless of the timeout duration. // The short timeout is really used whenever we want to give up // the screen lock, such as when we're in call. int pokeLockSetting = 0; switch (mScreenTimeoutDuration) { case SHORT: // Set the poke lock to timeout the display after a short // timeout (5s). This ensures that the screen goes to sleep // as soon as acceptably possible after we the wake lock // has been released. pokeLockSetting |= LocalPowerManager.POKE_LOCK_SHORT_TIMEOUT; break; case MEDIUM: // Set the poke lock to timeout the display after a medium // timeout (15s). This ensures that the screen goes to sleep // as soon as acceptably possible after we the wake lock // has been released. pokeLockSetting |= LocalPowerManager.POKE_LOCK_MEDIUM_TIMEOUT; break; case DEFAULT: default: // set the poke lock to timeout the display after a long // delay by default. // TODO: it may be nice to be able to disable cheek presses // for long poke locks (emergency dialer, for instance). break; } if (mIgnoreTouchUserActivity) { pokeLockSetting |= LocalPowerManager.POKE_LOCK_IGNORE_TOUCH_EVENTS; } // Send the request try { mPowerManagerService.setPokeLock(pokeLockSetting, mPokeLockToken, LOG_TAG); } catch (RemoteException e) { Log.w(LOG_TAG, "mPowerManagerService.setPokeLock() failed: " + e); } } /** * Controls whether or not the screen is allowed to sleep. * * Once sleep is allowed (WakeState is SLEEP), it will rely on the * settings for the poke lock to determine when to timeout and let * the device sleep {@link PhoneApp#setScreenTimeout}. * * @param ws tells the device to how to wake. */ /* package */ void requestWakeState(WakeState ws) { if (VDBG) Log.d(LOG_TAG, "requestWakeState(" + ws + ")..."); synchronized (this) { if (mWakeState != ws) { switch (ws) { case PARTIAL: // acquire the processor wake lock, and release the FULL // lock if it is being held. mPartialWakeLock.acquire(); if (mWakeLock.isHeld()) { mWakeLock.release(); } break; case FULL: // acquire the full wake lock, and release the PARTIAL // lock if it is being held. mWakeLock.acquire(); if (mPartialWakeLock.isHeld()) { mPartialWakeLock.release(); } break; case SLEEP: default: // release both the PARTIAL and FULL locks. if (mWakeLock.isHeld()) { mWakeLock.release(); } if (mPartialWakeLock.isHeld()) { mPartialWakeLock.release(); } break; } mWakeState = ws; } } } /** * If we are not currently keeping the screen on, then poke the power * manager to wake up the screen for the user activity timeout duration. */ /* package */ void wakeUpScreen() { synchronized (this) { if (mWakeState == WakeState.SLEEP) { if (DBG) Log.d(LOG_TAG, "pulse screen lock"); try { mPowerManagerService.userActivityWithForce(SystemClock.uptimeMillis(), false, true); } catch (RemoteException ex) { // Ignore -- the system process is dead. } } } } /** * Sets the wake state and screen timeout based on the current state * of the phone, and the current state of the in-call UI. * * This method is a "UI Policy" wrapper around * {@link PhoneApp#requestWakeState} and {@link PhoneApp#setScreenTimeout}. * * It's safe to call this method regardless of the state of the Phone * (e.g. whether or not it's idle), and regardless of the state of the * Phone UI (e.g. whether or not the InCallScreen is active.) */ /* package */ void updateWakeState() { Phone.State state = mCM.getState(); // True if the in-call UI is the foreground activity. // (Note this will be false if the screen is currently off, // since in that case *no* activity is in the foreground.) boolean isShowingCallScreen = isShowingCallScreen(); // True if the InCallScreen's DTMF dialer is currently opened. // (Note this does NOT imply whether or not the InCallScreen // itself is visible.) boolean isDialerOpened = (mInCallScreen != null) && mInCallScreen.isDialerOpened(); // True if the speakerphone is in use. (If so, we *always* use // the default timeout. Since the user is obviously not holding // the phone up to his/her face, we don't need to worry about // false touches, and thus don't need to turn the screen off so // aggressively.) // Note that we need to make a fresh call to this method any // time the speaker state changes. (That happens in // PhoneUtils.turnOnSpeaker().) boolean isSpeakerInUse = (state == Phone.State.OFFHOOK) && PhoneUtils.isSpeakerOn(this); // TODO (bug 1440854): The screen timeout *might* also need to // depend on the bluetooth state, but this isn't as clear-cut as // the speaker state (since while using BT it's common for the // user to put the phone straight into a pocket, in which case the // timeout should probably still be short.) if (DBG) Log.d(LOG_TAG, "updateWakeState: callscreen " + isShowingCallScreen + ", dialer " + isDialerOpened + ", speaker " + isSpeakerInUse + "..."); // // (1) Set the screen timeout. // // Note that the "screen timeout" value we determine here is // meaningless if the screen is forced on (see (2) below.) // // Historical note: In froyo and earlier, we checked here for a special // case: the in-call UI being active, the speaker off, and the DTMF dialpad // not visible. In that case, with no touchable UI onscreen at all (for // non-prox-sensor devices at least), we could assume the user was probably // holding the phone up to their face and *not* actually looking at the // screen. So we'd switch to a special screen timeout value // (ScreenTimeoutDuration.MEDIUM), purely to save battery life. // // On current devices, we can rely on the proximity sensor to turn the // screen off in this case, so we use the system-wide default timeout // unconditionally. setScreenTimeout(ScreenTimeoutDuration.DEFAULT); // // (2) Decide whether to force the screen on or not. // // Force the screen to be on if the phone is ringing or dialing, // or if we're displaying the "Call ended" UI for a connection in // the "disconnected" state. // boolean isRinging = (state == Phone.State.RINGING); boolean isDialing = (phone.getForegroundCall().getState() == Call.State.DIALING); boolean showingDisconnectedConnection = PhoneUtils.hasDisconnectedConnections(phone) && isShowingCallScreen; boolean keepScreenOn = isRinging || isDialing || showingDisconnectedConnection; if (DBG) Log.d(LOG_TAG, "updateWakeState: keepScreenOn = " + keepScreenOn + " (isRinging " + isRinging + ", isDialing " + isDialing + ", showingDisc " + showingDisconnectedConnection + ")"); // keepScreenOn == true means we'll hold a full wake lock: requestWakeState(keepScreenOn ? WakeState.FULL : WakeState.SLEEP); } /** * Wrapper around the PowerManagerService.preventScreenOn() API. * This allows the in-call UI to prevent the screen from turning on * even if a subsequent call to updateWakeState() causes us to acquire * a full wake lock. */ /* package */ void preventScreenOn(boolean prevent) { if (VDBG) Log.d(LOG_TAG, "- preventScreenOn(" + prevent + ")..."); try { mPowerManagerService.preventScreenOn(prevent); } catch (RemoteException e) { Log.w(LOG_TAG, "mPowerManagerService.preventScreenOn() failed: " + e); } } /** * Sets or clears the flag that tells the PowerManager that touch * (and cheek) events should NOT be considered "user activity". * * Since the in-call UI is totally insensitive to touch in most * states, we set this flag whenever the InCallScreen is in the * foreground. (Otherwise, repeated unintentional touches could * prevent the device from going to sleep.) * * There *are* some some touch events that really do count as user * activity, though. For those, we need to manually poke the * PowerManager's userActivity method; see pokeUserActivity(). */ /* package */ void setIgnoreTouchUserActivity(boolean ignore) { if (VDBG) Log.d(LOG_TAG, "setIgnoreTouchUserActivity(" + ignore + ")..."); mIgnoreTouchUserActivity = ignore; updatePokeLock(); } /** * Manually pokes the PowerManager's userActivity method. Since we * hold the POKE_LOCK_IGNORE_TOUCH_EVENTS poke lock while * the InCallScreen is active, we need to do this for touch events * that really do count as user activity (like pressing any * onscreen UI elements.) */ /* package */ void pokeUserActivity() { if (VDBG) Log.d(LOG_TAG, "pokeUserActivity()..."); try { mPowerManagerService.userActivity(SystemClock.uptimeMillis(), false); } catch (RemoteException e) { Log.w(LOG_TAG, "mPowerManagerService.userActivity() failed: " + e); } } /** * Set when a new outgoing call is beginning, so we can update * the proximity sensor state. * Cleared when the InCallScreen is no longer in the foreground, * in case the call fails without changing the telephony state. */ /* package */ void setBeginningCall(boolean beginning) { // Note that we are beginning a new call, for proximity sensor support mBeginningCall = beginning; // Update the Proximity sensor based on mBeginningCall state updateProximitySensorMode(mCM.getState()); } /** * Updates the wake lock used to control proximity sensor behavior, * based on the current state of the phone. This method is called * from the CallNotifier on any phone state change. * * On devices that have a proximity sensor, to avoid false touches * during a call, we hold a PROXIMITY_SCREEN_OFF_WAKE_LOCK wake lock * whenever the phone is off hook. (When held, that wake lock causes * the screen to turn off automatically when the sensor detects an * object close to the screen.) * * This method is a no-op for devices that don't have a proximity * sensor. * * Note this method doesn't care if the InCallScreen is the foreground * activity or not. That's because we want the proximity sensor to be * enabled any time the phone is in use, to avoid false cheek events * for whatever app you happen to be running. * * Proximity wake lock will *not* be held if any one of the * conditions is true while on a call: * 1) If the audio is routed via Bluetooth * 2) If a wired headset is connected * 3) if the speaker is ON * 4) If the slider is open(i.e. the hardkeyboard is *not* hidden) * * @param state current state of the phone (see {@link Phone#State}) */ /* package */ void updateProximitySensorMode(Phone.State state) { if (VDBG) Log.d(LOG_TAG, "updateProximitySensorMode: state = " + state); if (proximitySensorModeEnabled()) { synchronized (mProximityWakeLock) { // turn proximity sensor off and turn screen on immediately if // we are using a headset, the keyboard is open, or the device // is being held in a horizontal position. boolean screenOnImmediately = (isHeadsetPlugged() || PhoneUtils.isSpeakerOn(this) || ((mBtHandsfree != null) && mBtHandsfree.isAudioOn()) || mIsHardKeyboardOpen); // We do not keep the screen off when we are horizontal, but we do not force it // on when we become horizontal until the proximity sensor goes negative. boolean horizontal = (mOrientation == AccelerometerListener.ORIENTATION_HORIZONTAL); if (((state == Phone.State.OFFHOOK) || mBeginningCall) && !screenOnImmediately && !horizontal) { // Phone is in use! Arrange for the screen to turn off // automatically when the sensor detects a close object. if (!mProximityWakeLock.isHeld()) { if (DBG) Log.d(LOG_TAG, "updateProximitySensorMode: acquiring..."); mProximityWakeLock.acquire(); } else { if (VDBG) Log.d(LOG_TAG, "updateProximitySensorMode: lock already held."); } } else { // Phone is either idle, or ringing. We don't want any // special proximity sensor behavior in either case. if (mProximityWakeLock.isHeld()) { if (DBG) Log.d(LOG_TAG, "updateProximitySensorMode: releasing..."); // Wait until user has moved the phone away from his head if we are // releasing due to the phone call ending. // Qtherwise, turn screen on immediately int flags = (screenOnImmediately ? 0 : PowerManager.WAIT_FOR_PROXIMITY_NEGATIVE); mProximityWakeLock.release(flags); } else { if (VDBG) { Log.d(LOG_TAG, "updateProximitySensorMode: lock already released."); } } } } } } public void orientationChanged(int orientation) { mOrientation = orientation; updateProximitySensorMode(mCM.getState()); } /** * Notifies the phone app when the phone state changes. * Currently used only for proximity sensor support. */ /* package */ void updatePhoneState(Phone.State state) { if (state != mLastPhoneState) { mLastPhoneState = state; updateProximitySensorMode(state); if (mAccelerometerListener != null) { // use accelerometer to augment proximity sensor when in call mOrientation = AccelerometerListener.ORIENTATION_UNKNOWN; mAccelerometerListener.enable(state == Phone.State.OFFHOOK); } // clear our beginning call flag mBeginningCall = false; // While we are in call, the in-call screen should dismiss the keyguard. // This allows the user to press Home to go directly home without going through // an insecure lock screen. // But we do not want to do this if there is no active call so we do not // bypass the keyguard if the call is not answered or declined. if (mInCallScreen != null) { mInCallScreen.updateKeyguardPolicy(state == Phone.State.OFFHOOK); } } } /* package */ Phone.State getPhoneState() { return mLastPhoneState; } /** * @return true if this device supports the "proximity sensor * auto-lock" feature while in-call (see updateProximitySensorMode()). */ /* package */ boolean proximitySensorModeEnabled() { return (mProximityWakeLock != null); } KeyguardManager getKeyguardManager() { return mKeyguardManager; } private void onMMIComplete(AsyncResult r) { if (VDBG) Log.d(LOG_TAG, "onMMIComplete()..."); MmiCode mmiCode = (MmiCode) r.result; PhoneUtils.displayMMIComplete(phone, getInstance(), mmiCode, null, null); } private void initForNewRadioTechnology() { if (DBG) Log.d(LOG_TAG, "initForNewRadioTechnology..."); if (phone.getPhoneType() == Phone.PHONE_TYPE_CDMA) { // Create an instance of CdmaPhoneCallState and initialize it to IDLE cdmaPhoneCallState = new CdmaPhoneCallState(); cdmaPhoneCallState.CdmaPhoneCallStateInit(); } if (TelephonyCapabilities.supportsOtasp(phone)) { //create instances of CDMA OTA data classes if (cdmaOtaProvisionData == null) { cdmaOtaProvisionData = new OtaUtils.CdmaOtaProvisionData(); } if (cdmaOtaConfigData == null) { cdmaOtaConfigData = new OtaUtils.CdmaOtaConfigData(); } if (cdmaOtaScreenState == null) { cdmaOtaScreenState = new OtaUtils.CdmaOtaScreenState(); } if (cdmaOtaInCallScreenUiState == null) { cdmaOtaInCallScreenUiState = new OtaUtils.CdmaOtaInCallScreenUiState(); } } else { //Clean up OTA data in GSM/UMTS. It is valid only for CDMA clearOtaState(); } ringer.updateRingerContextAfterRadioTechnologyChange(this.phone); notifier.updateCallNotifierRegistrationsAfterRadioTechnologyChange(); if (mBtHandsfree != null) { mBtHandsfree.updateBtHandsfreeAfterRadioTechnologyChange(); } if (mInCallScreen != null) { mInCallScreen.updateAfterRadioTechnologyChange(); } // Update registration for ICC status after radio technology change IccCard sim = phone.getIccCard(); if (sim != null) { if (DBG) Log.d(LOG_TAG, "Update registration for ICC status..."); //Register all events new to the new active phone sim.registerForNetworkLocked(mHandler, EVENT_SIM_NETWORK_LOCKED, null); } } /** * @return true if a wired headset is currently plugged in. * * @see Intent.ACTION_HEADSET_PLUG (which we listen for in mReceiver.onReceive()) */ boolean isHeadsetPlugged() { return mIsHeadsetPlugged; } /** * @return true if the onscreen UI should currently be showing the * special "bluetooth is active" indication in a couple of places (in * which UI elements turn blue and/or show the bluetooth logo.) * * This depends on the BluetoothHeadset state *and* the current * telephony state; see shouldShowBluetoothIndication(). * * @see CallCard * @see NotificationMgr.updateInCallNotification */ /* package */ boolean showBluetoothIndication() { return mShowBluetoothIndication; } /** * Recomputes the mShowBluetoothIndication flag based on the current * bluetooth state and current telephony state. * * This needs to be called any time the bluetooth headset state or the * telephony state changes. * * @param forceUiUpdate if true, force the UI elements that care * about this flag to update themselves. */ /* package */ void updateBluetoothIndication(boolean forceUiUpdate) { mShowBluetoothIndication = shouldShowBluetoothIndication(mBluetoothHeadsetState, mBluetoothHeadsetAudioState, mCM); if (forceUiUpdate) { // Post Handler messages to the various components that might // need to be refreshed based on the new state. if (isShowingCallScreen()) mInCallScreen.requestUpdateBluetoothIndication(); if (DBG) Log.d (LOG_TAG, "- updating in-call notification for BT state change..."); mHandler.sendEmptyMessage(EVENT_UPDATE_INCALL_NOTIFICATION); } // Update the Proximity sensor based on Bluetooth audio state updateProximitySensorMode(mCM.getState()); } /** * UI policy helper function for the couple of places in the UI that * have some way of indicating that "bluetooth is in use." * * @return true if the onscreen UI should indicate that "bluetooth is in use", * based on the specified bluetooth headset state, and the * current state of the phone. * @see showBluetoothIndication() */ private static boolean shouldShowBluetoothIndication(int bluetoothState, int bluetoothAudioState, CallManager cm) { // We want the UI to indicate that "bluetooth is in use" in two // slightly different cases: // // (a) The obvious case: if a bluetooth headset is currently in // use for an ongoing call. // // (b) The not-so-obvious case: if an incoming call is ringing, // and we expect that audio *will* be routed to a bluetooth // headset once the call is answered. switch (cm.getState()) { case OFFHOOK: // This covers normal active calls, and also the case if // the foreground call is DIALING or ALERTING. In this // case, bluetooth is considered "active" if a headset // is connected *and* audio is being routed to it. return ((bluetoothState == BluetoothHeadset.STATE_CONNECTED) && (bluetoothAudioState == BluetoothHeadset.STATE_AUDIO_CONNECTED)); case RINGING: // If an incoming call is ringing, we're *not* yet routing // audio to the headset (since there's no in-call audio // yet!) In this case, if a bluetooth headset is // connected at all, we assume that it'll become active // once the user answers the phone. return (bluetoothState == BluetoothHeadset.STATE_CONNECTED); default: // Presumably IDLE return false; } } /** * Receiver for misc intent broadcasts the Phone app cares about. */ private class PhoneAppBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(Intent.ACTION_AIRPLANE_MODE_CHANGED)) { boolean enabled = System.getInt(getContentResolver(), System.AIRPLANE_MODE_ON, 0) == 0; phone.setRadioPower(enabled); } else if (action.equals(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED)) { mBluetoothHeadsetState = intent.getIntExtra(BluetoothHeadset.EXTRA_STATE, BluetoothHeadset.STATE_DISCONNECTED); if (VDBG) Log.d(LOG_TAG, "mReceiver: HEADSET_STATE_CHANGED_ACTION"); if (VDBG) Log.d(LOG_TAG, "==> new state: " + mBluetoothHeadsetState); updateBluetoothIndication(true); // Also update any visible UI if necessary } else if (action.equals(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED)) { mBluetoothHeadsetAudioState = intent.getIntExtra(BluetoothHeadset.EXTRA_STATE, BluetoothHeadset.STATE_AUDIO_DISCONNECTED); if (VDBG) Log.d(LOG_TAG, "mReceiver: HEADSET_AUDIO_STATE_CHANGED_ACTION"); if (VDBG) Log.d(LOG_TAG, "==> new state: " + mBluetoothHeadsetAudioState); updateBluetoothIndication(true); // Also update any visible UI if necessary } else if (action.equals(TelephonyIntents.ACTION_ANY_DATA_CONNECTION_STATE_CHANGED)) { if (VDBG) Log.d(LOG_TAG, "mReceiver: ACTION_ANY_DATA_CONNECTION_STATE_CHANGED"); if (VDBG) Log.d(LOG_TAG, "- state: " + intent.getStringExtra(Phone.STATE_KEY)); if (VDBG) Log.d(LOG_TAG, "- reason: " + intent.getStringExtra(Phone.STATE_CHANGE_REASON_KEY)); // The "data disconnected due to roaming" notification is // visible if you've lost data connectivity because you're // roaming and you have the "data roaming" feature turned off. boolean disconnectedDueToRoaming = false; if ("DISCONNECTED".equals(intent.getStringExtra(Phone.STATE_KEY))) { String reason = intent.getStringExtra(Phone.STATE_CHANGE_REASON_KEY); if (Phone.REASON_ROAMING_ON.equals(reason)) { // We just lost our data connection, and the reason // is that we started roaming. This implies that // the user has data roaming turned off. disconnectedDueToRoaming = true; } } mHandler.sendEmptyMessage(disconnectedDueToRoaming ? EVENT_DATA_ROAMING_DISCONNECTED : EVENT_DATA_ROAMING_OK); } else if (action.equals(Intent.ACTION_HEADSET_PLUG)) { if (VDBG) Log.d(LOG_TAG, "mReceiver: ACTION_HEADSET_PLUG"); if (VDBG) Log.d(LOG_TAG, " state: " + intent.getIntExtra("state", 0)); if (VDBG) Log.d(LOG_TAG, " name: " + intent.getStringExtra("name")); mIsHeadsetPlugged = (intent.getIntExtra("state", 0) == 1); mHandler.sendMessage(mHandler.obtainMessage(EVENT_WIRED_HEADSET_PLUG, 0)); } else if (action.equals(Intent.ACTION_BATTERY_LOW)) { if (VDBG) Log.d(LOG_TAG, "mReceiver: ACTION_BATTERY_LOW"); notifier.sendBatteryLow(); // Play a warning tone if in-call } else if ((action.equals(TelephonyIntents.ACTION_SIM_STATE_CHANGED)) && (mPUKEntryActivity != null)) { // if an attempt to un-PUK-lock the device was made, while we're // receiving this state change notification, notify the handler. // NOTE: This is ONLY triggered if an attempt to un-PUK-lock has // been attempted. mHandler.sendMessage(mHandler.obtainMessage(EVENT_SIM_STATE_CHANGED, intent.getStringExtra(IccCard.INTENT_KEY_ICC_STATE))); } else if (action.equals(TelephonyIntents.ACTION_RADIO_TECHNOLOGY_CHANGED)) { String newPhone = intent.getStringExtra(Phone.PHONE_NAME_KEY); Log.d(LOG_TAG, "Radio technology switched. Now " + newPhone + " is active."); initForNewRadioTechnology(); } else if (action.equals(TelephonyIntents.ACTION_SERVICE_STATE_CHANGED)) { handleServiceStateChanged(intent); } else if (action.equals(TelephonyIntents.ACTION_EMERGENCY_CALLBACK_MODE_CHANGED)) { if (TelephonyCapabilities.supportsEcm(phone)) { Log.d(LOG_TAG, "Emergency Callback Mode arrived in PhoneApp."); // Start Emergency Callback Mode service if (intent.getBooleanExtra("phoneinECMState", false)) { context.startService(new Intent(context, EmergencyCallbackModeService.class)); } } else { // It doesn't make sense to get ACTION_EMERGENCY_CALLBACK_MODE_CHANGED // on a device that doesn't support ECM in the first place. Log.e(LOG_TAG, "Got ACTION_EMERGENCY_CALLBACK_MODE_CHANGED, " + "but ECM isn't supported for phone: " + phone.getPhoneName()); } } else if (action.equals(Intent.ACTION_DOCK_EVENT)) { mDockState = intent.getIntExtra(Intent.EXTRA_DOCK_STATE, Intent.EXTRA_DOCK_STATE_UNDOCKED); if (VDBG) Log.d(LOG_TAG, "ACTION_DOCK_EVENT -> mDockState = " + mDockState); mHandler.sendMessage(mHandler.obtainMessage(EVENT_DOCK_STATE_CHANGED, 0)); } else if (action.equals(TtyIntent.TTY_PREFERRED_MODE_CHANGE_ACTION)) { mPreferredTtyMode = intent.getIntExtra(TtyIntent.TTY_PREFFERED_MODE, Phone.TTY_MODE_OFF); if (VDBG) Log.d(LOG_TAG, "mReceiver: TTY_PREFERRED_MODE_CHANGE_ACTION"); if (VDBG) Log.d(LOG_TAG, " mode: " + mPreferredTtyMode); mHandler.sendMessage(mHandler.obtainMessage(EVENT_TTY_PREFERRED_MODE_CHANGED, 0)); } else if (action.equals(AudioManager.RINGER_MODE_CHANGED_ACTION)) { int ringerMode = intent.getIntExtra(AudioManager.EXTRA_RINGER_MODE, AudioManager.RINGER_MODE_NORMAL); if (ringerMode == AudioManager.RINGER_MODE_SILENT) { notifier.silenceRinger(); } } } } /** * Broadcast receiver for the ACTION_MEDIA_BUTTON broadcast intent. * * This functionality isn't lumped in with the other intents in * PhoneAppBroadcastReceiver because we instantiate this as a totally * separate BroadcastReceiver instance, since we need to manually * adjust its IntentFilter's priority (to make sure we get these * intents *before* the media player.) */ private class MediaButtonBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { KeyEvent event = (KeyEvent) intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT); if (VDBG) Log.d(LOG_TAG, "MediaButtonBroadcastReceiver.onReceive()... event = " + event); if ((event != null) && (event.getKeyCode() == KeyEvent.KEYCODE_HEADSETHOOK)) { if (VDBG) Log.d(LOG_TAG, "MediaButtonBroadcastReceiver: HEADSETHOOK"); boolean consumed = PhoneUtils.handleHeadsetHook(phone, event); if (VDBG) Log.d(LOG_TAG, "==> handleHeadsetHook(): consumed = " + consumed); if (consumed) { // If a headset is attached and the press is consumed, also update // any UI items (such as an InCallScreen mute button) that may need to // be updated if their state changed. updateInCallScreen(); // Has no effect if the InCallScreen isn't visible abortBroadcast(); } } else { if (mCM.getState() != Phone.State.IDLE) { // If the phone is anything other than completely idle, // then we consume and ignore any media key events, // Otherwise it is too easy to accidentally start // playing music while a phone call is in progress. if (VDBG) Log.d(LOG_TAG, "MediaButtonBroadcastReceiver: consumed"); abortBroadcast(); } } } } private void handleServiceStateChanged(Intent intent) { /** * This used to handle updating EriTextWidgetProvider this routine * and and listening for ACTION_SERVICE_STATE_CHANGED intents could * be removed. But leaving just in case it might be needed in the near * future. */ // If service just returned, start sending out the queued messages ServiceState ss = ServiceState.newFromBundle(intent.getExtras()); if (ss != null) { int state = ss.getState(); notificationMgr.updateNetworkSelection(state); } } public boolean isOtaCallInActiveState() { boolean otaCallActive = false; if (mInCallScreen != null) { otaCallActive = mInCallScreen.isOtaCallInActiveState(); } if (VDBG) Log.d(LOG_TAG, "- isOtaCallInActiveState " + otaCallActive); return otaCallActive; } public boolean isOtaCallInEndState() { boolean otaCallEnded = false; if (mInCallScreen != null) { otaCallEnded = mInCallScreen.isOtaCallInEndState(); } if (VDBG) Log.d(LOG_TAG, "- isOtaCallInEndState " + otaCallEnded); return otaCallEnded; } // it is safe to call clearOtaState() even if the InCallScreen isn't active public void clearOtaState() { if (DBG) Log.d(LOG_TAG, "- clearOtaState ..."); if ((mInCallScreen != null) && (otaUtils != null)) { otaUtils.cleanOtaScreen(true); if (DBG) Log.d(LOG_TAG, " - clearOtaState clears OTA screen"); } } // it is safe to call dismissOtaDialogs() even if the InCallScreen isn't active public void dismissOtaDialogs() { if (DBG) Log.d(LOG_TAG, "- dismissOtaDialogs ..."); if ((mInCallScreen != null) && (otaUtils != null)) { otaUtils.dismissAllOtaDialogs(); if (DBG) Log.d(LOG_TAG, " - dismissOtaDialogs clears OTA dialogs"); } } // it is safe to call clearInCallScreenMode() even if the InCallScreen isn't active public void clearInCallScreenMode() { if (DBG) Log.d(LOG_TAG, "- clearInCallScreenMode ..."); if (mInCallScreen != null) { mInCallScreen.resetInCallScreenMode(); } } /** * Force the in-call UI to refresh itself, if it's currently visible. * * This method can be used any time there's a state change anywhere in * the phone app that needs to be reflected in the onscreen UI. * * Note that it's *not* necessary to manually refresh the in-call UI * (via this method) for regular telephony state changes like * DIALING -> ALERTING -> ACTIVE, since the InCallScreen already * listens for those state changes itself. * * This method does *not* force the in-call UI to come up if it's not * already visible. To do that, use displayCallScreen(). */ /* package */ void updateInCallScreen() { if (DBG) Log.d(LOG_TAG, "- updateInCallScreen()..."); if (mInCallScreen != null) { // Post an updateScreen() request. Note that the // updateScreen() call will end up being a no-op if the // InCallScreen isn't the foreground activity. mInCallScreen.requestUpdateScreen(); } } private void handleQueryTTYModeResponse(Message msg) { AsyncResult ar = (AsyncResult) msg.obj; if (ar.exception != null) { if (DBG) Log.d(LOG_TAG, "handleQueryTTYModeResponse: Error getting TTY state."); } else { if (DBG) Log.d(LOG_TAG, "handleQueryTTYModeResponse: TTY enable state successfully queried."); int ttymode = ((int[]) ar.result)[0]; if (DBG) Log.d(LOG_TAG, "handleQueryTTYModeResponse:ttymode=" + ttymode); Intent ttyModeChanged = new Intent(TtyIntent.TTY_ENABLED_CHANGE_ACTION); ttyModeChanged.putExtra("ttyEnabled", ttymode != Phone.TTY_MODE_OFF); sendBroadcast(ttyModeChanged); String audioTtyMode; switch (ttymode) { case Phone.TTY_MODE_FULL: audioTtyMode = "tty_full"; break; case Phone.TTY_MODE_VCO: audioTtyMode = "tty_vco"; break; case Phone.TTY_MODE_HCO: audioTtyMode = "tty_hco"; break; case Phone.TTY_MODE_OFF: default: audioTtyMode = "tty_off"; break; } AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); audioManager.setParameters("tty_mode="+audioTtyMode); } } private void handleSetTTYModeResponse(Message msg) { AsyncResult ar = (AsyncResult) msg.obj; if (ar.exception != null) { if (DBG) Log.d (LOG_TAG, "handleSetTTYModeResponse: Error setting TTY mode, ar.exception" + ar.exception); } phone.queryTTYMode(mHandler.obtainMessage(EVENT_TTY_MODE_GET)); } /* package */ void clearUserActivityTimeout() { try { mPowerManagerService.clearUserActivityTimeout(SystemClock.uptimeMillis(), 10*1000 /* 10 sec */); } catch (RemoteException ex) { // System process is dead. } } /** * "Call origin" may be used by Contacts app to specify where the phone call comes from. * Currently, the only permitted value for this extra is {@link #ALLOWED_EXTRA_CALL_ORIGIN}. * Any other value will be ignored, to make sure that malicious apps can't trick the in-call * UI into launching some random other app after a call ends. * * TODO: make this more generic. Note that we should let the "origin" specify its package * while we are now assuming it is "com.android.contacts" */ public static final String EXTRA_CALL_ORIGIN = "com.android.phone.CALL_ORIGIN"; private static final String DEFAULT_CALL_ORIGIN_PACKAGE = "com.android.contacts"; private static final String ALLOWED_EXTRA_CALL_ORIGIN = "com.android.contacts.activities.DialtactsActivity"; public void setLatestActiveCallOrigin(String callOrigin) { inCallUiState.latestActiveCallOrigin = callOrigin; } /** * @return Intent which will be used when in-call UI is shown and the phone call is hang up. * By default CallLog screen will be introduced, but the destination may change depending on * its latest call origin state. */ public Intent createPhoneEndIntentUsingCallOrigin() { if (TextUtils.equals(inCallUiState.latestActiveCallOrigin, ALLOWED_EXTRA_CALL_ORIGIN)) { if (VDBG) Log.d(LOG_TAG, "Valid latestActiveCallOrigin(" + inCallUiState.latestActiveCallOrigin + ") was found. " + "Go back to the previous screen."); // Right now we just launch the Activity which launched in-call UI. Note that we're // assuming the origin is from "com.android.contacts", which may be incorrect in the // future. final Intent intent = new Intent(); intent.setClassName(DEFAULT_CALL_ORIGIN_PACKAGE, inCallUiState.latestActiveCallOrigin); return intent; } else { if (VDBG) Log.d(LOG_TAG, "Current latestActiveCallOrigin (" + inCallUiState.latestActiveCallOrigin + ") is not valid. " + "Just use CallLog as a default destination."); return PhoneApp.createCallLogIntent(); } } } diff --git a/src/com/android/phone/PhoneUtils.java b/src/com/android/phone/PhoneUtils.java index 29b89958..0bed83df 100644 --- a/src/com/android/phone/PhoneUtils.java +++ b/src/com/android/phone/PhoneUtils.java @@ -1,2576 +1,2575 @@ /* * Copyright (C) 2006 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.phone; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.ComponentName; import android.content.ContentResolver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.ServiceConnection; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.graphics.drawable.Drawable; import android.media.AudioManager; import android.net.Uri; import android.net.sip.SipManager; import android.os.AsyncResult; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.RemoteException; import android.os.SystemProperties; import android.telephony.PhoneNumberUtils; import android.text.TextUtils; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.WindowManager; import android.widget.EditText; import android.widget.Toast; import com.android.internal.telephony.Call; import com.android.internal.telephony.CallStateException; import com.android.internal.telephony.CallerInfo; import com.android.internal.telephony.CallerInfoAsyncQuery; import com.android.internal.telephony.Connection; import com.android.internal.telephony.IExtendedNetworkService; import com.android.internal.telephony.MmiCode; import com.android.internal.telephony.Phone; import com.android.internal.telephony.TelephonyProperties; import com.android.internal.telephony.cdma.CdmaConnection; import com.android.internal.telephony.CallManager; import com.android.internal.telephony.sip.SipPhone; import java.util.ArrayList; import java.util.Hashtable; import java.util.Iterator; import java.util.List; /** * Misc utilities for the Phone app. */ public class PhoneUtils { private static final String LOG_TAG = "PhoneUtils"; private static final boolean DBG = (PhoneApp.DBG_LEVEL >= 2); /** Control stack trace for Audio Mode settings */ private static final boolean DBG_SETAUDIOMODE_STACK = false; /** Identifier for the "Add Call" intent extra. */ static final String ADD_CALL_MODE_KEY = "add_call_mode"; // Return codes from placeCall() static final int CALL_STATUS_DIALED = 0; // The number was successfully dialed static final int CALL_STATUS_DIALED_MMI = 1; // The specified number was an MMI code static final int CALL_STATUS_FAILED = 2; // The call failed // State of the Phone's audio modes // Each state can move to the other states, but within the state only certain // transitions for AudioManager.setMode() are allowed. static final int AUDIO_IDLE = 0; /** audio behaviour at phone idle */ static final int AUDIO_RINGING = 1; /** audio behaviour while ringing */ static final int AUDIO_OFFHOOK = 2; /** audio behaviour while in call. */ /** Speaker state, persisting between wired headset connection events */ private static boolean sIsSpeakerEnabled = false; /** Hash table to store mute (Boolean) values based upon the connection.*/ private static Hashtable<Connection, Boolean> sConnectionMuteTable = new Hashtable<Connection, Boolean>(); /** Static handler for the connection/mute tracking */ private static ConnectionHandler mConnectionHandler; /** Phone state changed event*/ private static final int PHONE_STATE_CHANGED = -1; /** Define for not a special CNAP string */ private static final int CNAP_SPECIAL_CASE_NO = -1; // Extended network service interface instance private static IExtendedNetworkService mNwService = null; // used to cancel MMI command after 15 seconds timeout for NWService requirement private static Message mMmiTimeoutCbMsg = null; /** Noise suppression status as selected by user */ private static boolean sIsNoiseSuppressionEnabled = true; /** * Handler that tracks the connections and updates the value of the * Mute settings for each connection as needed. */ private static class ConnectionHandler extends Handler { @Override public void handleMessage(Message msg) { AsyncResult ar = (AsyncResult) msg.obj; switch (msg.what) { case PHONE_STATE_CHANGED: if (DBG) log("ConnectionHandler: updating mute state for each connection"); CallManager cm = (CallManager) ar.userObj; // update the foreground connections, if there are new connections. // Have to get all foreground calls instead of the active one // because there may two foreground calls co-exist in shore period // (a racing condition based on which phone changes firstly) // Otherwise the connection may get deleted. List<Connection> fgConnections = new ArrayList<Connection>(); for (Call fgCall : cm.getForegroundCalls()) { if (!fgCall.isIdle()) { fgConnections.addAll(fgCall.getConnections()); } } for (Connection cn : fgConnections) { if (sConnectionMuteTable.get(cn) == null) { sConnectionMuteTable.put(cn, Boolean.FALSE); } } // mute is connection based operation, we need loop over // all background calls instead of the first one to update // the background connections, if there are new connections. List<Connection> bgConnections = new ArrayList<Connection>(); for (Call bgCall : cm.getBackgroundCalls()) { if (!bgCall.isIdle()) { bgConnections.addAll(bgCall.getConnections()); } } for (Connection cn : bgConnections) { if (sConnectionMuteTable.get(cn) == null) { sConnectionMuteTable.put(cn, Boolean.FALSE); } } // Check to see if there are any lingering connections here // (disconnected connections), use old-school iterators to avoid // concurrent modification exceptions. Connection cn; for (Iterator<Connection> cnlist = sConnectionMuteTable.keySet().iterator(); cnlist.hasNext();) { cn = cnlist.next(); if (!fgConnections.contains(cn) && !bgConnections.contains(cn)) { if (DBG) log("connection '" + cn + "' not accounted for, removing."); cnlist.remove(); } } // Restore the mute state of the foreground call if we're not IDLE, // otherwise just clear the mute state. This is really saying that // as long as there is one or more connections, we should update // the mute state with the earliest connection on the foreground // call, and that with no connections, we should be back to a // non-mute state. if (cm.getState() != Phone.State.IDLE) { restoreMuteState(); } else { setMuteInternal(cm.getFgPhone(), false); } break; } } } private static ServiceConnection ExtendedNetworkServiceConnection = new ServiceConnection() { public void onServiceConnected(ComponentName name, IBinder iBinder) { if (DBG) log("Extended NW onServiceConnected"); mNwService = IExtendedNetworkService.Stub.asInterface(iBinder); } public void onServiceDisconnected(ComponentName arg0) { if (DBG) log("Extended NW onServiceDisconnected"); mNwService = null; } }; /** * Register the ConnectionHandler with the phone, to receive connection events */ public static void initializeConnectionHandler(CallManager cm) { if (mConnectionHandler == null) { mConnectionHandler = new ConnectionHandler(); } // pass over cm as user.obj cm.registerForPreciseCallStateChanged(mConnectionHandler, PHONE_STATE_CHANGED, cm); // Extended NW service Intent intent = new Intent("com.android.ussd.IExtendedNetworkService"); cm.getDefaultPhone().getContext().bindService(intent, ExtendedNetworkServiceConnection, Context.BIND_AUTO_CREATE); if (DBG) log("Extended NW bindService IExtendedNetworkService"); } /** This class is never instantiated. */ private PhoneUtils() { } /** * Answer the currently-ringing call. * * @return true if we answered the call, or false if there wasn't * actually a ringing incoming call, or some other error occurred. * * @see answerAndEndHolding() * @see answerAndEndActive() */ static boolean answerCall(Call ringing) { log("answerCall(" + ringing + ")..."); final PhoneApp app = PhoneApp.getInstance(); // If the ringer is currently ringing and/or vibrating, stop it // right now (before actually answering the call.) app.getRinger().stopRing(); boolean answered = false; Phone phone = ringing.getPhone(); boolean phoneIsCdma = (phone.getPhoneType() == Phone.PHONE_TYPE_CDMA); BluetoothHandsfree bthf = null; if (phoneIsCdma) { // Stop any signalInfo tone being played when a Call waiting gets answered if (ringing.getState() == Call.State.WAITING) { final CallNotifier notifier = app.notifier; notifier.stopSignalInfoTone(); } } if (ringing != null && ringing.isRinging()) { if (DBG) log("answerCall: call state = " + ringing.getState()); try { if (phoneIsCdma) { if (app.cdmaPhoneCallState.getCurrentCallState() == CdmaPhoneCallState.PhoneCallState.IDLE) { // This is the FIRST incoming call being answered. // Set the Phone Call State to SINGLE_ACTIVE app.cdmaPhoneCallState.setCurrentCallState( CdmaPhoneCallState.PhoneCallState.SINGLE_ACTIVE); } else { // This is the CALL WAITING call being answered. // Set the Phone Call State to CONF_CALL app.cdmaPhoneCallState.setCurrentCallState( CdmaPhoneCallState.PhoneCallState.CONF_CALL); // Enable "Add Call" option after answering a Call Waiting as the user // should be allowed to add another call in case one of the parties // drops off app.cdmaPhoneCallState.setAddCallMenuStateAfterCallWaiting(true); // If a BluetoothHandsfree is valid we need to set the second call state // so that the Bluetooth client can update the Call state correctly when // a call waiting is answered from the Phone. bthf = app.getBluetoothHandsfree(); if (bthf != null) { bthf.cdmaSetSecondCallState(true); } } } //if (DBG) log("sPhone.acceptCall"); app.mCM.acceptCall(ringing); answered = true; // Always reset to "unmuted" for a freshly-answered call setMute(false); setAudioMode(); // Check is phone in any dock, and turn on speaker accordingly activateSpeakerIfDocked(phone); } catch (CallStateException ex) { Log.w(LOG_TAG, "answerCall: caught " + ex, ex); if (phoneIsCdma) { // restore the cdmaPhoneCallState and bthf.cdmaSetSecondCallState: app.cdmaPhoneCallState.setCurrentCallState( app.cdmaPhoneCallState.getPreviousCallState()); if (bthf != null) { bthf.cdmaSetSecondCallState(false); } } } } return answered; } /** * Smart "hang up" helper method which hangs up exactly one connection, * based on the current Phone state, as follows: * <ul> * <li>If there's a ringing call, hang that up. * <li>Else if there's a foreground call, hang that up. * <li>Else if there's a background call, hang that up. * <li>Otherwise do nothing. * </ul> * @return true if we successfully hung up, or false * if there were no active calls at all. */ static boolean hangup(CallManager cm) { boolean hungup = false; Call ringing = cm.getFirstActiveRingingCall(); Call fg = cm.getActiveFgCall(); Call bg = cm.getFirstActiveBgCall(); if (!ringing.isIdle()) { log("hangup(): hanging up ringing call"); hungup = hangupRingingCall(ringing); } else if (!fg.isIdle()) { log("hangup(): hanging up foreground call"); hungup = hangup(fg); } else if (!bg.isIdle()) { log("hangup(): hanging up background call"); hungup = hangup(bg); } else { // No call to hang up! This is unlikely in normal usage, // since the UI shouldn't be providing an "End call" button in // the first place. (But it *can* happen, rarely, if an // active call happens to disconnect on its own right when the // user is trying to hang up..) log("hangup(): no active call to hang up"); } if (DBG) log("==> hungup = " + hungup); return hungup; } static boolean hangupRingingCall(Call ringing) { if (DBG) log("hangup ringing call"); int phoneType = ringing.getPhone().getPhoneType(); Call.State state = ringing.getState(); if (state == Call.State.INCOMING) { // Regular incoming call (with no other active calls) log("hangupRingingCall(): regular incoming call: hangup()"); return hangup(ringing); } else if (state == Call.State.WAITING) { // Call-waiting: there's an incoming call, but another call is // already active. // TODO: It would be better for the telephony layer to provide // a "hangupWaitingCall()" API that works on all devices, // rather than us having to check the phone type here and do // the notifier.sendCdmaCallWaitingReject() hack for CDMA phones. if (phoneType == Phone.PHONE_TYPE_CDMA) { // CDMA: Ringing call and Call waiting hangup is handled differently. // For Call waiting we DO NOT call the conventional hangup(call) function // as in CDMA we just want to hangup the Call waiting connection. log("hangupRingingCall(): CDMA-specific call-waiting hangup"); final CallNotifier notifier = PhoneApp.getInstance().notifier; notifier.sendCdmaCallWaitingReject(); return true; } else { // Otherwise, the regular hangup() API works for // call-waiting calls too. log("hangupRingingCall(): call-waiting call: hangup()"); return hangup(ringing); } } else { // Unexpected state: the ringing call isn't INCOMING or // WAITING, so there's no reason to have called // hangupRingingCall() in the first place. // (Presumably the incoming call went away at the exact moment // we got here, so just do nothing.) Log.w(LOG_TAG, "hangupRingingCall: no INCOMING or WAITING call"); return false; } } static boolean hangupActiveCall(Call foreground) { if (DBG) log("hangup active call"); return hangup(foreground); } static boolean hangupHoldingCall(Call background) { if (DBG) log("hangup holding call"); return hangup(background); } /** * Used in CDMA phones to end the complete Call session * @param phone the Phone object. * @return true if *any* call was successfully hung up */ static boolean hangupRingingAndActive(Phone phone) { boolean hungUpRingingCall = false; boolean hungUpFgCall = false; Call ringingCall = phone.getRingingCall(); Call fgCall = phone.getForegroundCall(); // Hang up any Ringing Call if (!ringingCall.isIdle()) { log("hangupRingingAndActive: Hang up Ringing Call"); hungUpRingingCall = hangupRingingCall(ringingCall); } // Hang up any Active Call if (!fgCall.isIdle()) { log("hangupRingingAndActive: Hang up Foreground Call"); hungUpFgCall = hangupActiveCall(fgCall); } return hungUpRingingCall || hungUpFgCall; } /** * Trivial wrapper around Call.hangup(), except that we return a * boolean success code rather than throwing CallStateException on * failure. * * @return true if the call was successfully hung up, or false * if the call wasn't actually active. */ static boolean hangup(Call call) { try { CallManager cm = PhoneApp.getInstance().mCM; if (call.getState() == Call.State.ACTIVE && cm.hasActiveBgCall()) { // handle foreground call hangup while there is background call log("- hangup(Call): hangupForegroundResumeBackground..."); cm.hangupForegroundResumeBackground(cm.getFirstActiveBgCall()); } else { log("- hangup(Call): regular hangup()..."); call.hangup(); } return true; } catch (CallStateException ex) { Log.e(LOG_TAG, "Call hangup: caught " + ex, ex); } return false; } /** * Trivial wrapper around Connection.hangup(), except that we silently * do nothing (rather than throwing CallStateException) if the * connection wasn't actually active. */ static void hangup(Connection c) { try { if (c != null) { c.hangup(); } } catch (CallStateException ex) { Log.w(LOG_TAG, "Connection hangup: caught " + ex, ex); } } static boolean answerAndEndHolding(CallManager cm, Call ringing) { if (DBG) log("end holding & answer waiting: 1"); if (!hangupHoldingCall(cm.getFirstActiveBgCall())) { Log.e(LOG_TAG, "end holding failed!"); return false; } if (DBG) log("end holding & answer waiting: 2"); return answerCall(ringing); } static boolean answerAndEndActive(CallManager cm, Call ringing) { if (DBG) log("answerAndEndActive()..."); // Unlike the answerCall() method, we *don't* need to stop the // ringer or change audio modes here since the user is already // in-call, which means that the audio mode is already set // correctly, and that we wouldn't have started the ringer in the // first place. // hanging up the active call also accepts the waiting call // while active call and waiting call are from the same phone // i.e. both from GSM phone if ( !hangupActiveCall(cm.getActiveFgCall())) { Log.w(LOG_TAG, "end active call failed!"); return false; } // since hangupActiveCall() also accepts the ringing call // check if the ringing call was already answered or not // only answer it when the call still is ringing if (ringing.isRinging()) { return answerCall(ringing); } return true; } /** * For a CDMA phone, advance the call state upon making a new * outgoing call. * * <pre> * IDLE -> SINGLE_ACTIVE * or * SINGLE_ACTIVE -> THRWAY_ACTIVE * </pre> * @param app The phone instance. */ private static void updateCdmaCallStateOnNewOutgoingCall(PhoneApp app) { if (app.cdmaPhoneCallState.getCurrentCallState() == CdmaPhoneCallState.PhoneCallState.IDLE) { // This is the first outgoing call. Set the Phone Call State to ACTIVE app.cdmaPhoneCallState.setCurrentCallState( CdmaPhoneCallState.PhoneCallState.SINGLE_ACTIVE); } else { // This is the second outgoing call. Set the Phone Call State to 3WAY app.cdmaPhoneCallState.setCurrentCallState( CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE); } } /** * Dial the number using the phone passed in. * * If the connection is establised, this method issues a sync call * that may block to query the caller info. * TODO: Change the logic to use the async query. * * @param context To perform the CallerInfo query. * @param phone the Phone object. * @param number to be dialed as requested by the user. This is * NOT the phone number to connect to. It is used only to build the * call card and to update the call log. See above for restrictions. * @param contactRef that triggered the call. Typically a 'tel:' * uri but can also be a 'content://contacts' one. * @param isEmergencyCall indicates that whether or not this is an * emergency call * @param gatewayUri Is the address used to setup the connection, null * if not using a gateway * * @return either CALL_STATUS_DIALED or CALL_STATUS_FAILED */ public static int placeCall(Context context, Phone phone, String number, Uri contactRef, boolean isEmergencyCall, Uri gatewayUri) { if (DBG) log("placeCall '" + number + "' GW:'" + gatewayUri + "'"); final PhoneApp app = PhoneApp.getInstance(); boolean useGateway = false; if (null != gatewayUri && !isEmergencyCall && PhoneUtils.isRoutableViaGateway(number)) { // Filter out MMI, OTA and other codes. useGateway = true; } int status = CALL_STATUS_DIALED; Connection connection; String numberToDial; if (useGateway) { // TODO: 'tel' should be a constant defined in framework base // somewhere (it is in webkit.) if (null == gatewayUri || !Constants.SCHEME_TEL.equals(gatewayUri.getScheme())) { Log.e(LOG_TAG, "Unsupported URL:" + gatewayUri); return CALL_STATUS_FAILED; } // We can use getSchemeSpecificPart because we don't allow # // in the gateway numbers (treated a fragment delim.) However // if we allow more complex gateway numbers sequence (with // passwords or whatnot) that use #, this may break. // TODO: Need to support MMI codes. numberToDial = gatewayUri.getSchemeSpecificPart(); } else { numberToDial = number; } try { connection = app.mCM.dial(phone, numberToDial); } catch (CallStateException ex) { // CallStateException means a new outgoing call is not currently // possible: either no more call slots exist, or there's another // call already in the process of dialing or ringing. Log.w(LOG_TAG, "Exception from app.mCM.dial()", ex); return CALL_STATUS_FAILED; // Note that it's possible for CallManager.dial() to return // null *without* throwing an exception; that indicates that // we dialed an MMI (see below). } int phoneType = phone.getPhoneType(); // On GSM phones, null is returned for MMI codes if (null == connection) { if (phoneType == Phone.PHONE_TYPE_GSM && gatewayUri == null) { if (DBG) log("dialed MMI code: " + number); status = CALL_STATUS_DIALED_MMI; // Set dialed MMI command to service if (mNwService != null) { try { mNwService.setMmiString(number); if (DBG) log("Extended NW bindService setUssdString (" + number + ")"); } catch (RemoteException e) { mNwService = null; } } } else { status = CALL_STATUS_FAILED; } } else { if (phoneType == Phone.PHONE_TYPE_CDMA) { updateCdmaCallStateOnNewOutgoingCall(app); } // Clean up the number to be displayed. if (phoneType == Phone.PHONE_TYPE_CDMA) { number = CdmaConnection.formatDialString(number); } number = PhoneNumberUtils.extractNetworkPortion(number); number = PhoneNumberUtils.convertKeypadLettersToDigits(number); number = PhoneNumberUtils.formatNumber(number); if (gatewayUri == null) { // phone.dial() succeeded: we're now in a normal phone call. // attach the URI to the CallerInfo Object if it is there, // otherwise just attach the Uri Reference. // if the uri does not have a "content" scheme, then we treat // it as if it does NOT have a unique reference. String content = context.getContentResolver().SCHEME_CONTENT; if ((contactRef != null) && (contactRef.getScheme().equals(content))) { Object userDataObject = connection.getUserData(); if (userDataObject == null) { connection.setUserData(contactRef); } else { // TODO: This branch is dead code, we have // just created the connection which has // no user data (null) by default. if (userDataObject instanceof CallerInfo) { ((CallerInfo) userDataObject).contactRefUri = contactRef; } else { ((CallerInfoToken) userDataObject).currentInfo.contactRefUri = contactRef; } } } } else { // Get the caller info synchronously because we need the final // CallerInfo object to update the dialed number with the one // requested by the user (and not the provider's gateway number). CallerInfo info = null; String content = phone.getContext().getContentResolver().SCHEME_CONTENT; if ((contactRef != null) && (contactRef.getScheme().equals(content))) { info = CallerInfo.getCallerInfo(context, contactRef); } // Fallback, lookup contact using the phone number if the // contact's URI scheme was not content:// or if is was but // the lookup failed. if (null == info) { info = CallerInfo.getCallerInfo(context, number); } info.phoneNumber = number; connection.setUserData(info); } setAudioMode(); if (DBG) log("about to activate speaker"); // Check is phone in any dock, and turn on speaker accordingly activateSpeakerIfDocked(phone); } return status; } /** * Wrapper function to control when to send an empty Flash command to the network. * Mainly needed for CDMA networks, such as scenarios when we need to send a blank flash * to the network prior to placing a 3-way call for it to be successful. */ static void sendEmptyFlash(Phone phone) { if (phone.getPhoneType() == Phone.PHONE_TYPE_CDMA) { Call fgCall = phone.getForegroundCall(); if (fgCall.getState() == Call.State.ACTIVE) { // Send the empty flash if (DBG) Log.d(LOG_TAG, "onReceive: (CDMA) sending empty flash to network"); switchHoldingAndActive(phone.getBackgroundCall()); } } } /** * @param heldCall is the background call want to be swapped */ static void switchHoldingAndActive(Call heldCall) { log("switchHoldingAndActive()..."); try { CallManager cm = PhoneApp.getInstance().mCM; if (heldCall.isIdle()) { // no heldCall, so it is to hold active call cm.switchHoldingAndActive(cm.getFgPhone().getBackgroundCall()); } else { // has particular heldCall, so to switch cm.switchHoldingAndActive(heldCall); } setAudioMode(cm); } catch (CallStateException ex) { Log.w(LOG_TAG, "switchHoldingAndActive: caught " + ex, ex); } } /** * Restore the mute setting from the earliest connection of the * foreground call. */ static Boolean restoreMuteState() { Phone phone = PhoneApp.getInstance().mCM.getFgPhone(); //get the earliest connection Connection c = phone.getForegroundCall().getEarliestConnection(); // only do this if connection is not null. if (c != null) { int phoneType = phone.getPhoneType(); // retrieve the mute value. Boolean shouldMute = null; // In CDMA, mute is not maintained per Connection. Single mute apply for // a call where call can have multiple connections such as // Three way and Call Waiting. Therefore retrieving Mute state for // latest connection can apply for all connection in that call if (phoneType == Phone.PHONE_TYPE_CDMA) { shouldMute = sConnectionMuteTable.get( phone.getForegroundCall().getLatestConnection()); } else if ((phoneType == Phone.PHONE_TYPE_GSM) || (phoneType == Phone.PHONE_TYPE_SIP)) { shouldMute = sConnectionMuteTable.get(c); } if (shouldMute == null) { if (DBG) log("problem retrieving mute value for this connection."); shouldMute = Boolean.FALSE; } // set the mute value and return the result. setMute (shouldMute.booleanValue()); return shouldMute; } return Boolean.valueOf(getMute()); } static void mergeCalls() { mergeCalls(PhoneApp.getInstance().mCM); } static void mergeCalls(CallManager cm) { int phoneType = cm.getFgPhone().getPhoneType(); if (phoneType == Phone.PHONE_TYPE_CDMA) { log("mergeCalls(): CDMA..."); PhoneApp app = PhoneApp.getInstance(); if (app.cdmaPhoneCallState.getCurrentCallState() == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE) { // Set the Phone Call State to conference app.cdmaPhoneCallState.setCurrentCallState( CdmaPhoneCallState.PhoneCallState.CONF_CALL); // Send flash cmd // TODO: Need to change the call from switchHoldingAndActive to // something meaningful as we are not actually trying to swap calls but // instead are merging two calls by sending a Flash command. log("- sending flash..."); switchHoldingAndActive(cm.getFirstActiveBgCall()); } } else { try { log("mergeCalls(): calling cm.conference()..."); cm.conference(cm.getFirstActiveBgCall()); } catch (CallStateException ex) { Log.w(LOG_TAG, "mergeCalls: caught " + ex, ex); } } } static void separateCall(Connection c) { try { if (DBG) log("separateCall: " + c.getAddress()); c.separate(); } catch (CallStateException ex) { Log.w(LOG_TAG, "separateCall: caught " + ex, ex); } } /** * Handle the MMIInitiate message and put up an alert that lets * the user cancel the operation, if applicable. * * @param context context to get strings. * @param mmiCode the MmiCode object being started. * @param buttonCallbackMessage message to post when button is clicked. * @param previousAlert a previous alert used in this activity. * @return the dialog handle */ static Dialog displayMMIInitiate(Context context, MmiCode mmiCode, Message buttonCallbackMessage, Dialog previousAlert) { if (DBG) log("displayMMIInitiate: " + mmiCode); if (previousAlert != null) { previousAlert.dismiss(); } // The UI paradigm we are using now requests that all dialogs have // user interaction, and that any other messages to the user should // be by way of Toasts. // // In adhering to this request, all MMI initiating "OK" dialogs // (non-cancelable MMIs) that end up being closed when the MMI // completes (thereby showing a completion dialog) are being // replaced with Toasts. // // As a side effect, moving to Toasts for the non-cancelable MMIs // also means that buttonCallbackMessage (which was tied into "OK") // is no longer invokable for these dialogs. This is not a problem // since the only callback messages we supported were for cancelable // MMIs anyway. // // A cancelable MMI is really just a USSD request. The term // "cancelable" here means that we can cancel the request when the // system prompts us for a response, NOT while the network is // processing the MMI request. Any request to cancel a USSD while // the network is NOT ready for a response may be ignored. // // With this in mind, we replace the cancelable alert dialog with // a progress dialog, displayed until we receive a request from // the the network. For more information, please see the comments // in the displayMMIComplete() method below. // // Anything that is NOT a USSD request is a normal MMI request, // which will bring up a toast (desribed above). // Optional code for Extended USSD running prompt if (mNwService != null) { if (DBG) log("running USSD code, displaying indeterminate progress."); // create the indeterminate progress dialog and display it. ProgressDialog pd = new ProgressDialog(context); CharSequence textmsg = ""; try { textmsg = mNwService.getMmiRunningText(); } catch (RemoteException e) { mNwService = null; textmsg = context.getText(R.string.ussdRunning); } if (DBG) log("Extended NW displayMMIInitiate (" + textmsg+ ")"); pd.setMessage(textmsg); pd.setCancelable(false); pd.setIndeterminate(true); pd.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); pd.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG); pd.show(); // trigger a 15 seconds timeout to clear this progress dialog mMmiTimeoutCbMsg = buttonCallbackMessage; try { mMmiTimeoutCbMsg.getTarget().sendMessageDelayed(buttonCallbackMessage, 15000); } catch(NullPointerException e) { mMmiTimeoutCbMsg = null; } return pd; } boolean isCancelable = (mmiCode != null) && mmiCode.isCancelable(); if (!isCancelable) { if (DBG) log("not a USSD code, displaying status toast."); CharSequence text = context.getText(R.string.mmiStarted); Toast.makeText(context, text, Toast.LENGTH_SHORT) .show(); return null; } else { if (DBG) log("running USSD code, displaying indeterminate progress."); // create the indeterminate progress dialog and display it. ProgressDialog pd = new ProgressDialog(context); pd.setMessage(context.getText(R.string.ussdRunning)); pd.setCancelable(false); pd.setIndeterminate(true); pd.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); pd.show(); return pd; } } /** * Handle the MMIComplete message and fire off an intent to display * the message. * * @param context context to get strings. * @param mmiCode MMI result. * @param previousAlert a previous alert used in this activity. */ static void displayMMIComplete(final Phone phone, Context context, final MmiCode mmiCode, Message dismissCallbackMessage, AlertDialog previousAlert) { final PhoneApp app = PhoneApp.getInstance(); CharSequence text; int title = 0; // title for the progress dialog, if needed. MmiCode.State state = mmiCode.getState(); if (DBG) log("displayMMIComplete: state=" + state); // Clear timeout trigger message if(mMmiTimeoutCbMsg != null) { try{ mMmiTimeoutCbMsg.getTarget().removeMessages(mMmiTimeoutCbMsg.what); if (DBG) log("Extended NW displayMMIComplete removeMsg"); } catch (NullPointerException e) { } mMmiTimeoutCbMsg = null; } switch (state) { case PENDING: // USSD code asking for feedback from user. text = mmiCode.getMessage(); if (DBG) log("- using text from PENDING MMI message: '" + text + "'"); break; case CANCELLED: text = context.getText(R.string.mmiCancelled); break; case COMPLETE: if (app.getPUKEntryActivity() != null) { // if an attempt to unPUK the device was made, we specify // the title and the message here. title = com.android.internal.R.string.PinMmi; text = context.getText(R.string.puk_unlocked); break; } // All other conditions for the COMPLETE mmi state will cause // the case to fall through to message logic in common with // the FAILED case. case FAILED: text = mmiCode.getMessage(); if (DBG) log("- using text from MMI message: '" + text + "'"); break; default: throw new IllegalStateException("Unexpected MmiCode state: " + state); } if (previousAlert != null) { previousAlert.dismiss(); } // Check to see if a UI exists for the PUK activation. If it does // exist, then it indicates that we're trying to unblock the PUK. if ((app.getPUKEntryActivity() != null) && (state == MmiCode.State.COMPLETE)) { if (DBG) log("displaying PUK unblocking progress dialog."); // create the progress dialog, make sure the flags and type are // set correctly. ProgressDialog pd = new ProgressDialog(app); pd.setTitle(title); pd.setMessage(text); pd.setCancelable(false); pd.setIndeterminate(true); pd.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG); pd.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); // display the dialog pd.show(); // indicate to the Phone app that the progress dialog has // been assigned for the PUK unlock / SIM READY process. app.setPukEntryProgressDialog(pd); } else { // In case of failure to unlock, we'll need to reset the // PUK unlock activity, so that the user may try again. if (app.getPUKEntryActivity() != null) { app.setPukEntryActivity(null); } // A USSD in a pending state means that it is still // interacting with the user. if (state != MmiCode.State.PENDING) { if (DBG) log("MMI code has finished running."); // Replace response message with Extended Mmi wording if (mNwService != null) { try { text = mNwService.getUserMessage(text); } catch (RemoteException e) { mNwService = null; } if (DBG) log("Extended NW displayMMIInitiate (" + text + ")"); if (text == null || text.length() == 0) return; } // displaying system alert dialog on the screen instead of // using another activity to display the message. This // places the message at the forefront of the UI. AlertDialog newDialog = new AlertDialog.Builder(context) .setMessage(text) .setPositiveButton(R.string.ok, null) .setCancelable(true) .create(); newDialog.getWindow().setType( WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG); newDialog.getWindow().addFlags( WindowManager.LayoutParams.FLAG_DIM_BEHIND); newDialog.show(); } else { if (DBG) log("USSD code has requested user input. Constructing input dialog."); // USSD MMI code that is interacting with the user. The // basic set of steps is this: // 1. User enters a USSD request // 2. We recognize the request and displayMMIInitiate // (above) creates a progress dialog. // 3. Request returns and we get a PENDING or COMPLETE // message. // 4. These MMI messages are caught in the PhoneApp // (onMMIComplete) and the InCallScreen // (mHandler.handleMessage) which bring up this dialog // and closes the original progress dialog, // respectively. // 5. If the message is anything other than PENDING, // we are done, and the alert dialog (directly above) // displays the outcome. // 6. If the network is requesting more information from // the user, the MMI will be in a PENDING state, and // we display this dialog with the message. // 7. User input, or cancel requests result in a return // to step 1. Keep in mind that this is the only // time that a USSD should be canceled. // inflate the layout with the scrolling text area for the dialog. LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE); View dialogView = inflater.inflate(R.layout.dialog_ussd_response, null); // get the input field. final EditText inputText = (EditText) dialogView.findViewById(R.id.input_field); // specify the dialog's click listener, with SEND and CANCEL logic. final DialogInterface.OnClickListener mUSSDDialogListener = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { switch (whichButton) { case DialogInterface.BUTTON_POSITIVE: phone.sendUssdResponse(inputText.getText().toString()); break; case DialogInterface.BUTTON_NEGATIVE: if (mmiCode.isCancelable()) { mmiCode.cancel(); } break; } } }; // build the dialog final AlertDialog newDialog = new AlertDialog.Builder(context) .setMessage(text) .setView(dialogView) .setPositiveButton(R.string.send_button, mUSSDDialogListener) .setNegativeButton(R.string.cancel, mUSSDDialogListener) .setCancelable(false) .create(); // attach the key listener to the dialog's input field and make // sure focus is set. final View.OnKeyListener mUSSDDialogInputListener = new View.OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_CALL: case KeyEvent.KEYCODE_ENTER: if(event.getAction() == KeyEvent.ACTION_DOWN) { phone.sendUssdResponse(inputText.getText().toString()); newDialog.dismiss(); } return true; } return false; } }; inputText.setOnKeyListener(mUSSDDialogInputListener); inputText.requestFocus(); // set the window properties of the dialog newDialog.getWindow().setType( WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG); newDialog.getWindow().addFlags( WindowManager.LayoutParams.FLAG_DIM_BEHIND); // now show the dialog! newDialog.show(); } } } /** * Cancels the current pending MMI operation, if applicable. * @return true if we canceled an MMI operation, or false * if the current pending MMI wasn't cancelable * or if there was no current pending MMI at all. * * @see displayMMIInitiate */ static boolean cancelMmiCode(Phone phone) { List<? extends MmiCode> pendingMmis = phone.getPendingMmiCodes(); int count = pendingMmis.size(); if (DBG) log("cancelMmiCode: num pending MMIs = " + count); boolean canceled = false; if (count > 0) { // assume that we only have one pending MMI operation active at a time. // I don't think it's possible to enter multiple MMI codes concurrently // in the phone UI, because during the MMI operation, an Alert panel // is displayed, which prevents more MMI code from being entered. MmiCode mmiCode = pendingMmis.get(0); if (mmiCode.isCancelable()) { mmiCode.cancel(); canceled = true; } } //clear timeout message and pre-set MMI command if (mNwService != null) { try { mNwService.clearMmiString(); } catch (RemoteException e) { mNwService = null; } } if (mMmiTimeoutCbMsg != null) { mMmiTimeoutCbMsg = null; } return canceled; } public static class VoiceMailNumberMissingException extends Exception { VoiceMailNumberMissingException() { super(); } VoiceMailNumberMissingException(String msg) { super(msg); } } /** * Gets the phone number to be called from an intent. Requires a Context * to access the contacts database, and a Phone to access the voicemail * number. * * <p>If <code>phone</code> is <code>null</code>, the function will return * <code>null</code> for <code>voicemail:</code> URIs; * if <code>context</code> is <code>null</code>, the function will return * <code>null</code> for person/phone URIs.</p> * * <p>If the intent contains a <code>sip:</code> URI, the returned * "number" is actually the SIP address. * * @param context a context to use (or * @param intent the intent * * @throws VoiceMailNumberMissingException if <code>intent</code> contains * a <code>voicemail:</code> URI, but <code>phone</code> does not * have a voicemail number set. * * @return the phone number (or SIP address) that would be called by the intent, * or <code>null</code> if the number cannot be found. */ static String getNumberFromIntent(Context context, Intent intent) throws VoiceMailNumberMissingException { Uri uri = intent.getData(); String scheme = uri.getScheme(); // The sip: scheme is simple: just treat the rest of the URI as a // SIP address. if (Constants.SCHEME_SIP.equals(scheme)) { return uri.getSchemeSpecificPart(); } // Otherwise, let PhoneNumberUtils.getNumberFromIntent() handle // the other cases (i.e. tel: and voicemail: and contact: URIs.) final String number = PhoneNumberUtils.getNumberFromIntent(intent, context); // Check for a voicemail-dialing request. If the voicemail number is // empty, throw a VoiceMailNumberMissingException. if (Constants.SCHEME_VOICEMAIL.equals(scheme) && (number == null || TextUtils.isEmpty(number))) throw new VoiceMailNumberMissingException(); return number; } /** * Returns the caller-id info corresponding to the specified Connection. * (This is just a simple wrapper around CallerInfo.getCallerInfo(): we * extract a phone number from the specified Connection, and feed that * number into CallerInfo.getCallerInfo().) * * The returned CallerInfo may be null in certain error cases, like if the * specified Connection was null, or if we weren't able to get a valid * phone number from the Connection. * * Finally, if the getCallerInfo() call did succeed, we save the resulting * CallerInfo object in the "userData" field of the Connection. * * NOTE: This API should be avoided, with preference given to the * asynchronous startGetCallerInfo API. */ static CallerInfo getCallerInfo(Context context, Connection c) { CallerInfo info = null; if (c != null) { //See if there is a URI attached. If there is, this means //that there is no CallerInfo queried yet, so we'll need to //replace the URI with a full CallerInfo object. Object userDataObject = c.getUserData(); if (userDataObject instanceof Uri) { info = CallerInfo.getCallerInfo(context, (Uri) userDataObject); if (info != null) { c.setUserData(info); } } else { if (userDataObject instanceof CallerInfoToken) { //temporary result, while query is running info = ((CallerInfoToken) userDataObject).currentInfo; } else { //final query result info = (CallerInfo) userDataObject; } if (info == null) { // No URI, or Existing CallerInfo, so we'll have to make do with // querying a new CallerInfo using the connection's phone number. String number = c.getAddress(); if (DBG) log("getCallerInfo: number = " + number); if (!TextUtils.isEmpty(number)) { info = CallerInfo.getCallerInfo(context, number); if (info != null) { c.setUserData(info); } } } } } return info; } /** * Class returned by the startGetCallerInfo call to package a temporary * CallerInfo Object, to be superceded by the CallerInfo Object passed * into the listener when the query with token mAsyncQueryToken is complete. */ public static class CallerInfoToken { /**indicates that there will no longer be updates to this request.*/ public boolean isFinal; public CallerInfo currentInfo; public CallerInfoAsyncQuery asyncQuery; } /** * Start a CallerInfo Query based on the earliest connection in the call. */ static CallerInfoToken startGetCallerInfo(Context context, Call call, CallerInfoAsyncQuery.OnQueryCompleteListener listener, Object cookie) { Connection conn = null; int phoneType = call.getPhone().getPhoneType(); if (phoneType == Phone.PHONE_TYPE_CDMA) { conn = call.getLatestConnection(); } else if ((phoneType == Phone.PHONE_TYPE_GSM) || (phoneType == Phone.PHONE_TYPE_SIP)) { conn = call.getEarliestConnection(); } else { throw new IllegalStateException("Unexpected phone type: " + phoneType); } return startGetCallerInfo(context, conn, listener, cookie); } /** * place a temporary callerinfo object in the hands of the caller and notify * caller when the actual query is done. */ static CallerInfoToken startGetCallerInfo(Context context, Connection c, CallerInfoAsyncQuery.OnQueryCompleteListener listener, Object cookie) { CallerInfoToken cit; if (c == null) { //TODO: perhaps throw an exception here. cit = new CallerInfoToken(); cit.asyncQuery = null; return cit; } Object userDataObject = c.getUserData(); // There are now 3 states for the Connection's userData object: // // (1) Uri - query has not been executed yet // // (2) CallerInfoToken - query is executing, but has not completed. // // (3) CallerInfo - query has executed. // // In each case we have slightly different behaviour: // 1. If the query has not been executed yet (Uri or null), we start // query execution asynchronously, and note it by attaching a // CallerInfoToken as the userData. // 2. If the query is executing (CallerInfoToken), we've essentially // reached a state where we've received multiple requests for the // same callerInfo. That means that once the query is complete, // we'll need to execute the additional listener requested. // 3. If the query has already been executed (CallerInfo), we just // return the CallerInfo object as expected. // 4. Regarding isFinal - there are cases where the CallerInfo object // will not be attached, like when the number is empty (caller id // blocking). This flag is used to indicate that the // CallerInfoToken object is going to be permanent since no // query results will be returned. In the case where a query // has been completed, this flag is used to indicate to the caller // that the data will not be updated since it is valid. // // Note: For the case where a number is NOT retrievable, we leave // the CallerInfo as null in the CallerInfoToken. This is // something of a departure from the original code, since the old // code manufactured a CallerInfo object regardless of the query // outcome. From now on, we will append an empty CallerInfo // object, to mirror previous behaviour, and to avoid Null Pointer // Exceptions. if (userDataObject instanceof Uri) { // State (1): query has not been executed yet //create a dummy callerinfo, populate with what we know from URI. cit = new CallerInfoToken(); cit.currentInfo = new CallerInfo(); cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context, (Uri) userDataObject, sCallerInfoQueryListener, c); cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie); cit.isFinal = false; c.setUserData(cit); if (DBG) log("startGetCallerInfo: query based on Uri: " + userDataObject); } else if (userDataObject == null) { // No URI, or Existing CallerInfo, so we'll have to make do with // querying a new CallerInfo using the connection's phone number. String number = c.getAddress(); if (DBG) { log("PhoneUtils.startGetCallerInfo: new query for phone number..."); log("- number (address): " + number); log("- c: " + c); log("- phone: " + c.getCall().getPhone()); int phoneType = c.getCall().getPhone().getPhoneType(); log("- phoneType: " + phoneType); switch (phoneType) { case Phone.PHONE_TYPE_NONE: log(" ==> PHONE_TYPE_NONE"); break; case Phone.PHONE_TYPE_GSM: log(" ==> PHONE_TYPE_GSM"); break; case Phone.PHONE_TYPE_CDMA: log(" ==> PHONE_TYPE_CDMA"); break; case Phone.PHONE_TYPE_SIP: log(" ==> PHONE_TYPE_SIP"); break; default: log(" ==> Unknown phone type"); break; } } cit = new CallerInfoToken(); cit.currentInfo = new CallerInfo(); // Store CNAP information retrieved from the Connection (we want to do this // here regardless of whether the number is empty or not). cit.currentInfo.cnapName = c.getCnapName(); cit.currentInfo.name = cit.currentInfo.cnapName; // This can still get overwritten // by ContactInfo later cit.currentInfo.numberPresentation = c.getNumberPresentation(); cit.currentInfo.namePresentation = c.getCnapNamePresentation(); if (DBG) { log("startGetCallerInfo: number = " + number); log("startGetCallerInfo: CNAP Info from FW(1): name=" + cit.currentInfo.cnapName + ", Name/Number Pres=" + cit.currentInfo.numberPresentation); } // handling case where number is null (caller id hidden) as well. if (!TextUtils.isEmpty(number)) { // Check for special CNAP cases and modify the CallerInfo accordingly // to be sure we keep the right information to display/log later number = modifyForSpecialCnapCases(context, cit.currentInfo, number, cit.currentInfo.numberPresentation); cit.currentInfo.phoneNumber = number; // For scenarios where we may receive a valid number from the network but a // restricted/unavailable presentation, we do not want to perform a contact query // (see note on isFinal above). So we set isFinal to true here as well. if (cit.currentInfo.numberPresentation != Connection.PRESENTATION_ALLOWED) { cit.isFinal = true; } else { if (DBG) log("==> Actually starting CallerInfoAsyncQuery.startQuery()..."); cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context, number, sCallerInfoQueryListener, c); cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie); cit.isFinal = false; } } else { // This is the case where we are querying on a number that // is null or empty, like a caller whose caller id is // blocked or empty (CLIR). The previous behaviour was to // throw a null CallerInfo object back to the user, but // this departure is somewhat cleaner. if (DBG) log("startGetCallerInfo: No query to start, send trivial reply."); cit.isFinal = true; // please see note on isFinal, above. } c.setUserData(cit); if (DBG) log("startGetCallerInfo: query based on number: " + number); } else if (userDataObject instanceof CallerInfoToken) { // State (2): query is executing, but has not completed. // just tack on this listener to the queue. cit = (CallerInfoToken) userDataObject; // handling case where number is null (caller id hidden) as well. if (cit.asyncQuery != null) { cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie); if (DBG) log("startGetCallerInfo: query already running, adding listener: " + listener.getClass().toString()); } else { // handling case where number/name gets updated later on by the network String updatedNumber = c.getAddress(); if (DBG) log("startGetCallerInfo: updatedNumber initially = " + updatedNumber); if (!TextUtils.isEmpty(updatedNumber)) { // Store CNAP information retrieved from the Connection cit.currentInfo.cnapName = c.getCnapName(); // This can still get overwritten by ContactInfo cit.currentInfo.name = cit.currentInfo.cnapName; cit.currentInfo.numberPresentation = c.getNumberPresentation(); cit.currentInfo.namePresentation = c.getCnapNamePresentation(); updatedNumber = modifyForSpecialCnapCases(context, cit.currentInfo, updatedNumber, cit.currentInfo.numberPresentation); cit.currentInfo.phoneNumber = updatedNumber; if (DBG) log("startGetCallerInfo: updatedNumber=" + updatedNumber); if (DBG) log("startGetCallerInfo: CNAP Info from FW(2): name=" + cit.currentInfo.cnapName + ", Name/Number Pres=" + cit.currentInfo.numberPresentation); // For scenarios where we may receive a valid number from the network but a // restricted/unavailable presentation, we do not want to perform a contact query // (see note on isFinal above). So we set isFinal to true here as well. if (cit.currentInfo.numberPresentation != Connection.PRESENTATION_ALLOWED) { cit.isFinal = true; } else { cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context, updatedNumber, sCallerInfoQueryListener, c); cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie); cit.isFinal = false; } } else { if (DBG) log("startGetCallerInfo: No query to attach to, send trivial reply."); if (cit.currentInfo == null) { cit.currentInfo = new CallerInfo(); } // Store CNAP information retrieved from the Connection cit.currentInfo.cnapName = c.getCnapName(); // This can still get // overwritten by ContactInfo cit.currentInfo.name = cit.currentInfo.cnapName; cit.currentInfo.numberPresentation = c.getNumberPresentation(); cit.currentInfo.namePresentation = c.getCnapNamePresentation(); if (DBG) log("startGetCallerInfo: CNAP Info from FW(3): name=" + cit.currentInfo.cnapName + ", Name/Number Pres=" + cit.currentInfo.numberPresentation); cit.isFinal = true; // please see note on isFinal, above. } } } else { // State (3): query is complete. // The connection's userDataObject is a full-fledged // CallerInfo instance. Wrap it in a CallerInfoToken and // return it to the user. cit = new CallerInfoToken(); cit.currentInfo = (CallerInfo) userDataObject; cit.asyncQuery = null; cit.isFinal = true; // since the query is already done, call the listener. if (DBG) log("startGetCallerInfo: query already done, returning CallerInfo"); if (DBG) log("==> cit.currentInfo = " + cit.currentInfo); } return cit; } /** * Static CallerInfoAsyncQuery.OnQueryCompleteListener instance that * we use with all our CallerInfoAsyncQuery.startQuery() requests. */ private static final int QUERY_TOKEN = -1; static CallerInfoAsyncQuery.OnQueryCompleteListener sCallerInfoQueryListener = new CallerInfoAsyncQuery.OnQueryCompleteListener () { /** * When the query completes, we stash the resulting CallerInfo * object away in the Connection's "userData" (where it will * later be retrieved by the in-call UI.) */ public void onQueryComplete(int token, Object cookie, CallerInfo ci) { if (DBG) log("query complete, updating connection.userdata"); Connection conn = (Connection) cookie; // Added a check if CallerInfo is coming from ContactInfo or from Connection. // If no ContactInfo, then we want to use CNAP information coming from network if (DBG) log("- onQueryComplete: CallerInfo:" + ci); if (ci.contactExists || ci.isEmergencyNumber() || ci.isVoiceMailNumber()) { // If the number presentation has not been set by // the ContactInfo, use the one from the // connection. // TODO: Need a new util method to merge the info // from the Connection in a CallerInfo object. // Here 'ci' is a new CallerInfo instance read // from the DB. It has lost all the connection // info preset before the query (see PhoneUtils // line 1334). We should have a method to merge // back into this new instance the info from the // connection object not set by the DB. If the // Connection already has a CallerInfo instance in // userData, then we could use this instance to // fill 'ci' in. The same routine could be used in // PhoneUtils. if (0 == ci.numberPresentation) { ci.numberPresentation = conn.getNumberPresentation(); } } else { // No matching contact was found for this number. // Return a new CallerInfo based solely on the CNAP // information from the network. CallerInfo newCi = getCallerInfo(null, conn); // ...but copy over the (few) things we care about // from the original CallerInfo object: if (newCi != null) { newCi.phoneNumber = ci.phoneNumber; // To get formatted phone number newCi.geoDescription = ci.geoDescription; // To get geo description string ci = newCi; } } if (DBG) log("==> Stashing CallerInfo " + ci + " into the connection..."); conn.setUserData(ci); } }; /** * Returns a single "name" for the specified given a CallerInfo object. * If the name is null, return defaultString as the default value, usually * context.getString(R.string.unknown). */ static String getCompactNameFromCallerInfo(CallerInfo ci, Context context) { if (DBG) log("getCompactNameFromCallerInfo: info = " + ci); String compactName = null; if (ci != null) { if (TextUtils.isEmpty(ci.name)) { // Perform any modifications for special CNAP cases to // the phone number being displayed, if applicable. compactName = modifyForSpecialCnapCases(context, ci, ci.phoneNumber, ci.numberPresentation); } else { // Don't call modifyForSpecialCnapCases on regular name. See b/2160795. compactName = ci.name; } } if ((compactName == null) || (TextUtils.isEmpty(compactName))) { // If we're still null/empty here, then check if we have a presentation // string that takes precedence that we could return, otherwise display // "unknown" string. if (ci != null && ci.numberPresentation == Connection.PRESENTATION_RESTRICTED) { compactName = context.getString(R.string.private_num); } else if (ci != null && ci.numberPresentation == Connection.PRESENTATION_PAYPHONE) { compactName = context.getString(R.string.payphone); } else { compactName = context.getString(R.string.unknown); } } if (DBG) log("getCompactNameFromCallerInfo: compactName=" + compactName); return compactName; } /** * Returns true if the specified Call is a "conference call", meaning * that it owns more than one Connection object. This information is * used to trigger certain UI changes that appear when a conference * call is active (like displaying the label "Conference call", and * enabling the "Manage conference" UI.) * * Watch out: This method simply checks the number of Connections, * *not* their states. So if a Call has (for example) one ACTIVE * connection and one DISCONNECTED connection, this method will return * true (which is unintuitive, since the Call isn't *really* a * conference call any more.) * * @return true if the specified call has more than one connection (in any state.) */ static boolean isConferenceCall(Call call) { // CDMA phones don't have the same concept of "conference call" as // GSM phones do; there's no special "conference call" state of // the UI or a "manage conference" function. (Instead, when // you're in a 3-way call, all we can do is display the "generic" // state of the UI.) So as far as the in-call UI is concerned, // Conference corresponds to generic display. final PhoneApp app = PhoneApp.getInstance(); int phoneType = call.getPhone().getPhoneType(); if (phoneType == Phone.PHONE_TYPE_CDMA) { CdmaPhoneCallState.PhoneCallState state = app.cdmaPhoneCallState.getCurrentCallState(); if ((state == CdmaPhoneCallState.PhoneCallState.CONF_CALL) || ((state == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE) && !app.cdmaPhoneCallState.IsThreeWayCallOrigStateDialing())) { return true; } } else { List<Connection> connections = call.getConnections(); if (connections != null && connections.size() > 1) { return true; } } return false; // TODO: We may still want to change the semantics of this method // to say that a given call is only really a conference call if // the number of ACTIVE connections, not the total number of // connections, is greater than one. (See warning comment in the // javadoc above.) // Here's an implementation of that: // if (connections == null) { // return false; // } // int numActiveConnections = 0; // for (Connection conn : connections) { // if (DBG) log(" - CONN: " + conn + ", state = " + conn.getState()); // if (conn.getState() == Call.State.ACTIVE) numActiveConnections++; // if (numActiveConnections > 1) { // return true; // } // } // return false; } /** * Launch the Dialer to start a new call. * This is just a wrapper around the ACTION_DIAL intent. */ static void startNewCall(final CallManager cm) { final PhoneApp app = PhoneApp.getInstance(); // Sanity-check that this is OK given the current state of the phone. if (!okToAddCall(cm)) { Log.w(LOG_TAG, "startNewCall: can't add a new call in the current state"); dumpCallManager(); return; } // if applicable, mute the call while we're showing the add call UI. if (cm.hasActiveFgCall()) { setMuteInternal(cm.getActiveFgCall().getPhone(), true); // Inform the phone app that this mute state was NOT done // voluntarily by the User. app.setRestoreMuteOnInCallResume(true); } Intent intent = new Intent(Intent.ACTION_DIAL); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // when we request the dialer come up, we also want to inform // it that we're going through the "add call" option from the // InCallScreen / PhoneUtils. intent.putExtra(ADD_CALL_MODE_KEY, true); app.startActivity(intent); } static void turnOnSpeaker(Context context, boolean flag, boolean store) { if (DBG) log("turnOnSpeaker(flag=" + flag + ", store=" + store + ")..."); final PhoneApp app = PhoneApp.getInstance(); AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); audioManager.setSpeakerphoneOn(flag); // record the speaker-enable value if (store) { sIsSpeakerEnabled = flag; } // Update the status bar icon app.notificationMgr.updateSpeakerNotification(flag); // We also need to make a fresh call to PhoneApp.updateWakeState() // any time the speaker state changes, since the screen timeout is // sometimes different depending on whether or not the speaker is // in use. app.updateWakeState(); // Update the Proximity sensor based on speaker state app.updateProximitySensorMode(app.mCM.getState()); app.mCM.setEchoSuppressionEnabled(flag); } /** * Restore the speaker mode, called after a wired headset disconnect * event. */ static void restoreSpeakerMode(Context context) { if (DBG) log("restoreSpeakerMode, restoring to: " + sIsSpeakerEnabled); // change the mode if needed. if (isSpeakerOn(context) != sIsSpeakerEnabled) { turnOnSpeaker(context, sIsSpeakerEnabled, false); } } static boolean isSpeakerOn(Context context) { AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); return audioManager.isSpeakerphoneOn(); } static void turnOnNoiseSuppression(Context context, boolean flag, boolean store) { if (DBG) log("turnOnNoiseSuppression: " + flag); AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); if (!context.getResources().getBoolean(R.bool.has_in_call_noise_suppression)) { return; } if (flag) { audioManager.setParameters("noise_suppression=auto"); } else { audioManager.setParameters("noise_suppression=off"); } // record the speaker-enable value if (store) { sIsNoiseSuppressionEnabled = flag; } // TODO: implement and manage ICON } static void restoreNoiseSuppression(Context context) { if (DBG) log("restoreNoiseSuppression, restoring to: " + sIsNoiseSuppressionEnabled); if (!context.getResources().getBoolean(R.bool.has_in_call_noise_suppression)) { return; } // change the mode if needed. if (isNoiseSuppressionOn(context) != sIsNoiseSuppressionEnabled) { turnOnNoiseSuppression(context, sIsNoiseSuppressionEnabled, false); } } static boolean isNoiseSuppressionOn(Context context) { if (!context.getResources().getBoolean(R.bool.has_in_call_noise_suppression)) { return false; } AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); String noiseSuppression = audioManager.getParameters("noise_suppression"); if (DBG) log("isNoiseSuppressionOn: " + noiseSuppression); if (noiseSuppression.contains("off")) { return false; } else { return true; } } /** * * Mute / umute the foreground phone, which has the current foreground call * * All muting / unmuting from the in-call UI should go through this * wrapper. * * Wrapper around Phone.setMute() and setMicrophoneMute(). * It also updates the connectionMuteTable and mute icon in the status bar. * */ static void setMute(boolean muted) { CallManager cm = PhoneApp.getInstance().mCM; // make the call to mute the audio setMuteInternal(cm.getFgPhone(), muted); // update the foreground connections to match. This includes // all the connections on conference calls. for (Connection cn : cm.getActiveFgCall().getConnections()) { if (sConnectionMuteTable.get(cn) == null) { if (DBG) log("problem retrieving mute value for this connection."); } sConnectionMuteTable.put(cn, Boolean.valueOf(muted)); } } /** * Internally used muting function. */ private static void setMuteInternal(Phone phone, boolean muted) { final PhoneApp app = PhoneApp.getInstance(); Context context = phone.getContext(); boolean routeToAudioManager = context.getResources().getBoolean(R.bool.send_mic_mute_to_AudioManager); if (routeToAudioManager) { AudioManager audioManager = (AudioManager) phone.getContext().getSystemService(Context.AUDIO_SERVICE); if (DBG) log("setMuteInternal: using setMicrophoneMute(" + muted + ")..."); audioManager.setMicrophoneMute(muted); } else { if (DBG) log("setMuteInternal: using phone.setMute(" + muted + ")..."); phone.setMute(muted); } app.notificationMgr.updateMuteNotification(); } /** * Get the mute state of foreground phone, which has the current * foreground call */ static boolean getMute() { final PhoneApp app = PhoneApp.getInstance(); boolean routeToAudioManager = app.getResources().getBoolean(R.bool.send_mic_mute_to_AudioManager); if (routeToAudioManager) { AudioManager audioManager = (AudioManager) app.getSystemService(Context.AUDIO_SERVICE); return audioManager.isMicrophoneMute(); } else { return app.mCM.getMute(); } } /* package */ static void setAudioMode() { setAudioMode(PhoneApp.getInstance().mCM); } /** * Sets the audio mode per current phone state. */ /* package */ static void setAudioMode(CallManager cm) { if (DBG) Log.d(LOG_TAG, "setAudioMode()..." + cm.getState()); Context context = PhoneApp.getInstance(); AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); int modeBefore = audioManager.getMode(); cm.setAudioMode(); int modeAfter = audioManager.getMode(); if (modeBefore != modeAfter) { // Enable stack dump only when actively debugging ("new Throwable()" is expensive!) if (DBG_SETAUDIOMODE_STACK) Log.d(LOG_TAG, "Stack:", new Throwable("stack dump")); } else { if (DBG) Log.d(LOG_TAG, "setAudioMode() no change: " + audioModeToString(modeBefore)); } } private static String audioModeToString(int mode) { switch (mode) { case AudioManager.MODE_INVALID: return "MODE_INVALID"; case AudioManager.MODE_CURRENT: return "MODE_CURRENT"; case AudioManager.MODE_NORMAL: return "MODE_NORMAL"; case AudioManager.MODE_RINGTONE: return "MODE_RINGTONE"; case AudioManager.MODE_IN_CALL: return "MODE_IN_CALL"; default: return String.valueOf(mode); } } /** * Handles the wired headset button while in-call. * * This is called from the PhoneApp, not from the InCallScreen, * since the HEADSETHOOK button means "mute or unmute the current * call" *any* time a call is active, even if the user isn't actually * on the in-call screen. * * @return true if we consumed the event. */ /* package */ static boolean handleHeadsetHook(Phone phone, KeyEvent event) { if (DBG) log("handleHeadsetHook()..." + event.getAction() + " " + event.getRepeatCount()); final PhoneApp app = PhoneApp.getInstance(); // If the phone is totally idle, we ignore HEADSETHOOK events // (and instead let them fall through to the media player.) if (phone.getState() == Phone.State.IDLE) { return false; } // Ok, the phone is in use. // The headset button button means "Answer" if an incoming call is // ringing. If not, it toggles the mute / unmute state. // // And in any case we *always* consume this event; this means // that the usual mediaplayer-related behavior of the headset // button will NEVER happen while the user is on a call. final boolean hasRingingCall = !phone.getRingingCall().isIdle(); final boolean hasActiveCall = !phone.getForegroundCall().isIdle(); final boolean hasHoldingCall = !phone.getBackgroundCall().isIdle(); if (hasRingingCall && event.getRepeatCount() == 0 && event.getAction() == KeyEvent.ACTION_UP) { // If an incoming call is ringing, answer it (just like with the // CALL button): int phoneType = phone.getPhoneType(); if (phoneType == Phone.PHONE_TYPE_CDMA) { answerCall(phone.getRingingCall()); } else if ((phoneType == Phone.PHONE_TYPE_GSM) || (phoneType == Phone.PHONE_TYPE_SIP)) { if (hasActiveCall && hasHoldingCall) { if (DBG) log("handleHeadsetHook: ringing (both lines in use) ==> answer!"); answerAndEndActive(app.mCM, phone.getRingingCall()); } else { if (DBG) log("handleHeadsetHook: ringing ==> answer!"); // answerCall() will automatically hold the current // active call, if there is one. answerCall(phone.getRingingCall()); } } else { throw new IllegalStateException("Unexpected phone type: " + phoneType); } } else { // No incoming ringing call. if (event.isLongPress()) { if (DBG) log("handleHeadsetHook: longpress -> hangup"); hangup(app.mCM); } else if (event.getAction() == KeyEvent.ACTION_UP && event.getRepeatCount() == 0) { Connection c = phone.getForegroundCall().getLatestConnection(); // If it is NOT an emg #, toggle the mute state. Otherwise, ignore the hook. if (c != null && !PhoneNumberUtils.isLocalEmergencyNumber(c.getAddress(), PhoneApp.getInstance())) { if (getMute()) { if (DBG) log("handleHeadsetHook: UNmuting..."); setMute(false); } else { if (DBG) log("handleHeadsetHook: muting..."); setMute(true); } } } } // Even if the InCallScreen is the current activity, there's no // need to force it to update, because (1) if we answered a // ringing call, the InCallScreen will imminently get a phone // state change event (causing an update), and (2) if we muted or // unmuted, the setMute() call automagically updates the status // bar, and there's no "mute" indication in the InCallScreen // itself (other than the menu item, which only ever stays // onscreen for a second anyway.) // TODO: (2) isn't entirely true anymore. Once we return our result // to the PhoneApp, we ask InCallScreen to update its control widgets // in case we changed mute or speaker state and phones with touch- // screen [toggle] buttons need to update themselves. return true; } /** * Look for ANY connections on the phone that qualify as being * disconnected. * * @return true if we find a connection that is disconnected over * all the phone's call objects. */ /* package */ static boolean hasDisconnectedConnections(Phone phone) { return hasDisconnectedConnections(phone.getForegroundCall()) || hasDisconnectedConnections(phone.getBackgroundCall()) || hasDisconnectedConnections(phone.getRingingCall()); } /** * Iterate over all connections in a call to see if there are any * that are not alive (disconnected or idle). * * @return true if we find a connection that is disconnected, and * pending removal via * {@link com.android.internal.telephony.gsm.GsmCall#clearDisconnected()}. */ private static final boolean hasDisconnectedConnections(Call call) { // look through all connections for non-active ones. for (Connection c : call.getConnections()) { if (!c.isAlive()) { return true; } } return false; } // // Misc UI policy helper functions // /** * @return true if we're allowed to swap calls, given the current * state of the Phone. */ /* package */ static boolean okToSwapCalls(CallManager cm) { int phoneType = cm.getDefaultPhone().getPhoneType(); if (phoneType == Phone.PHONE_TYPE_CDMA) { // CDMA: "Swap" is enabled only when the phone reaches a *generic*. // state by either accepting a Call Waiting or by merging two calls PhoneApp app = PhoneApp.getInstance(); return (app.cdmaPhoneCallState.getCurrentCallState() == CdmaPhoneCallState.PhoneCallState.CONF_CALL); } else if ((phoneType == Phone.PHONE_TYPE_GSM) || (phoneType == Phone.PHONE_TYPE_SIP)) { // GSM: "Swap" is available if both lines are in use and there's no // incoming call. (Actually we need to verify that the active // call really is in the ACTIVE state and the holding call really // is in the HOLDING state, since you *can't* actually swap calls // when the foreground call is DIALING or ALERTING.) return !cm.hasActiveRingingCall() && (cm.getActiveFgCall().getState() == Call.State.ACTIVE) && (cm.getFirstActiveBgCall().getState() == Call.State.HOLDING); } else { throw new IllegalStateException("Unexpected phone type: " + phoneType); } } /** * @return true if we're allowed to merge calls, given the current * state of the Phone. */ /* package */ static boolean okToMergeCalls(CallManager cm) { int phoneType = cm.getFgPhone().getPhoneType(); if (phoneType == Phone.PHONE_TYPE_CDMA) { // CDMA: "Merge" is enabled only when the user is in a 3Way call. PhoneApp app = PhoneApp.getInstance(); return ((app.cdmaPhoneCallState.getCurrentCallState() == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE) && !app.cdmaPhoneCallState.IsThreeWayCallOrigStateDialing()); } else { // GSM: "Merge" is available if both lines are in use and there's no // incoming call, *and* the current conference isn't already // "full". // TODO: shall move all okToMerge logic to CallManager return !cm.hasActiveRingingCall() && cm.hasActiveFgCall() && cm.hasActiveBgCall() && cm.canConference(cm.getFirstActiveBgCall()); } } /** * @return true if the UI should let you add a new call, given the current * state of the Phone. */ /* package */ static boolean okToAddCall(CallManager cm) { Phone phone = cm.getActiveFgCall().getPhone(); // "Add call" is never allowed in emergency callback mode (ECM). if (isPhoneInEcm(phone)) { return false; } int phoneType = phone.getPhoneType(); final Call.State fgCallState = cm.getActiveFgCall().getState(); if (phoneType == Phone.PHONE_TYPE_CDMA) { // CDMA: "Add call" button is only enabled when: // - ForegroundCall is in ACTIVE state // - After 30 seconds of user Ignoring/Missing a Call Waiting call. PhoneApp app = PhoneApp.getInstance(); return ((fgCallState == Call.State.ACTIVE) && (app.cdmaPhoneCallState.getAddCallMenuStateAfterCallWaiting())); } else if ((phoneType == Phone.PHONE_TYPE_GSM) || (phoneType == Phone.PHONE_TYPE_SIP)) { // GSM: "Add call" is available only if ALL of the following are true: // - There's no incoming ringing call // - There's < 2 lines in use // - The foreground call is ACTIVE or IDLE or DISCONNECTED. // (We mainly need to make sure it *isn't* DIALING or ALERTING.) final boolean hasRingingCall = cm.hasActiveRingingCall(); final boolean hasActiveCall = cm.hasActiveFgCall(); final boolean hasHoldingCall = cm.hasActiveBgCall(); final boolean allLinesTaken = hasActiveCall && hasHoldingCall; return !hasRingingCall && !allLinesTaken && ((fgCallState == Call.State.ACTIVE) || (fgCallState == Call.State.IDLE) || (fgCallState == Call.State.DISCONNECTED)); } else { throw new IllegalStateException("Unexpected phone type: " + phoneType); } } /** * Based on the input CNAP number string, * @return _RESTRICTED or _UNKNOWN for all the special CNAP strings. * Otherwise, return CNAP_SPECIAL_CASE_NO. */ private static int checkCnapSpecialCases(String n) { if (n.equals("PRIVATE") || n.equals("P") || n.equals("RES")) { if (DBG) log("checkCnapSpecialCases, PRIVATE string: " + n); return Connection.PRESENTATION_RESTRICTED; } else if (n.equals("UNAVAILABLE") || n.equals("UNKNOWN") || n.equals("UNA") || n.equals("U")) { if (DBG) log("checkCnapSpecialCases, UNKNOWN string: " + n); return Connection.PRESENTATION_UNKNOWN; } else { if (DBG) log("checkCnapSpecialCases, normal str. number: " + n); return CNAP_SPECIAL_CASE_NO; } } /** * Handles certain "corner cases" for CNAP. When we receive weird phone numbers * from the network to indicate different number presentations, convert them to * expected number and presentation values within the CallerInfo object. * @param number number we use to verify if we are in a corner case * @param presentation presentation value used to verify if we are in a corner case * @return the new String that should be used for the phone number */ /* package */ static String modifyForSpecialCnapCases(Context context, CallerInfo ci, String number, int presentation) { // Obviously we return number if ci == null, but still return number if // number == null, because in these cases the correct string will still be // displayed/logged after this function returns based on the presentation value. if (ci == null || number == null) return number; if (DBG) log("modifyForSpecialCnapCases: initially, number=" + number + ", presentation=" + presentation + " ci " + ci); // "ABSENT NUMBER" is a possible value we could get from the network as the // phone number, so if this happens, change it to "Unknown" in the CallerInfo // and fix the presentation to be the same. if (number.equals(context.getString(R.string.absent_num)) && presentation == Connection.PRESENTATION_ALLOWED) { number = context.getString(R.string.unknown); ci.numberPresentation = Connection.PRESENTATION_UNKNOWN; } // Check for other special "corner cases" for CNAP and fix them similarly. Corner // cases only apply if we received an allowed presentation from the network, so check // if we think we have an allowed presentation, or if the CallerInfo presentation doesn't // match the presentation passed in for verification (meaning we changed it previously // because it's a corner case and we're being called from a different entry point). if (ci.numberPresentation == Connection.PRESENTATION_ALLOWED || (ci.numberPresentation != presentation && presentation == Connection.PRESENTATION_ALLOWED)) { int cnapSpecialCase = checkCnapSpecialCases(number); if (cnapSpecialCase != CNAP_SPECIAL_CASE_NO) { // For all special strings, change number & numberPresentation. if (cnapSpecialCase == Connection.PRESENTATION_RESTRICTED) { number = context.getString(R.string.private_num); } else if (cnapSpecialCase == Connection.PRESENTATION_UNKNOWN) { number = context.getString(R.string.unknown); } if (DBG) log("SpecialCnap: number=" + number + "; presentation now=" + cnapSpecialCase); ci.numberPresentation = cnapSpecialCase; } } if (DBG) log("modifyForSpecialCnapCases: returning number string=" + number); return number; } // // Support for 3rd party phone service providers. // /** * Check if all the provider's info is present in the intent. * @param intent Expected to have the provider's extra. * @return true if the intent has all the extras to build the * in-call screen's provider info overlay. */ /* package */ static boolean hasPhoneProviderExtras(Intent intent) { if (null == intent) { return false; } final String name = intent.getStringExtra(InCallScreen.EXTRA_GATEWAY_PROVIDER_PACKAGE); final String gatewayUri = intent.getStringExtra(InCallScreen.EXTRA_GATEWAY_URI); return !TextUtils.isEmpty(name) && !TextUtils.isEmpty(gatewayUri); } /** * Copy all the expected extras set when a 3rd party provider is * used from the source intent to the destination one. Checks all * the required extras are present, if any is missing, none will * be copied. * @param src Intent which may contain the provider's extras. * @param dst Intent where a copy of the extras will be added if applicable. */ /* package */ static void checkAndCopyPhoneProviderExtras(Intent src, Intent dst) { if (!hasPhoneProviderExtras(src)) { Log.d(LOG_TAG, "checkAndCopyPhoneProviderExtras: some or all extras are missing."); return; } dst.putExtra(InCallScreen.EXTRA_GATEWAY_PROVIDER_PACKAGE, src.getStringExtra(InCallScreen.EXTRA_GATEWAY_PROVIDER_PACKAGE)); dst.putExtra(InCallScreen.EXTRA_GATEWAY_URI, src.getStringExtra(InCallScreen.EXTRA_GATEWAY_URI)); } /** * Get the provider's label from the intent. * @param context to lookup the provider's package name. * @param intent with an extra set to the provider's package name. * @return The provider's application label. null if an error * occurred during the lookup of the package name or the label. */ /* package */ static CharSequence getProviderLabel(Context context, Intent intent) { String packageName = intent.getStringExtra(InCallScreen.EXTRA_GATEWAY_PROVIDER_PACKAGE); PackageManager pm = context.getPackageManager(); try { ApplicationInfo info = pm.getApplicationInfo(packageName, 0); return pm.getApplicationLabel(info); } catch (PackageManager.NameNotFoundException e) { return null; } } /** * Get the provider's icon. * @param context to lookup the provider's icon. * @param intent with an extra set to the provider's package name. * @return The provider's application icon. null if an error occured during the icon lookup. */ /* package */ static Drawable getProviderIcon(Context context, Intent intent) { String packageName = intent.getStringExtra(InCallScreen.EXTRA_GATEWAY_PROVIDER_PACKAGE); PackageManager pm = context.getPackageManager(); try { return pm.getApplicationIcon(packageName); } catch (PackageManager.NameNotFoundException e) { return null; } } /** * Return the gateway uri from the intent. * @param intent With the gateway uri extra. * @return The gateway URI or null if not found. */ /* package */ static Uri getProviderGatewayUri(Intent intent) { String uri = intent.getStringExtra(InCallScreen.EXTRA_GATEWAY_URI); return TextUtils.isEmpty(uri) ? null : Uri.parse(uri); } /** * Return a formatted version of the uri's scheme specific * part. E.g for 'tel:12345678', return '1-234-5678'. * @param uri A 'tel:' URI with the gateway phone number. * @return the provider's address (from the gateway uri) formatted * for user display. null if uri was null or its scheme was not 'tel:'. */ /* package */ static String formatProviderUri(Uri uri) { if (null != uri) { if (Constants.SCHEME_TEL.equals(uri.getScheme())) { return PhoneNumberUtils.formatNumber(uri.getSchemeSpecificPart()); } else { return uri.toString(); } } return null; } /** * Check if a phone number can be route through a 3rd party * gateway. The number must be a global phone number in numerical * form (1-800-666-SEXY won't work). * * MMI codes and the like cannot be used as a dial number for the * gateway either. * * @param number To be dialed via a 3rd party gateway. * @return true If the number can be routed through the 3rd party network. */ /* package */ static boolean isRoutableViaGateway(String number) { if (TextUtils.isEmpty(number)) { return false; } number = PhoneNumberUtils.stripSeparators(number); if (!number.equals(PhoneNumberUtils.convertKeypadLettersToDigits(number))) { return false; } number = PhoneNumberUtils.extractNetworkPortion(number); return PhoneNumberUtils.isGlobalPhoneNumber(number); } /** * This function is called when phone answers or places a call. * Check if the phone is in a car dock or desk dock. * If yes, turn on the speaker, when no wired or BT headsets are connected. * Otherwise do nothing. */ private static void activateSpeakerIfDocked(Phone phone) { if (DBG) log("activateSpeakerIfDocked()..."); - if (PhoneApp.mDockState == Intent.EXTRA_DOCK_STATE_DESK || - PhoneApp.mDockState == Intent.EXTRA_DOCK_STATE_CAR) { + if (PhoneApp.mDockState != Intent.EXTRA_DOCK_STATE_UNDOCKED) { if (DBG) log("activateSpeakerIfDocked(): In a dock -> may need to turn on speaker."); PhoneApp app = PhoneApp.getInstance(); BluetoothHandsfree bthf = app.getBluetoothHandsfree(); if (!app.isHeadsetPlugged() && !(bthf != null && bthf.isAudioOn())) { turnOnSpeaker(phone.getContext(), true, true); } } } /** * Returns whether the phone is in ECM ("Emergency Callback Mode") or not. */ /* package */ static boolean isPhoneInEcm(Phone phone) { if ((phone != null) && TelephonyCapabilities.supportsEcm(phone)) { // For phones that support ECM, return true iff PROPERTY_INECM_MODE == "true". // TODO: There ought to be a better API for this than just // exposing a system property all the way up to the app layer, // probably a method like "inEcm()" provided by the telephony // layer. String ecmMode = SystemProperties.get(TelephonyProperties.PROPERTY_INECM_MODE); if (ecmMode != null) { return ecmMode.equals("true"); } } return false; } /** * Returns the most appropriate Phone object to handle a call * to the specified number. * * @param cm the CallManager. * @param scheme the scheme from the data URI that the number originally came from. * @param number the phone number, or SIP address. */ public static Phone pickPhoneBasedOnNumber(CallManager cm, String scheme, String number, String primarySipUri) { if (DBG) log("pickPhoneBasedOnNumber: scheme " + scheme + ", number " + number + ", sipUri " + primarySipUri); if (primarySipUri != null) { Phone phone = getSipPhoneFromUri(cm, primarySipUri); if (phone != null) return phone; } return cm.getDefaultPhone(); } public static Phone getSipPhoneFromUri(CallManager cm, String target) { for (Phone phone : cm.getAllPhones()) { if (phone.getPhoneType() == Phone.PHONE_TYPE_SIP) { String sipUri = ((SipPhone) phone).getSipUri(); if (target.equals(sipUri)) { if (DBG) log("- pickPhoneBasedOnNumber:" + "found SipPhone! obj = " + phone + ", " + phone.getClass()); return phone; } } } return null; } public static boolean isRealIncomingCall(Call.State state) { return (state == Call.State.INCOMING && !PhoneApp.getInstance().mCM.hasActiveFgCall()); } private static boolean sVoipSupported = false; static { PhoneApp app = PhoneApp.getInstance(); sVoipSupported = SipManager.isVoipSupported(app) && app.getResources().getBoolean(com.android.internal.R.bool.config_built_in_sip_phone) && app.getResources().getBoolean(com.android.internal.R.bool.config_voice_capable); } /** * @return true if this device supports voice calls using the built-in SIP stack. */ static boolean isVoipSupported() { return sVoipSupported; } // // General phone and call state debugging/testing code // /* package */ static void dumpCallState(Phone phone) { PhoneApp app = PhoneApp.getInstance(); Log.d(LOG_TAG, "dumpCallState():"); Log.d(LOG_TAG, "- Phone: " + phone + ", name = " + phone.getPhoneName() + ", state = " + phone.getState()); StringBuilder b = new StringBuilder(128); Call call = phone.getForegroundCall(); b.setLength(0); b.append(" - FG call: ").append(call.getState()); b.append(" isAlive ").append(call.getState().isAlive()); b.append(" isRinging ").append(call.getState().isRinging()); b.append(" isDialing ").append(call.getState().isDialing()); b.append(" isIdle ").append(call.isIdle()); b.append(" hasConnections ").append(call.hasConnections()); Log.d(LOG_TAG, b.toString()); call = phone.getBackgroundCall(); b.setLength(0); b.append(" - BG call: ").append(call.getState()); b.append(" isAlive ").append(call.getState().isAlive()); b.append(" isRinging ").append(call.getState().isRinging()); b.append(" isDialing ").append(call.getState().isDialing()); b.append(" isIdle ").append(call.isIdle()); b.append(" hasConnections ").append(call.hasConnections()); Log.d(LOG_TAG, b.toString()); call = phone.getRingingCall(); b.setLength(0); b.append(" - RINGING call: ").append(call.getState()); b.append(" isAlive ").append(call.getState().isAlive()); b.append(" isRinging ").append(call.getState().isRinging()); b.append(" isDialing ").append(call.getState().isDialing()); b.append(" isIdle ").append(call.isIdle()); b.append(" hasConnections ").append(call.hasConnections()); Log.d(LOG_TAG, b.toString()); final boolean hasRingingCall = !phone.getRingingCall().isIdle(); final boolean hasActiveCall = !phone.getForegroundCall().isIdle(); final boolean hasHoldingCall = !phone.getBackgroundCall().isIdle(); final boolean allLinesTaken = hasActiveCall && hasHoldingCall; b.setLength(0); b.append(" - hasRingingCall ").append(hasRingingCall); b.append(" hasActiveCall ").append(hasActiveCall); b.append(" hasHoldingCall ").append(hasHoldingCall); b.append(" allLinesTaken ").append(allLinesTaken); Log.d(LOG_TAG, b.toString()); // On CDMA phones, dump out the CdmaPhoneCallState too: if (phone.getPhoneType() == Phone.PHONE_TYPE_CDMA) { if (app.cdmaPhoneCallState != null) { Log.d(LOG_TAG, " - CDMA call state: " + app.cdmaPhoneCallState.getCurrentCallState()); } else { Log.d(LOG_TAG, " - CDMA device, but null cdmaPhoneCallState!"); } } // Watch out: the isRinging() call below does NOT tell us anything // about the state of the telephony layer; it merely tells us whether // the Ringer manager is currently playing the ringtone. boolean ringing = app.getRinger().isRinging(); Log.d(LOG_TAG, " - Ringer state: " + ringing); } private static void log(String msg) { Log.d(LOG_TAG, msg); } static void dumpCallManager() { Call call; CallManager cm = PhoneApp.getInstance().mCM; StringBuilder b = new StringBuilder(128); Log.d(LOG_TAG, "############### dumpCallManager() ##############"); // TODO: Don't log "cm" itself, since CallManager.toString() // already spews out almost all this same information. // We should fix CallManager.toString() to be more minimal, and // use an explicit dumpState() method for the verbose dump. // Log.d(LOG_TAG, "CallManager: " + cm // + ", state = " + cm.getState()); Log.d(LOG_TAG, "CallManager: state = " + cm.getState()); b.setLength(0); call = cm.getActiveFgCall(); b.append(" - FG call: ").append(cm.hasActiveFgCall()? "YES ": "NO "); b.append(call); b.append( " State: ").append(cm.getActiveFgCallState()); b.append( " Conn: ").append(cm.getFgCallConnections()); Log.d(LOG_TAG, b.toString()); b.setLength(0); call = cm.getFirstActiveBgCall(); b.append(" - BG call: ").append(cm.hasActiveBgCall()? "YES ": "NO "); b.append(call); b.append( " State: ").append(cm.getFirstActiveBgCall().getState()); b.append( " Conn: ").append(cm.getBgCallConnections()); Log.d(LOG_TAG, b.toString()); b.setLength(0); call = cm.getFirstActiveRingingCall(); b.append(" - RINGING call: ").append(cm.hasActiveRingingCall()? "YES ": "NO "); b.append(call); b.append( " State: ").append(cm.getFirstActiveRingingCall().getState()); Log.d(LOG_TAG, b.toString()); for (Phone phone : CallManager.getInstance().getAllPhones()) { if (phone != null) { Log.d(LOG_TAG, "Phone: " + phone + ", name = " + phone.getPhoneName() + ", state = " + phone.getState()); b.setLength(0); call = phone.getForegroundCall(); b.append(" - FG call: ").append(call); b.append( " State: ").append(call.getState()); b.append( " Conn: ").append(call.hasConnections()); Log.d(LOG_TAG, b.toString()); b.setLength(0); call = phone.getBackgroundCall(); b.append(" - BG call: ").append(call); b.append( " State: ").append(call.getState()); b.append( " Conn: ").append(call.hasConnections()); Log.d(LOG_TAG, b.toString());b.setLength(0); call = phone.getRingingCall(); b.append(" - RINGING call: ").append(call); b.append( " State: ").append(call.getState()); b.append( " Conn: ").append(call.hasConnections()); Log.d(LOG_TAG, b.toString()); } } Log.d(LOG_TAG, "############## END dumpCallManager() ###############"); } }
false
false
null
null
diff --git a/src/org/ohmage/query/UserMobilityQueries.java b/src/org/ohmage/query/UserMobilityQueries.java index 191997cd..b3ef65a9 100644 --- a/src/org/ohmage/query/UserMobilityQueries.java +++ b/src/org/ohmage/query/UserMobilityQueries.java @@ -1,936 +1,936 @@ package org.ohmage.query; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.LinkedList; import java.util.List; import java.util.TimeZone; import javax.sql.DataSource; import org.json.JSONException; import org.json.JSONObject; import org.ohmage.domain.Location; import org.ohmage.domain.MobilityPoint; import org.ohmage.domain.MobilityPoint.LocationStatus; import org.ohmage.domain.MobilityPoint.Mode; import org.ohmage.domain.MobilityPoint.SubType; import org.ohmage.exception.DataAccessException; import org.ohmage.exception.ErrorCodeException; import org.ohmage.util.StringUtils; import org.ohmage.util.TimeUtils; import org.springframework.jdbc.core.PreparedStatementCreator; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.SingleColumnRowMapper; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.support.GeneratedKeyHolder; import org.springframework.jdbc.support.KeyHolder; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionException; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.DefaultTransactionDefinition; import edu.ucla.cens.mobilityclassifier.MobilityClassifier; /** * This class contains all of the functionality for creating, reading, * updating, and deleting user-Mobility relationships. While it may read * information pertaining to other entities, the information it takes and * provides should pertain to user-Mobility relationships only. * * @author John Jenkins */ public final class UserMobilityQueries extends AbstractUploadQuery { // Retrieves the ID for all of the Mobility points that belong to a user. private static final String SQL_GET_IDS_FOR_USER = "SELECT m.id " + "FROM user u, mobility m " + "WHERE u.username = ? " + "AND u.id = m.user_id"; // Retrieves the ID for all of the Mobility points that belong to a user // and were uploaded by a client. private static final String SQL_GET_IDS_FOR_CLIENT = "SELECT m.id " + "FROM user u, mobility m " + "WHERE u.username = ? " + "AND u.id = m.user_id " + "AND m.client = ?"; // Retrieves the ID for all of the Mobility points that belong to a user // and were created on or after a specified date. private static final String SQL_GET_IDS_CREATED_AFTER_DATE = "SELECT m.id " + "FROM user u, mobility m " + "WHERE u.username = ? " + "AND u.id = m.user_id " + "AND m.msg_timestamp >= ?"; // Retrieves the ID for all of the Mobility points that belong to a user // and were created on or before a specified date. private static final String SQL_GET_IDS_CREATED_BEFORE_DATE = "SELECT m.id " + "FROM user u, mobility m " + "WHERE u.username = ? " + "AND u.id = m.user_id " + "AND m.msg_timestamp <= ?"; private static final String SQL_GET_IDS_CREATE_BETWEEN_DATES = "SELECT m.id " + "FROM user u, mobility m " + "WHERE u.username = ? " + "AND u.id = m.user_id " + "AND m.msg_timestamp >= ? " + "AND m.msg_timestamp <= ?"; // Retrieves the ID for all of the Mobility points that belong to a user // and were uploaded on or after a specified date. private static final String SQL_GET_IDS_UPLOADED_AFTER_DATE = "SELECT m.id " + "FROM user u, mobility m " + "WHERE u.username = ? " + "AND u.id = m.user_id " + "AND m.upload_timestamp >= ?"; // Retrieves the ID for all of the Mobility points that belong to a user // and were uploaded on or before a specified date. private static final String SQL_GET_IDS_UPLOADED_BEFORE_DATE = "SELECT m.id " + "FROM user u, mobility m " + "WHERE u.username = ? " + "AND u.id = m.user_id " + "AND m.upload_timestamp <= ?"; // Retrieves the UD for all of the Mobility points that belong to a user // and have a given privacy state. private static final String SQL_GET_IDS_WITH_PRIVACY_STATE = "SELECT m.id " + "FROM user u, mobility m " + "WHERE u.username = ? " + "AND u.id = m.user_id " + "AND m.privacy_state = ?"; // Retrieves the ID for all of the Mobility points that belong to a user // and have a given location status. private static final String SQL_GET_IDS_WITH_LOCATION_STATUS = "SELECT m.id " + "FROM user u, mobility m " + "WHERE u.username = ? " + "AND u.id = m.user_id " + "AND m.location_status = ?"; // Retrieves the ID for all of the Mobility points that belong to a user // and have a given mode. private static final String SQL_GET_IDS_WITH_MODE = "SELECT m.id " + "FROM user u, mobility m " + "WHERE u.username = ? " + "AND u.id = m.user_id " + "AND m.mode = ?"; // Retrieves all of the information pertaining to a single Mobility data // point from a given database ID. private static final String SQL_GET_MOBILITY_DATA_FROM_ID = "SELECT u.username, m.client, " + "m.msg_timestamp, m.epoch_millis, m.upload_timestamp, " + "m.phone_timezone, m.location_status, m.location, " + "m.mode, mps.privacy_state, " + "me.sensor_data, me.features, me.classifier_version " + "FROM user u, mobility_privacy_state mps, " + "mobility m LEFT JOIN mobility_extended me " + "ON m.id = me.mobility_id " + "WHERE m.id = ? " + "AND u.id = m.user_id " + "AND mps.id = m.privacy_state_id"; private static final String SQL_GET_MOBILITY_DATA_FROM_IDS = "SELECT u.username, m.client, " + "m.msg_timestamp, m.epoch_millis, m.upload_timestamp, " + "m.phone_timezone, m.location_status, m.location, " + "m.mode, mps.privacy_state, " + "me.sensor_data, me.features, me.classifier_version " + "FROM user u, mobility_privacy_state mps, " + "mobility m LEFT JOIN mobility_extended me " + "ON m.id = me.mobility_id " + "WHERE u.id = m.user_id " + "AND mps.id = m.privacy_state_id " + "AND m.id IN "; // Retrieves all of the information pertaining to a single Mobility data // point for a given username. This will return alot of data and should be // used with caution. Instead, it is recommended that a list of ID's be // aggregated and 'SQL_GET_MOBILITY_DATA_FROM_ID' be run on each of those // IDs. private static final String SQL_GET_MOBILITY_DATA_FOR_USER = "SELECT u.username, m.client, " + "m.msg_timestamp, m.epoch_millis, m.upload_timestamp, " + "m.phone_timezone, m.location_status, m.location, " + "m.mode, mps.privacy_state, " + "me.sensor_data, me.features, me.classifier_version " + "FROM user u, mobility_privacy_state mps, " + "mobility m LEFT JOIN mobility_extended me " + "ON m.id = me.mobility_id " + "WHERE u.username = ? " + "AND u.id = m.user_id " + "AND mps.id = m.privacy_state_id"; // Inserts a mode-only entry into the database. private static final String SQL_INSERT = "INSERT INTO mobility(user_id, client, msg_timestamp, epoch_millis, phone_timezone, location_status, location, mode, upload_timestamp, privacy_state_id) " + "VALUES (" + "(" + // user_id "SELECT id " + "FROM user " + "WHERE username = ?" + "), " + "?, " + // client "?, " + // msg_timestamp "?, " + // epoch_millis "?, " + // phone_timezone "?, " + // location_status "?, " + // location "?, " + // mode "now(), " + // upload_timestamp "(" + // privacy_state_id "SELECT id " + "FROM mobility_privacy_state " + "WHERE privacy_state = ?" + ")" + ")"; // Inserts an extended entry into the database. private static final String SQL_INSERT_EXTENDED = "INSERT INTO mobility_extended(mobility_id, sensor_data, features, classifier_version) " + "VALUES (" + "?, " + // mobility_id "?, " + // sensor_data "?, " + // features "?" + // classifier_version ")"; private static UserMobilityQueries instance; /** * Creates this object. * * @param dataSource The DataSource to use when accessing the database. */ private UserMobilityQueries(DataSource dataSource) { super(dataSource); instance = this; } /** * Creates a new Mobility point. * * @param username The username of the user to which this point belongs. * * @param client The client value given on upload. * * @param mobilityPoint The Mobility point to be created. * * @throws DataAccessException Thrown if there is an error. */ public static void createMobilityPoint(final String username, final String client, final MobilityPoint mobilityPoint) throws DataAccessException { // Create the transaction. DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setName("Creating a Mobility data point."); try { // Begin the transaction. PlatformTransactionManager transactionManager = new DataSourceTransactionManager(instance.getDataSource()); TransactionStatus status = transactionManager.getTransaction(def); try { KeyHolder mobilityPointDatabaseKeyHolder = new GeneratedKeyHolder(); instance.getJdbcTemplate().update( new PreparedStatementCreator() { public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { PreparedStatement ps = connection.prepareStatement(SQL_INSERT, new String[] {"id"}); ps.setString(1, username); ps.setString(2, client); ps.setTimestamp(3, new Timestamp(mobilityPoint.getDate().getTime())); ps.setLong(4, mobilityPoint.getTime()); ps.setString(5, mobilityPoint.getTimezone().getID()); ps.setString(6, mobilityPoint.getLocationStatus().toString().toLowerCase()); Location location = mobilityPoint.getLocation(); ps.setString(7, ((location == null) ? null : location.toJson(false).toString())); ps.setString(8, mobilityPoint.getMode().toString().toLowerCase()); ps.setString(9, mobilityPoint.getPrivacyState().toString()); return ps; } }, mobilityPointDatabaseKeyHolder ); // If it's an extended entry, add the sensor data. if(SubType.SENSOR_DATA.equals(mobilityPoint.getSubType())) { try { instance.getJdbcTemplate().update( SQL_INSERT_EXTENDED, mobilityPointDatabaseKeyHolder.getKey().longValue(), mobilityPoint.getSensorData().toJson().toString(), ((mobilityPoint.getClassifierData() == null) ? new JSONObject() : mobilityPoint.getClassifierData().toJson().toString()), MobilityClassifier.getVersion()); } catch(org.springframework.dao.DataAccessException e) { throw new DataAccessException( "Error executing SQL '" + SQL_INSERT_EXTENDED + "' with parameters: " + mobilityPointDatabaseKeyHolder.getKey().longValue() + ", " + mobilityPoint.getSensorData().toJson().toString() + ", " + ((mobilityPoint.getClassifierData() == null) ? new JSONObject() : mobilityPoint.getClassifierData().toJson().toString()) + ", " + MobilityClassifier.getVersion(), e); } } } // If this is a duplicate upload, we will ignore it by rolling back // to where we were before we started and return. catch(org.springframework.dao.DataIntegrityViolationException e) { if(! instance.isDuplicate(e)) { throw new DataAccessException( - "Error executing SQL '" + SQL_INSERT_EXTENDED + "' with parameters: " + + "Error executing SQL '" + SQL_INSERT + "' with parameters: " + username + ", " + client + ", " + TimeUtils.getIso8601DateTimeString(mobilityPoint.getDate()) + ", " + mobilityPoint.getTime() + ", " + mobilityPoint.getTimezone().getID() + ", " + mobilityPoint.getLocationStatus().toString().toLowerCase() + ", " + ((mobilityPoint.getLocation() == null) ? "null" : mobilityPoint.getLocation().toJson(false).toString()) + ", " + mobilityPoint.getMode().toString().toLowerCase() + ", " + mobilityPoint.getPrivacyState(), e); } } catch(org.springframework.dao.DataAccessException e) { throw new DataAccessException( - "Error executing SQL '" + SQL_INSERT_EXTENDED + "' with parameters: " + + "Error executing SQL '" + SQL_INSERT + "' with parameters: " + username + ", " + client + ", " + TimeUtils.getIso8601DateTimeString(mobilityPoint.getDate()) + ", " + mobilityPoint.getTime() + ", " + mobilityPoint.getTimezone().getID() + ", " + mobilityPoint.getLocationStatus().toString().toLowerCase() + ", " + ((mobilityPoint.getLocation() == null) ? "null" : mobilityPoint.getLocation().toJson(false).toString()) + ", " + mobilityPoint.getMode().toString().toLowerCase() + ", " + mobilityPoint.getPrivacyState(), e); } // Commit the transaction. try { transactionManager.commit(status); } catch(TransactionException e) { transactionManager.rollback(status); throw new DataAccessException("Error while committing the transaction.", e); } } catch(TransactionException e) { throw new DataAccessException("Error while attempting to rollback the transaction.", e); } } /** * Retrieves the database ID for all of the Mobility data points that * belong to a specific user. * * @param username The user's username. * * @return A, possibly empty but never null, list of database IDs for each * Mobility data point belonging to some user. * * @throws DataAccessException Thrown if there is an error. */ public static List<Long> getIdsForUser(String username) throws DataAccessException { try { return instance.getJdbcTemplate().query( SQL_GET_IDS_FOR_USER, new Object[] { username }, new SingleColumnRowMapper<Long>()); } catch(org.springframework.dao.DataAccessException e) { throw new DataAccessException( "Error executing SQL '" + SQL_GET_IDS_FOR_USER + "' with parameter: " + username, e); } } /** * Retrieves the database ID for all of the Mobility data points that * belong to a specific user and that were uploaded by a specific client. * * @param username The user's username. * * @param client The client value. * * @return A, possibly empty but never null, list of database IDs for each * Mobility data point belonging to some user. * * @throws DataAccessException Thrown if there is an error. */ public static List<Long> getIdsForClient(String username, String client) throws DataAccessException { try { return instance.getJdbcTemplate().query( SQL_GET_IDS_FOR_CLIENT, new Object[] { username, client }, new SingleColumnRowMapper<Long>()); } catch(org.springframework.dao.DataAccessException e) { throw new DataAccessException( "Error executing SQL '" + SQL_GET_IDS_FOR_CLIENT + "' with parameters: " + username + ", " + client, e); } } /** * Retrieves the database ID for all of the Mobility data points that * belong to a specific user and that were created on or after a specified * date. * * @param username The user's username. * * @param startDate The date. * * @return A, possibly empty but never null, list of database IDs for each * Mobility data point belonging to some user. * * @throws DataAccessException Thrown if there is an error. */ public static List<Long> getIdsCreatedAfterDate(String username, Date startDate) throws DataAccessException { try { return instance.getJdbcTemplate().query( SQL_GET_IDS_CREATED_AFTER_DATE, new Object[] { username, TimeUtils.getIso8601DateString(startDate) }, new SingleColumnRowMapper<Long>()); } catch(org.springframework.dao.DataAccessException e) { throw new DataAccessException( "Error executing SQL '" + SQL_GET_IDS_CREATED_AFTER_DATE + "' with parameters: " + username + ", " + TimeUtils.getIso8601DateString(startDate), e); } } /** * Retrieves the database ID for all of the Mobility data points that * belong to a specific user and that were created on or before a specified * date. * * @param username The user's username. * * @param endDate The date. * * @return A, possibly empty but never null, list of database IDs for each * Mobility data point belonging to some user. * * @throws DataAccessException Thrown if there is an error. */ public static List<Long> getIdsCreatedBeforeDate(String username, Date endDate) throws DataAccessException { try { return instance.getJdbcTemplate().query( SQL_GET_IDS_CREATED_BEFORE_DATE, new Object[] { username, TimeUtils.getIso8601DateString(endDate) }, new SingleColumnRowMapper<Long>()); } catch(org.springframework.dao.DataAccessException e) { throw new DataAccessException( "Error executing SQL '" + SQL_GET_IDS_CREATED_BEFORE_DATE + "' with parameters: " + username + ", " + TimeUtils.getIso8601DateString(endDate), e); } } public static List<Long> getIdsCreatedBetweenDates(String username, Date startDate, Date endDate) throws DataAccessException { try { return instance.getJdbcTemplate().query( SQL_GET_IDS_CREATE_BETWEEN_DATES, new Object[] { username, TimeUtils.getIso8601DateString(startDate), TimeUtils.getIso8601DateString(endDate) }, new SingleColumnRowMapper<Long>()); } catch(org.springframework.dao.DataAccessException e) { throw new DataAccessException( "Error executing SQL '" + SQL_GET_IDS_CREATED_BEFORE_DATE + "' with parameters: " + username + ", " + TimeUtils.getIso8601DateString(endDate), e); } } /** * Retrieves the database ID for all of the Mobility data points that * belong to a specific user and that were uploaded on or after a specified * date. * * @param username The user's username. * * @param startDate The date. * * @return A, possibly empty but never null, list of database IDs for each * Mobility data point belonging to some user. * * @throws DataAccessException Thrown if there is an error. */ public static List<Long> getIdsUploadedAfterDate(String username, Date startDate) throws DataAccessException { try { return instance.getJdbcTemplate().query( SQL_GET_IDS_UPLOADED_AFTER_DATE, new Object[] { username, TimeUtils.getIso8601DateString(startDate) }, new SingleColumnRowMapper<Long>()); } catch(org.springframework.dao.DataAccessException e) { throw new DataAccessException( "Error executing SQL '" + SQL_GET_IDS_UPLOADED_AFTER_DATE + "' with parameters: " + username + ", " + TimeUtils.getIso8601DateString(startDate), e); } } /** * Retrieves the database ID for all of the Mobility data points that * belong to a specific user and that were uploaded on or before a * specified date. * * @param username The user's username. * * @param endDate The date. * * @return A, possibly empty but never null, list of database IDs for each * Mobility data point belonging to some user. * * @throws DataAccessException Thrown if there is an error. */ public static List<Long> getIdsUploadedBeforeDate(String username, Date endDate) throws DataAccessException { try { return instance.getJdbcTemplate().query( SQL_GET_IDS_UPLOADED_BEFORE_DATE, new Object[] { username, TimeUtils.getIso8601DateString(endDate) }, new SingleColumnRowMapper<Long>()); } catch(org.springframework.dao.DataAccessException e) { throw new DataAccessException( "Error executing SQL '" + SQL_GET_IDS_UPLOADED_BEFORE_DATE + "' with parameters: " + username + ", " + TimeUtils.getIso8601DateString(endDate), e); } } /** * Retrieves the database ID for all of the Mobility data points that * belong to a specific user and that have a given privacy state. * * @param username The user's username. * * @param privacyState The privacy state. * * @return A, possibly empty but never null, list of database IDs for each * Mobility data point belonging to some user. * * @throws DataAccessException Thrown if there is an error. */ public static List<Long> getIdsWithPrivacyState(String username, MobilityPoint.PrivacyState privacyState) throws DataAccessException { try { return instance.getJdbcTemplate().query( SQL_GET_IDS_WITH_PRIVACY_STATE, new Object[] { username, privacyState.toString() }, new SingleColumnRowMapper<Long>()); } catch(org.springframework.dao.DataAccessException e) { throw new DataAccessException( "Error executing SQL '" + SQL_GET_IDS_WITH_PRIVACY_STATE + "' with parameters: " + username + ", " + privacyState, e); } } /** * Retrieves the database ID for all Mobility data points that belong to a * user and have a given location status. * * @param username The username of the user. * * @param locationStatus The location status. * * @return A, possibly empty but never null, list of database IDs for the * resulting Mobility data points. * * @throws DataAccessException Thrown if there is an error. */ public static List<Long> getIdsWithLocationStatus(String username, LocationStatus locationStatus) throws DataAccessException { try { return instance.getJdbcTemplate().query( SQL_GET_IDS_WITH_LOCATION_STATUS, new Object[] { username, locationStatus.toString().toLowerCase() }, new SingleColumnRowMapper<Long>()); } catch(org.springframework.dao.DataAccessException e) { throw new DataAccessException( "Error executing SQL '" + SQL_GET_IDS_WITH_LOCATION_STATUS + "' with parameters: " + username + ", " + locationStatus.toString().toLowerCase(), e); } } /** * Retrieves the database ID for all Mobiltiy data points that belong to a * user and have a given mode. * * @param username The username of the user. * * @param mode The mode. * * @return A, possibly empty but never null, list of database IDs for the * resulting Mobility data points. * * @throws DataAccessException Thrown if there is an error. */ public static List<Long> getIdsWithMode(String username, Mode mode) throws DataAccessException { try { return instance.getJdbcTemplate().query( SQL_GET_IDS_WITH_MODE, new Object[] { username, mode.toString().toLowerCase() }, new SingleColumnRowMapper<Long>()); } catch(org.springframework.dao.DataAccessException e) { throw new DataAccessException( "Error executing SQL '" + SQL_GET_IDS_WITH_MODE + "' with parameters: " + username + ", " + mode.toString().toLowerCase(), e); } } /** * Retrieves a MobilityInformation object representing the Mobility data * point whose database ID is 'id' or null if no such database ID exists. * * @param id The Mobility data point's database ID. * * @return A MobilityInformation object representing this Mobility data * point or null if no such point exists. * * @throws DataAccessException Thrown if there is an error. */ public static MobilityPoint getMobilityInformationFromId(Long id) throws DataAccessException { try { return instance.getJdbcTemplate().queryForObject( SQL_GET_MOBILITY_DATA_FROM_ID, new Object[] { id }, new RowMapper<MobilityPoint>() { @Override public MobilityPoint mapRow(ResultSet rs, int rowNum) throws SQLException { try { JSONObject location = null; String locationString = rs.getString("location"); if(locationString != null) { location = new JSONObject(locationString); } JSONObject sensorData = null; String sensorDataString = rs.getString("sensor_data"); if(sensorDataString != null) { sensorData = new JSONObject(sensorDataString); } JSONObject features = null; String featuresString = rs.getString("features"); if(featuresString != null) { features = new JSONObject(featuresString); } return new MobilityPoint( rs.getTimestamp("msg_timestamp"), rs.getLong("epoch_millis"), TimeZone.getTimeZone(rs.getString("phone_timezone")), LocationStatus.valueOf(rs.getString("location_status").toUpperCase()), location, Mode.valueOf(rs.getString("mode").toUpperCase()), MobilityPoint.PrivacyState.getValue(rs.getString("privacy_state")), sensorData, features, rs.getString("classifier_version")); } catch(JSONException e) { throw new SQLException("Error building a JSONObject.", e); } catch(ErrorCodeException e) { throw new SQLException("Error building the MobilityInformation object. This suggests malformed data in the database.", e); } catch(IllegalArgumentException e) { throw new SQLException("Error building the MobilityInformation object. This suggests malformed data in the database.", e); } } } ); } catch(org.springframework.dao.IncorrectResultSizeDataAccessException e) { if(e.getActualSize() > 1) { throw new DataAccessException("Multiple Mobility data points have the same database ID.", e); } return null; } catch(org.springframework.dao.DataAccessException e) { throw new DataAccessException( "Error executing SQL '" + SQL_GET_MOBILITY_DATA_FROM_ID + "' with parameter: " + id, e); } } /** * Gathers the MobilitInformation for all of the IDs in the collection. * * @param ids A collection of database IDs for Mobility points. * * @return A, possibly empty but never null, list of MobilityInformation * objects where each object should correspond to an ID in the * 'ids' list. * * @throws DataAccessException Thrown if there is an error. */ public static List<MobilityPoint> getMobilityInformationFromIds(Collection<Long> ids) throws DataAccessException { try { return instance.getJdbcTemplate().query( SQL_GET_MOBILITY_DATA_FROM_IDS + StringUtils.generateStatementPList(ids.size()), ids.toArray(), new RowMapper<MobilityPoint>() { @Override public MobilityPoint mapRow(ResultSet rs, int rowNum) throws SQLException { try { JSONObject location = null; String locationString = rs.getString("location"); if(locationString != null) { location = new JSONObject(locationString); } JSONObject sensorData = null; String sensorDataString = rs.getString("sensor_data"); if(sensorDataString != null) { sensorData = new JSONObject(sensorDataString); } JSONObject features = null; String featuresString = rs.getString("features"); if(featuresString != null) { features = new JSONObject(featuresString); } return new MobilityPoint( rs.getTimestamp("msg_timestamp"), rs.getLong("epoch_millis"), TimeZone.getTimeZone(rs.getString("phone_timezone")), LocationStatus.valueOf(rs.getString("location_status").toUpperCase()), location, Mode.valueOf(rs.getString("mode").toUpperCase()), MobilityPoint.PrivacyState.getValue(rs.getString("privacy_state")), sensorData, features, rs.getString("classifier_version")); } catch(JSONException e) { throw new SQLException("Error building a JSONObject.", e); } catch(ErrorCodeException e) { throw new SQLException("Error building the MobilityInformation object. This suggests malformed data in the database.", e); } catch(IllegalArgumentException e) { throw new SQLException("Error building the MobilityInformation object. This suggests malformed data in the database.", e); } } } ); } catch(org.springframework.dao.DataAccessException e) { throw new DataAccessException( "Error executing SQL '" + SQL_GET_MOBILITY_DATA_FROM_ID + "' with parameter: " + ids, e); } } /** * Retrieves the timestamp of last Mobility upload from a user. * * @param username The user's username. * * @return Returns a Timestamp representing the date and time that the last * Mobility upload from a user took place. If no Mobility data was * ever uploaded, null is returned. */ public static Timestamp getLastUploadForUser(String username) throws DataAccessException { try { List<Timestamp> timestamps = instance.getJdbcTemplate().query( SQL_GET_MOBILITY_DATA_FOR_USER, new Object[] { username }, new RowMapper<Timestamp>() { @Override public Timestamp mapRow(ResultSet rs, int rowNum) throws SQLException { // First, create a TimeZone object with the time // zone from the database. TimeZone timezone = TimeZone.getDefault(); String timezoneString = rs.getString("phone_timezone"); if(timezoneString != null) { timezone = TimeZone.getTimeZone(timezoneString); } // Next, create a Calendar object and updated it // with the time zone. Calendar calendar = Calendar.getInstance(); calendar.setTimeZone(timezone); // Finally, grab the time from the database and // update it with the time zone stored in the // database. return rs.getTimestamp("msg_timestamp", calendar); } } ); if(timestamps.size() > 0) { Collections.sort(timestamps); return timestamps.get(timestamps.size() - 1); } else { return null; } } catch(org.springframework.dao.DataAccessException e) { throw new DataAccessException( "Error while executing '" + SQL_GET_MOBILITY_DATA_FOR_USER + "' with parameters: " + username, e); } } /** * Returns the percentage of non-null location values that were uploaded in * the last 'hours'. * * @param username The user's username. * * @param hours The number of hours before now to find applicable uploads. * * @return The percentage of non-null Mobility uploads or null if there * were none. */ public static Double getPercentageOfNonNullLocations(String username, int hours) throws DataAccessException { try { // Get a time stamp from 'hours' ago. Calendar dayAgo = Calendar.getInstance(); dayAgo.add(Calendar.HOUR_OF_DAY, -hours); final Timestamp dayAgoTimestamp = new Timestamp(dayAgo.getTimeInMillis()); final List<String> nonNullLocations = new LinkedList<String>(); final List<String> allLocations = new LinkedList<String>(); instance.getJdbcTemplate().query( SQL_GET_MOBILITY_DATA_FOR_USER, new Object[] { username }, new RowMapper<Object>() { @Override public Object mapRow(ResultSet rs, int rowNum) throws SQLException { // First, create a TimeZone object with the time // zone from the database. TimeZone timezone = TimeZone.getDefault(); String timezoneString = rs.getString("phone_timezone"); if(timezoneString != null) { timezone = TimeZone.getTimeZone(timezoneString); } // Next, create a Calendar object and updated it // with the time zone. Calendar calendar = Calendar.getInstance(); calendar.setTimeZone(timezone); // Now, generate a timestamp with the accurate // date and time. Timestamp generatedTimestamp = rs.getTimestamp("msg_timestamp", calendar); // If it was uploaded within the last 'hours' it is // valid. if(! generatedTimestamp.before(dayAgoTimestamp)) { String location = rs.getString("location"); if(location != null) { nonNullLocations.add(location); } allLocations.add(location); } return null; } } ); if(allLocations.size() == 0) { return null; } else { return new Double(nonNullLocations.size()) / new Double(allLocations.size()); } } catch(org.springframework.dao.DataAccessException e) { throw new DataAccessException( "Error while executing '" + SQL_GET_MOBILITY_DATA_FOR_USER + "' with parameters: " + username, e); } } } \ No newline at end of file
false
false
null
null
diff --git a/PortKnocker/src/com/xargsgrep/portknocker/fragment/PortsFragment.java b/PortKnocker/src/com/xargsgrep/portknocker/fragment/PortsFragment.java index 00d86c6..7384d6e 100644 --- a/PortKnocker/src/com/xargsgrep/portknocker/fragment/PortsFragment.java +++ b/PortKnocker/src/com/xargsgrep/portknocker/fragment/PortsFragment.java @@ -1,108 +1,112 @@ package com.xargsgrep.portknocker.fragment; +import java.util.ArrayList; import java.util.Arrays; import java.util.List; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import com.actionbarsherlock.app.SherlockListFragment; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; import com.xargsgrep.portknocker.R; import com.xargsgrep.portknocker.activity.EditHostActivity; import com.xargsgrep.portknocker.adapter.PortArrayAdapter; import com.xargsgrep.portknocker.db.DatabaseManager; import com.xargsgrep.portknocker.model.Host; import com.xargsgrep.portknocker.model.Port; public class PortsFragment extends SherlockListFragment { public static final String TAG = "PortsFragment"; DatabaseManager databaseManager; - PortArrayAdapter portAdapter; boolean savedInstanceState = false; public static PortsFragment newInstance(Long hostId) { PortsFragment fragment = new PortsFragment(); if (hostId != null) { Bundle args = new Bundle(); args.putLong(EditHostActivity.KEY_HOST_ID, hostId); fragment.setArguments(args); } return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); setHasOptionsMenu(true); databaseManager = new DatabaseManager(getActivity()); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View view = inflater.inflate(R.layout.list_view, container, false); - View header = getActivity().getLayoutInflater().inflate(R.layout.ports_header, null); + View header = inflater.inflate(R.layout.ports_header, null); ((LinearLayout) view).addView(header, 0); return view; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); Bundle args = getArguments(); + List<Port> defaultPorts = new ArrayList<Port>(); + defaultPorts.add(new Port()); + defaultPorts.add(new Port()); + defaultPorts.add(new Port()); + if (args != null && !this.savedInstanceState) { // only restore state from args if onSaveInstanceState hasn't been invoked Long hostId = args.getLong(EditHostActivity.KEY_HOST_ID); Host host = databaseManager.getHost(hostId); - List<Port> ports = (host.getPorts().size() > 0) ? host.getPorts() : Arrays.asList(new Port()); + List<Port> ports = (host.getPorts().size() > 0) ? host.getPorts() : defaultPorts; portAdapter = new PortArrayAdapter(getActivity(), ports); setListAdapter(portAdapter); } else if (portAdapter == null) { - List<Port> ports = Arrays.asList(new Port(), new Port(), new Port()); - portAdapter = new PortArrayAdapter(getActivity(), ports); + portAdapter = new PortArrayAdapter(getActivity(), defaultPorts); setListAdapter(portAdapter); } } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); menu.add(Menu.NONE, EditHostActivity.MENU_ITEM_ADD_PORT, 0, "Add Port").setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case EditHostActivity.MENU_ITEM_ADD_PORT: addPort(); return true; default: return false; } } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); savedInstanceState = true; } private void addPort() { PortArrayAdapter adapter = (PortArrayAdapter) getListAdapter(); adapter.add(new Port()); } }
false
false
null
null
diff --git a/BixiOnHBase/src/org/apache/hadoop/hbase/client/coprocessor/BixiClient.java b/BixiOnHBase/src/org/apache/hadoop/hbase/client/coprocessor/BixiClient.java index 287cd39..77432b0 100644 --- a/BixiOnHBase/src/org/apache/hadoop/hbase/client/coprocessor/BixiClient.java +++ b/BixiOnHBase/src/org/apache/hadoop/hbase/client/coprocessor/BixiClient.java @@ -1,356 +1,356 @@ package org.apache.hadoop.hbase.client.coprocessor; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.client.Get; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.coprocessor.BixiProtocol; import org.apache.hadoop.hbase.filter.Filter; import org.apache.hadoop.hbase.filter.RegexStringComparator; import org.apache.hadoop.hbase.filter.RowFilter; import org.apache.hadoop.hbase.filter.CompareFilter; import org.apache.hadoop.hbase.util.Bytes; import bixi.hbase.query.BixiConstant; public class BixiClient { public static final Log log = LogFactory.getLog(BixiClient.class); HTable table, stat_table, cluster_table;; Configuration conf; private static final byte[] TABLE_NAME = Bytes.toBytes(BixiConstant.SCHEMA1_TABLE_NAME); private static final byte[] STATION_TABLE_NAME = Bytes.toBytes(BixiConstant.SCHEMA2_BIKE_TABLE_NAME); private static final byte[] STATION_CLUSTER_TABLE_NAME = Bytes.toBytes(BixiConstant.SCHEMA2_CLUSTER_TABLE_NAME); public BixiClient(Configuration conf) throws IOException { this.conf = conf; this.table = new HTable(conf, TABLE_NAME); this.stat_table = new HTable(conf, STATION_TABLE_NAME); this.cluster_table = new HTable(conf, STATION_CLUSTER_TABLE_NAME); log.debug("in constructor of BixiClient"); } /** * @param stationIds * @param dateWithHour * : most simple format; format is: dd_mm_yyyy__hh * @return //01_10_2010__01 * @throws Throwable * @throws IOException */ public <R> Map<String, Integer> getAvailBikes(final List<String> stationIds, String dateWithHour) throws IOException, Throwable { final Scan scan = new Scan(); log.debug("in getAvailBikes: " + dateWithHour); if (dateWithHour != null) { scan.setStartRow((dateWithHour + "_00").getBytes()); scan.setStopRow((dateWithHour + "_59").getBytes()); } class BixiCallBack implements Batch.Callback<Map<String, Integer>> { Map<String, Integer> res = new HashMap<String, Integer>(); @Override public void update(byte[] region, byte[] row, Map<String, Integer> result) { res = result; } } BixiCallBack callBack = new BixiCallBack(); table.coprocessorExec(BixiProtocol.class, scan.getStartRow(), scan .getStopRow(), new Batch.Call<BixiProtocol, Map<String, Integer>>() { public Map<String, Integer> call(BixiProtocol instance) throws IOException { return instance.giveAvailableBikes(0, stationIds, scan); }; }, callBack); return callBack.res; } public Map<String, Double> getAvgUsageForPeriod(final List<String> stationIds, String startDate, String endDate) throws IOException, Throwable { final Scan scan = new Scan(); if(endDate == null) endDate = startDate; if (startDate != null) { scan.setStartRow((startDate + "_00").getBytes()); scan.setStopRow((endDate + "_59").getBytes()); } - DateFormat formatter = new SimpleDateFormat("yyyyMMddHH"); + DateFormat formatter = new SimpleDateFormat("dd_MM_yyyy__HH"); Date start = formatter.parse(startDate); Date end = formatter.parse(endDate); long comp = (end.getTime()/60000)-(start.getTime()/60000)+1; final double count = comp; class BixiCallBack implements Batch.Callback<Map<String, Long>> { Map<String, Long> res = new HashMap<String, Long>(); @Override public void update(byte[] region, byte[] row, Map<String, Long> result) { for (Map.Entry<String, Long> e : result.entrySet()) { if (res.containsKey(e.getKey())) { // add the val long t = e.getValue(); t += res.get(e.getKey()); res.put(e.getKey(), t); } else { res.put(e.getKey(), e.getValue()); } } } private Map<String, Double> getResult() { Map<String, Double> ret = new HashMap<String, Double>(); for (Map.Entry<String, Long> e : res.entrySet()) { double i = e.getValue() / count; ret.put(e.getKey(), i); } return ret; } } BixiCallBack callBack = new BixiCallBack(); long starttime = System.currentTimeMillis(); table.coprocessorExec(BixiProtocol.class, scan.getStartRow(), scan .getStopRow(), new Batch.Call<BixiProtocol, Map<String, Long>>() { public Map<String, Long> call(BixiProtocol instance) throws IOException { return instance.giveTotalUsage(stationIds, scan); }; }, callBack); long cluster_access = System.currentTimeMillis(); System.out.println("cluster access time : " + (cluster_access - starttime)); return callBack.getResult(); } // get number of free bikes at a given time. for a given pair of lat/lon and a // radius /** * @param lat * @param lon * @param radius * @param dateWithHour * @return * @throws IOException * @throws Throwable */ public Map<String, Integer> getAvailableBikesFromAPoint(final double lat, final double lon, final double radius, String dateWithHour) throws IOException, Throwable { final Get get = new Get((dateWithHour + "_00").getBytes()); log.debug("in getAvgUsageForAHr: " + dateWithHour); class BixiAvailCallBack implements Batch.Callback<Map<String, Integer>> { Map<String, Integer> res = new HashMap<String, Integer>(); @Override public void update(byte[] region, byte[] row, Map<String, Integer> result) { res = result; } private Map<String, Integer> getResult() { return res; } } BixiAvailCallBack callBack = new BixiAvailCallBack(); long starttime = System.currentTimeMillis(); table.coprocessorExec(BixiProtocol.class, get.getRow(), get.getRow(), new Batch.Call<BixiProtocol, Map<String, Integer>>() { public Map<String, Integer> call(BixiProtocol instance) throws IOException { return instance.getAvailableBikesFromAPoint(lat, lon, radius, get); }; }, callBack); long cluster_access = System.currentTimeMillis(); System.out.println("cluster access time : " + (cluster_access - starttime)); Map<String, Integer> res = callBack.getResult(); System.out.println("Number of stations: " + res.size()); return res; } /* Schema 2 implementation */ public Map<String, Double> getAvgUsageForPeriod_Schema2(final List<String> stationIds, String startDateWithHour, String endDateWithHour) throws IOException, Throwable { final Scan scan = new Scan(); log.debug("in getAvgUsageForPeriod: " + startDateWithHour); if(endDateWithHour == null){ endDateWithHour = startDateWithHour; } if (startDateWithHour != null) { scan.setStartRow((startDateWithHour + "-1").getBytes()); scan.setStopRow((endDateWithHour + "-407").getBytes()); if(stationIds!=null && stationIds.size()>0){ String regex = "("; boolean start = true; for(String sId : stationIds){ if(!start) regex += "|"; start = false; regex += "-" + sId; } regex += ")$"; Filter filter = new RowFilter(CompareFilter.CompareOp.EQUAL, new RegexStringComparator(regex)); scan.setFilter(filter); } } DateFormat formatter = new SimpleDateFormat("yyyyMMddHH"); Date start = formatter.parse(startDateWithHour); Date end = formatter.parse(endDateWithHour); long comp = (end.getTime()/60000)-(start.getTime()/60000)+1; final long numHours = comp; class BixiCallBack implements Batch.Callback<Map<String, Long>> { Map<String, Double> res = new HashMap<String, Double>(); @Override public void update(byte[] region, byte[] row, Map<String, Long> result) { for (Map.Entry<String, Long> e : result.entrySet()) { if (res.containsKey(e.getKey())) { // add the val long t = e.getValue(); t += res.get(e.getKey()); res.put(e.getKey(), (double)t); } else { res.put(e.getKey(), (double)e.getValue()); } } } private Map<String, Double> getResult() { System.out.println("numHours: " + numHours); for (Map.Entry<String, Double> e : res.entrySet()) { double i = e.getValue() / (double)numHours; res.put(e.getKey(), i); } return res; } } BixiCallBack callBack = new BixiCallBack(); long starttime = System.currentTimeMillis(); stat_table.coprocessorExec(BixiProtocol.class, scan.getStartRow(), scan .getStopRow(), new Batch.Call<BixiProtocol, Map<String, Long>>() { public Map<String, Long> call(BixiProtocol instance) throws IOException { return instance.getTotalUsage_Schema2(scan); }; }, callBack); long cluster_access = System.currentTimeMillis(); System.out.println("cluster access time : " + (cluster_access - starttime)); return callBack.getResult(); } // get number of free bikes at a given time. for a given pair of lat/lon and a // radius /** * @param lat * @param lon * @param radius * @param dateWithHour * @return * @throws IOException * @throws Throwable */ public Map<String, Integer> getAvailableBikesFromAPoint_Schema2(final double lat, final double lon, String dateWithHour) throws IOException, Throwable { List<String> stationIds = this.getStationsNearPoint(lat, lon); final Scan scan = new Scan(); if (dateWithHour != null) { scan.setStartRow((dateWithHour + "-1").getBytes()); scan.setStopRow((dateWithHour + "-407").getBytes()); if(stationIds!=null && stationIds.size()>0){ String regex = "("; boolean start = true; for(String sId : stationIds){ if(!start) regex += "|"; start = false; regex += "-" + sId; } regex += ")$"; Filter filter = new RowFilter(CompareFilter.CompareOp.EQUAL, new RegexStringComparator(regex)); scan.setFilter(filter); } } class BixiAvailCallBack implements Batch.Callback<Map<String, Integer>> { Map<String, Integer> res = new HashMap<String, Integer>(); @Override public void update(byte[] region, byte[] row, Map<String, Integer> result) { res.putAll(result); } private Map<String, Integer> getResult() { return res; } } BixiAvailCallBack callBack = new BixiAvailCallBack(); long starttime = System.currentTimeMillis(); stat_table.coprocessorExec(BixiProtocol.class, scan.getStartRow(), scan.getStopRow(), new Batch.Call<BixiProtocol, Map<String, Integer>>() { public Map<String, Integer> call(BixiProtocol instance) throws IOException { return instance.getAvailableBikesFromAPoint_Schema2(scan); }; }, callBack); long cluster_access = System.currentTimeMillis(); System.out.println("cluster access time : " + (cluster_access - starttime)); Map<String, Integer> res = callBack.getResult(); return res; } public List<String> getStationsNearPoint(final double lat, final double lon) throws IOException, Throwable{ System.out.println("Getting stations in cluster"); class BixiAvailCallBack implements Batch.Callback<List<String>> { List<String> res = new ArrayList<String>(); @Override public void update(byte[] region, byte[] row, List<String> result) { res.addAll(result); } private List<String> getResult() { return res; } } BixiAvailCallBack callBack = new BixiAvailCallBack(); long starttime = System.currentTimeMillis(); cluster_table.coprocessorExec(BixiProtocol.class, null, null, new Batch.Call<BixiProtocol, List<String>>() { public List<String> call(BixiProtocol instance) throws IOException { return instance.getStationsNearPoint_Schema2(lat, lon); }; }, callBack); long cluster_access = System.currentTimeMillis(); System.out.println("get stations in cluster access time : " + (cluster_access - starttime)); List<String> res = callBack.getResult(); System.out.println("got " + res.size() + " stations"); return res; } }
true
false
null
null
diff --git a/src/org/eclipse/core/internal/resources/Project.java b/src/org/eclipse/core/internal/resources/Project.java index b2ee8e0a..0efa9526 100644 --- a/src/org/eclipse/core/internal/resources/Project.java +++ b/src/org/eclipse/core/internal/resources/Project.java @@ -1,909 +1,911 @@ /******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.core.internal.resources; import java.util.*; import org.eclipse.core.internal.events.LifecycleEvent; import org.eclipse.core.internal.utils.Assert; import org.eclipse.core.internal.utils.Policy; import org.eclipse.core.resources.*; import org.eclipse.core.resources.team.IMoveDeleteHook; import org.eclipse.core.runtime.*; public class Project extends Container implements IProject { protected Project(IPath path, Workspace container) { super(path, container); } /* * If the creation boolean is true then this method is being called on project creation. * Otherwise it is being called via #setDescription. The difference is that we don't allow * some description fields to change value after project creation. (e.g. project location) */ protected MultiStatus basicSetDescription(ProjectDescription description) { String message = Policy.bind("resources.projectDesc"); //$NON-NLS-1$ MultiStatus result = new MultiStatus(ResourcesPlugin.PI_RESOURCES, IResourceStatus.FAILED_WRITE_METADATA, message, null); ProjectDescription current = (ProjectDescription) internalGetDescription(); current.setComment(description.getComment()); // set the build order before setting the references or the natures current.setBuildSpec(description.getBuildSpec(true)); // set the references before the natures IProject[] oldReferences = current.getReferencedProjects(); IProject[] newReferences = description.getReferencedProjects(); if (!Arrays.equals(oldReferences, newReferences)) { current.setReferencedProjects(description.getReferencedProjects(true)); workspace.flushBuildOrder(); } // the natures last as this may cause recursive calls to setDescription. workspace.getNatureManager().configureNatures(this, current, description, result); return result; } /** * @see IProject#build */ public void build(int kind, String builderName, Map args, IProgressMonitor monitor) throws CoreException { try { workspace.prepareOperation(); ResourceInfo info = getResourceInfo(false, false); int flags = getFlags(info); if (!exists(flags, true) || !isOpen(flags)) return; workspace.beginOperation(true); workspace.getBuildManager().build(this, kind, builderName, args, monitor); } finally { //building may close the tree, but we are still inside an operation so open it if (workspace.getElementTree().isImmutable()) workspace.newWorkingTree(); workspace.getWorkManager().avoidAutoBuild(); workspace.endOperation(false, null); } } /** * @see IProject#build */ public void build(int trigger, IProgressMonitor monitor) throws CoreException { try { workspace.prepareOperation(); ResourceInfo info = getResourceInfo(false, false); int flags = getFlags(info); if (!exists(flags, true) || !isOpen(flags)) return; workspace.beginOperation(true); workspace.getBuildManager().build(this, trigger, monitor); } finally { //building may close the tree, but we are still inside an operation so open it if (workspace.getElementTree().isImmutable()) workspace.newWorkingTree(); workspace.getWorkManager().avoidAutoBuild(); workspace.endOperation(false, null); } } /** * Checks that this resource is accessible. Typically this means that it * exists. In the case of projects, they must also be open. * If phantom is true, phantom resources are considered. * * @exception CoreException if this resource is not accessible */ public void checkAccessible(int flags) throws CoreException { super.checkAccessible(flags); if (!isOpen(flags)) { String message = Policy.bind("resources.mustBeOpen", getFullPath().toString()); //$NON-NLS-1$ throw new ResourceException(IResourceStatus.PROJECT_NOT_OPEN, getFullPath(), message, null); } } /** * Checks validity of the given project description. */ protected void checkDescription(IProject project, IProjectDescription desc, boolean moving) throws CoreException { IPath location = desc.getLocation(); if (location == null) return; String message = Policy.bind("resources.invalidProjDesc"); //$NON-NLS-1$ MultiStatus status = new MultiStatus(ResourcesPlugin.PI_RESOURCES, IResourceStatus.INVALID_VALUE, message, null); status.merge(workspace.validateName(desc.getName(), IResource.PROJECT)); if (moving) { // if we got here from a move call then we should check the location in the description since // its possible that we want to do a rename without moving the contents. (and we shouldn't // throw an Overlapping mapping exception in this case) So if the source description's location // is null (we are using the default) or if the locations aren't equal, then validate the location // of the new description. Otherwise both locations aren't null and they are equal so ignore validation. IPath sourceLocation = internalGetDescription().getLocation(); if (sourceLocation == null || !sourceLocation.equals(location)) status.merge(workspace.validateProjectLocation(project, location)); } else // otherwise continue on like before status.merge(workspace.validateProjectLocation(project, location)); if (!status.isOK()) throw new ResourceException(status); } /** * @see IProject#close */ public void close(IProgressMonitor monitor) throws CoreException { monitor = Policy.monitorFor(monitor); try { String msg = Policy.bind("resources.closing.1", getFullPath().toString()); //$NON-NLS-1$ monitor.beginTask(msg, Policy.totalWork); try { workspace.prepareOperation(); ResourceInfo info = getResourceInfo(false, false); int flags = getFlags(info); checkExists(flags, true); monitor.subTask(msg); if (!isOpen(flags)) return; // Signal that this resource is about to be closed. Do this at the very // beginning so that infrastructure pieces have a chance to do clean up // while the resources still exist. // Do this before the begin to prevent lifecycle participants to change the tree. workspace.broadcastEvent(LifecycleEvent.newEvent(LifecycleEvent.PRE_PROJECT_CLOSE, this)); workspace.beginOperation(true); // flush the build order early in case there is a problem workspace.flushBuildOrder(); IProgressMonitor sub = Policy.subMonitorFor(monitor, Policy.opWork / 2, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL); IStatus saveStatus = workspace.getSaveManager().save(ISaveContext.PROJECT_SAVE, this, sub); internalClose(); monitor.worked(Policy.opWork / 2); if (saveStatus != null && !saveStatus.isOK()) throw new ResourceException(saveStatus); } catch (OperationCanceledException e) { workspace.getWorkManager().operationCanceled(); throw e; } finally { workspace.endOperation(true, Policy.subMonitorFor(monitor, Policy.buildWork)); } } finally { monitor.done(); } } /** * @see IResource#copy */ public void copy(IProjectDescription destination, int updateFlags, IProgressMonitor monitor) throws CoreException { // FIXME - the logic here for copying projects needs to be moved to Resource.copy // so that IResource.copy(IProjectDescription,int,IProgressMonitor) works properly for // projects and honours all update flags Assert.isNotNull(destination); internalCopy(destination, updateFlags, monitor); } /** * @see IResource#copy */ public void copy(IPath destination, int updateFlags, IProgressMonitor monitor) throws CoreException { // FIXME - the logic here for copying projects needs to be moved to Resource.copy // so that IResource.copy(IPath,int,IProgressMonitor) works properly for // projects and honours all update flags monitor = Policy.monitorFor(monitor); if (destination.segmentCount() == 1) { // copy project to project String projectName = destination.segment(0); IProjectDescription desc = getDescription(); desc.setName(projectName); desc.setLocation(null); internalCopy(desc, updateFlags, monitor); } else { // will fail since we're trying to copy a project to a non-project checkCopyRequirements(destination, IResource.PROJECT, updateFlags); } } protected void copyMetaArea(IProject source, IProject destination, IProgressMonitor monitor) throws CoreException { java.io.File oldMetaArea = workspace.getMetaArea().locationFor(source).toFile(); java.io.File newMetaArea = workspace.getMetaArea().locationFor(destination).toFile(); getLocalManager().getStore().copy(oldMetaArea, newMetaArea, IResource.DEPTH_INFINITE, monitor); } /** * @see IProject#create */ public void create(IProjectDescription description, IProgressMonitor monitor) throws CoreException { monitor = Policy.monitorFor(monitor); try { monitor.beginTask(Policy.bind("resources.create"), Policy.totalWork); //$NON-NLS-1$ checkValidPath(path, PROJECT); try { workspace.prepareOperation(); checkDoesNotExist(); if (description != null) checkDescription(this, description, false); workspace.broadcastEvent(LifecycleEvent.newEvent(LifecycleEvent.PRE_PROJECT_CREATE, this)); workspace.beginOperation(true); workspace.createResource(this, false); workspace.getMetaArea().create(this); ProjectInfo info = (ProjectInfo) getResourceInfo(false, true); // setup description to obtain project location ProjectDescription desc; if (description == null) { desc = new ProjectDescription(); } else { desc = (ProjectDescription)((ProjectDescription)description).clone(); } desc.setName(getName()); info.setDescription(desc); //look for a description on disk try { if (getLocalManager().hasSavedProject(this)) { updateDescription(); //make sure the .location file is written workspace.getMetaArea().writeLocation(this); } else { //write out the project writeDescription(IResource.FORCE); } } catch (CoreException e) { workspace.deleteResource(this); throw e; } // inaccessible projects have a null modification stamp. // set this after setting the description as #setDescription // updates the stamp info.setModificationStamp(IResource.NULL_STAMP); workspace.getSaveManager().requestSnapshot(); } catch (OperationCanceledException e) { workspace.getWorkManager().operationCanceled(); throw e; } finally { workspace.endOperation(true, Policy.subMonitorFor(monitor, Policy.buildWork)); } } finally { monitor.done(); } } /** * @see IProject#create(IProgressMonitor) */ public void create(IProgressMonitor monitor) throws CoreException { create(null, monitor); } /** * @see IResource#delete(boolean, IProgressMonitor) */ public void delete(boolean force, IProgressMonitor monitor) throws CoreException { int updateFlags = force ? IResource.FORCE : IResource.NONE; delete(updateFlags, monitor); } protected void fixupAfterMoveSource() throws CoreException { workspace.deleteResource(this); } /** * @see IProject#delete(boolean, boolean, IProgressMonitor) */ public void delete(boolean deleteContent, boolean force, IProgressMonitor monitor) throws CoreException { int updateFlags = force ? IResource.FORCE : IResource.NONE; updateFlags |= deleteContent ? IResource.ALWAYS_DELETE_PROJECT_CONTENT : IResource.NEVER_DELETE_PROJECT_CONTENT; delete(updateFlags, monitor); } /** * @see IProject */ public IProjectDescription getDescription() throws CoreException { ResourceInfo info = getResourceInfo(false, false); checkAccessible(getFlags(info)); return (IProjectDescription) ((ProjectInfo) info).getDescription().clone(); } /** * @see IProject#getNature */ public IProjectNature getNature(String natureID) throws CoreException { // Has it already been initialized? ProjectInfo info = (ProjectInfo) getResourceInfo(false, false); checkAccessible(getFlags(info)); IProjectNature nature = info.getNature(natureID); if (nature == null) { // Not initialized yet. Does this project have the nature? if (!hasNature(natureID)) return null; nature = workspace.getNatureManager().createNature(this, natureID); info.setNature(natureID, nature); } return nature; } /** * @see IResource#getParent */ public IContainer getParent() { return workspace.getRoot(); } /** * @see IProject */ public IPath getPluginWorkingLocation(IPluginDescriptor plugin) { if (!exists()) return null; IPath result = workspace.getMetaArea().getWorkingLocation(this, plugin); result.toFile().mkdirs(); return result; } /** * @see IResource#getProject */ public IProject getProject() { return this; } /** * @see IResource#getProjectRelativePath */ public IPath getProjectRelativePath() { return Path.EMPTY; } /** * @see IResource#getRawLocation */ public IPath getRawLocation() { ProjectDescription description = internalGetDescription(); return description == null ? null : description.getLocation(); } /* * @see IProject */ public IProject[] getReferencedProjects() throws CoreException { + ResourceInfo info = getResourceInfo(false, false); + checkAccessible(getFlags(info)); return ((ProjectDescription) internalGetDescription()).getReferencedProjects(true); } /** * @see IProject */ public IProject[] getReferencingProjects() { IProject[] projects = workspace.getRoot().getProjects(); List result = new ArrayList(projects.length); for (int i = 0; i < projects.length; i++) { Project project = (Project) projects[i]; if (!project.isAccessible()) continue; IProject[] references = project.internalGetDescription().getReferencedProjects(false); for (int j = 0; j < references.length; j++) if (references[j].equals(this)) { result.add(projects[i]); break; } } return (IProject[]) result.toArray(new IProject[result.size()]); } /** * @see IResource#getType */ public int getType() { return PROJECT; } /** * @see IProject#hasNature */ public boolean hasNature(String natureID) throws CoreException { checkAccessible(getFlags(getResourceInfo(false, false))); // use #internal method to avoid copy but still throw an // exception if the resource doesn't exist. IProjectDescription desc = internalGetDescription(); if (desc == null) checkAccessible(NULL_FLAG); return desc.hasNature(natureID); } /** * Closes the project. This is called during restore when there is a failure * to read the project description. Since it is called during workspace restore, * it cannot start any operations. */ protected void internalClose() throws CoreException { workspace.flushBuildOrder(); getMarkerManager().removeMarkers(this, IResource.DEPTH_INFINITE); // remove each member from the resource tree. // DO NOT use resource.delete() as this will delete it from disk as well. IResource[] members = members(IContainer.INCLUDE_PHANTOMS | IContainer.INCLUDE_TEAM_PRIVATE_MEMBERS); for (int i = 0; i < members.length; i++) { Resource member = (Resource) members[i]; workspace.deleteResource(member); } // finally mark the project as closed. ResourceInfo info = getResourceInfo(false, true); info.clear(M_OPEN); info.clearSessionProperties(); info.setModificationStamp(IResource.NULL_STAMP); info.setSyncInfo(null); } protected void internalCopy(IProjectDescription destDesc, int updateFlags, IProgressMonitor monitor) throws CoreException { monitor = Policy.monitorFor(monitor); try { String message = Policy.bind("resources.copying", getFullPath().toString()); //$NON-NLS-1$ monitor.beginTask(message, Policy.totalWork); try { workspace.prepareOperation(); String destName = destDesc.getName(); IPath destPath = new Path(destName).makeAbsolute(); // The following assert method throws CoreExceptions as stated in the IProject.copy API // and assert for programming errors. See checkCopyRequirements for more information. assertCopyRequirements(destPath, IResource.PROJECT, updateFlags); Project destProject = (Project) workspace.getRoot().getProject(destName); checkDescription(destProject, destDesc, false); workspace.broadcastEvent(LifecycleEvent.newEvent(LifecycleEvent.PRE_PROJECT_COPY, this, destProject, updateFlags)); workspace.beginOperation(true); getLocalManager().refresh(this, DEPTH_INFINITE, true, Policy.subMonitorFor(monitor, Policy.opWork * 20 / 100)); // close the property store so incorrect info is not copied to the destination getPropertyManager().closePropertyStore(this); // copy the meta area for the project copyMetaArea(this, destProject, Policy.subMonitorFor(monitor, Policy.opWork * 5 / 100)); // copy just the project and not its children yet (tree node, properties) internalCopyProjectOnly(destProject, Policy.subMonitorFor(monitor, Policy.opWork * 5 / 100)); // set the description destProject.internalSetDescription(destDesc, false); // call super.copy for each child (excluding project description file) //make it a best effort copy message = Policy.bind("resources.copyProblem"); //$NON-NLS-1$ MultiStatus problems = new MultiStatus(ResourcesPlugin.PI_RESOURCES, IResourceStatus.INTERNAL_ERROR, message, null); IResource[] children = members(IContainer.INCLUDE_TEAM_PRIVATE_MEMBERS); final int childCount = children.length; final int childWork = childCount > 1 ? Policy.opWork * 50 / 100 / (childCount- 1) : 0; for (int i = 0; i < childCount; i++) { IResource child = children[i]; if (!isProjectDescriptionFile(child)) { try { child.copy(destProject.getFullPath().append(child.getName()), updateFlags, Policy.subMonitorFor(monitor, childWork)); } catch (CoreException e) { problems.merge(e.getStatus()); } } } // write out the new project description to the meta area try { destProject.writeDescription(IResource.FORCE); } catch (CoreException e) { try { destProject.delete((updateFlags & IResource.FORCE) != 0, null); } catch (CoreException e2) { // ignore and rethrow the exception that got us here } throw e; } monitor.worked(Policy.opWork * 10 / 100); // refresh local monitor.subTask(Policy.bind("resources.updating")); //$NON-NLS-1$ getLocalManager().refresh(destProject, DEPTH_INFINITE, true, Policy.subMonitorFor(monitor, Policy.opWork * 10 / 100)); if (!problems.isOK()) throw new ResourceException(problems); } catch (OperationCanceledException e) { workspace.getWorkManager().operationCanceled(); throw e; } finally { workspace.endOperation(true, Policy.subMonitorFor(monitor, Policy.buildWork)); } } finally { monitor.done(); } } /* * Copies just the project and no children. Does NOT copy the meta area. */ protected void internalCopyProjectOnly(IResource destination, IProgressMonitor monitor) throws CoreException { // close the property store so bogus values aren't copied to the destination getPropertyManager().closePropertyStore(this); // copy the tree and properties workspace.copyTree(this, destination.getFullPath(), IResource.DEPTH_ZERO, IResource.NONE, false); getPropertyManager().copy(this, destination, IResource.DEPTH_ZERO); //clear instantiated builders and natures because they reference the project handle ProjectInfo info = (ProjectInfo) ((Resource)destination).getResourceInfo(false, true); info.setBuilders(null); info.clearNatures(); //clear session properties and markers for the new project, because they shouldn't be copied. info.setMarkers(null); info.clearSessionProperties(); } /** * This is an internal helper method. This implementation is different from the API * method getDescription(). This one does not check the project accessibility. It exists * in order to prevent "chicken and egg" problems in places like the project creation. * It may return null. */ public ProjectDescription internalGetDescription() { ProjectInfo info = (ProjectInfo) getResourceInfo(false, false); if (info == null) return null; return info.getDescription(); } /** * Sets this project's description to the given value. This is the body of the * corresponding API method but is needed separately since it is used * during workspace restore (i.e., when you cannot do an operation) */ void internalSetDescription(IProjectDescription value, boolean incrementContentId) throws CoreException { ResourceInfo info = getResourceInfo(false, true); ((ProjectInfo) info).setDescription((ProjectDescription) value); if (incrementContentId) { info.incrementContentId(); //if the project is not accessible, stamp will be null and should remain null if (info.getModificationStamp() != NULL_STAMP) workspace.updateModificationStamp(info); } } public void internalSetLocal(boolean flag, int depth) throws CoreException { // do nothing for projects, but call for its children if (depth == IResource.DEPTH_ZERO) return; if (depth == IResource.DEPTH_ONE) depth = IResource.DEPTH_ZERO; // get the children via the workspace since we know that this // resource exists (it is local). IResource[] children = getChildren(this, false); for (int i = 0; i < children.length; i++) ((Resource) children[i]).internalSetLocal(flag, depth); } /** * @see IResource#isAccessible */ public boolean isAccessible() { return isOpen(); } /** * @see IResource#isLocal */ public boolean isLocal(int depth) { // the flags parm is ignored for projects so pass anything return isLocal(-1, depth); } /** * @see IResource#isLocal */ public boolean isLocal(int flags, int depth) { // don't check the flags....projects are always local if (depth == DEPTH_ZERO) return true; if (depth == DEPTH_ONE) depth = DEPTH_ZERO; // get the children via the workspace since we know that this // resource exists (it is local). IResource[] children = getChildren(this, false); for (int i = 0; i < children.length; i++) if (!children[i].isLocal(depth)) return false; return true; } /** * @see IProject#isNatureEnabled(String) */ public boolean isNatureEnabled(String natureId) throws CoreException { checkAccessible(getFlags(getResourceInfo(false, false))); return workspace.getNatureManager().isNatureEnabled(this, natureId); } /** * @see IProject */ public boolean isOpen() { ResourceInfo info = getResourceInfo(false, false); return isOpen(getFlags(info)); } /** * @see IProject */ public boolean isOpen(int flags) { return flags != NULL_FLAG && ResourceInfo.isSet(flags, M_OPEN); } /** * Returns true if this resource represents the project description file, and * false otherwise. */ protected boolean isProjectDescriptionFile(IResource resource) { return resource.getType() == IResource.FILE && resource.getFullPath().segmentCount() == 2 && resource.getName().equals(IProjectDescription.DESCRIPTION_FILE_NAME); } /** * @see IProject#move */ public void move(IProjectDescription destination, boolean force, IProgressMonitor monitor) throws CoreException { Assert.isNotNull(destination); move(destination, force ? IResource.FORCE : IResource.NONE, monitor); } /* * @see IResource#move */ public void move(IProjectDescription description, int updateFlags, IProgressMonitor monitor) throws CoreException { Assert.isNotNull(description); monitor = Policy.monitorFor(monitor); try { String message = Policy.bind("resources.moving", getFullPath().toString()); //$NON-NLS-1$ monitor.beginTask(message, Policy.totalWork); try { workspace.prepareOperation(); // The following assert method throws CoreExceptions as stated in the IResource.move API // and assert for programming errors. See checkMoveRequirements for more information. if (!getName().equals(description.getName())) { IPath path = Path.ROOT.append(description.getName()); assertMoveRequirements(path, IResource.PROJECT, updateFlags); } IProject destination = workspace.getRoot().getProject(description.getName()); checkDescription(destination, description, true); workspace.beginOperation(true); message = Policy.bind("resources.moveProblem"); //$NON-NLS-1$ MultiStatus status = new MultiStatus(ResourcesPlugin.PI_RESOURCES, IStatus.ERROR, message, null); ResourceTree tree = new ResourceTree(status, updateFlags); IMoveDeleteHook hook = workspace.getMoveDeleteHook(); workspace.broadcastEvent(LifecycleEvent.newEvent(LifecycleEvent.PRE_PROJECT_MOVE, this, destination, updateFlags)); if (!hook.moveProject(tree, this, description, updateFlags, Policy.subMonitorFor(monitor, Policy.opWork/2))) tree.standardMoveProject(this, description, updateFlags, Policy.subMonitorFor(monitor, Policy.opWork/2)); // Invalidate the tree for further use by clients. tree.makeInvalid(); if (!tree.getStatus().isOK()) throw new ResourceException(tree.getStatus()); } catch (OperationCanceledException e) { workspace.getWorkManager().operationCanceled(); throw e; } finally { workspace.endOperation(true, Policy.subMonitorFor(monitor, Policy.buildWork)); } } finally { monitor.done(); } } /** * @see IProject */ public void open(IProgressMonitor monitor) throws CoreException { monitor = Policy.monitorFor(monitor); try { String msg = Policy.bind("resources.opening.1", getFullPath().toString()); //$NON-NLS-1$ monitor.beginTask(msg, Policy.totalWork); monitor.subTask(msg); try { workspace.prepareOperation(); ProjectInfo info = (ProjectInfo)getResourceInfo(false, false); int flags = getFlags(info); checkExists(flags, true); if (isOpen(flags)) return; workspace.beginOperation(true); // flush the build order early in case there is a problem workspace.flushBuildOrder(); info = (ProjectInfo)getResourceInfo(false, true); info.set(M_OPEN); // the M_USED flag is used to indicate the difference between opening a project // for the first time and opening it from a previous close (restoring it from disk) if (info.isSet(M_USED)) { workspace.getSaveManager().restore(this, Policy.subMonitorFor(monitor, Policy.opWork * 30 / 100)); } else { info.set(M_USED); //reconcile any links in the project description reconcileLinks(info.getDescription()); workspace.updateModificationStamp(info); } startup(); monitor.worked(Policy.opWork * 20 / 100); refreshLocal(DEPTH_INFINITE, Policy.subMonitorFor(monitor, Policy.opWork * 50 / 100)); } catch (OperationCanceledException e) { workspace.getWorkManager().operationCanceled(); throw e; } finally { workspace.endOperation(true, Policy.subMonitorFor(monitor, Policy.buildWork)); } } finally { monitor.done(); } } /** * The project description file has changed on disk, resulting in a changed * set of linked resources. Perform the necessary creations and deletions of * links to bring the links in sync with those described in the project description. * @param newDescription the new project description that may have * changed link descriptions. * @param status ok if everything went well, otherwise an ERROR multistatus * describing the problems encountered. */ public IStatus reconcileLinks(ProjectDescription newDescription) { HashMap newLinks = newDescription.getLinks(); IResource[] children = null; try { children = members(); } catch (CoreException e) { return e.getStatus(); } String msg = Policy.bind("links.errorLinkReconcile"); //$NON-NLS-1$ MultiStatus status = new MultiStatus(ResourcesPlugin.PI_RESOURCES, IResourceStatus.OPERATION_FAILED, msg, null); //walk over old linked resources and remove those that are no longer defined for (int i = 0; i < children.length; i++) { Resource oldLink = (Resource)children[i]; if (!oldLink.isLinked()) continue; LinkDescription newLink = null; if (newLinks != null) newLink = (LinkDescription)newLinks.get(oldLink.getName()); //if the new link is missing, or has different location or gender, then remove old link if (newLink == null || !newLink.getLocation().equals(oldLink.getLocation()) || newLink.getType() != oldLink.getType()) { try { oldLink.delete(IResource.NONE, null); } catch (CoreException e) { status.merge(e.getStatus()); } } } //walk over new links and create if necessary if (newLinks == null) return status; for (Iterator it = newLinks.values().iterator(); it.hasNext();) { LinkDescription newLink = (LinkDescription) it.next(); IResource existing = findMember(newLink.getName()); if (existing != null) { if (!existing.isLinked()) //cannot create a link if a normal resource is blocking it status.add(new ResourceStatus(IResourceStatus.RESOURCE_EXISTS, existing.getFullPath(), msg)); } else { //no conflicting old resource, just create the new link try { Resource toLink = newLink.getType() == IResource.FILE ? (Resource)getFile(newLink.getName()) : (Resource)getFolder(newLink.getName()); toLink.createLink(newLink.getLocation(), IResource.ALLOW_MISSING_LOCAL, null); } catch (CoreException e) { status.merge(e.getStatus()); } } } return status; } protected void renameMetaArea(IProject source, IProject destination, IProgressMonitor monitor) throws CoreException { java.io.File oldMetaArea = workspace.getMetaArea().locationFor(source).toFile(); java.io.File newMetaArea = workspace.getMetaArea().locationFor(destination).toFile(); getLocalManager().getStore().move(oldMetaArea, newMetaArea, false, monitor); } /** * @see IProject */ public void setDescription(IProjectDescription description, int updateFlags, IProgressMonitor monitor) throws CoreException { // FIXME - update flags should be honoured: // KEEP_HISTORY means capture .project file in local history // FORCE means overwrite any existing .project file monitor = Policy.monitorFor(monitor); try { monitor.beginTask(Policy.bind("resources.setDesc"), Policy.totalWork); //$NON-NLS-1$ try { workspace.prepareOperation(); ResourceInfo info = getResourceInfo(false, false); checkAccessible(getFlags(info)); //If we're out of sync and !FORCE, then fail. //If the file is missing, we want to write the new description then throw an exception. boolean hadSavedDescription = true; if (((updateFlags & IResource.FORCE) == 0)) { hadSavedDescription = getLocalManager().hasSavedProject(this); if (hadSavedDescription && !getLocalManager().isDescriptionSynchronized(this)) { String message = Policy.bind("resources.projectDescSync", getName()); //$NON-NLS-1$ throw new ResourceException(IResourceStatus.OUT_OF_SYNC_LOCAL, getFullPath(), message, null); } } //see if we have an old .prj file if (!hadSavedDescription) hadSavedDescription = workspace.getMetaArea().hasSavedProject(this); workspace.broadcastEvent(LifecycleEvent.newEvent(LifecycleEvent.PRE_PROJECT_CHANGE, this)); workspace.beginOperation(true); MultiStatus status = basicSetDescription((ProjectDescription) description); if (hadSavedDescription && !status.isOK()) throw new CoreException(status); //write the new description to the .project file writeDescription(internalGetDescription(), updateFlags); info = getResourceInfo(false, true); info.incrementContentId(); workspace.updateModificationStamp(info); if (!hadSavedDescription) { String msg = Policy.bind("resources.missingProjectMetaRepaired", getName()); //$NON-NLS-1$ status.merge(new ResourceStatus(IResourceStatus.MISSING_DESCRIPTION_REPAIRED, getFullPath(), msg)); } if (!status.isOK()) throw new CoreException(status); } finally { workspace.endOperation(true, Policy.subMonitorFor(monitor, Policy.buildWork)); } } finally { monitor.done(); } } /** * @see IProject */ public void setDescription(IProjectDescription description, IProgressMonitor monitor) throws CoreException { // funnel all operations to central method setDescription(description, IResource.KEEP_HISTORY, monitor); } /** * Restore the non-persisted state for the project. For example, read and set * the description from the local meta area. Also, open the property store etc. * This method is used when an open project is restored and so emulates * the behaviour of open(). */ protected void startup() throws CoreException { if (!isOpen()) return; workspace.broadcastEvent(LifecycleEvent.newEvent(LifecycleEvent.PRE_PROJECT_OPEN, this)); } /** * @see IResource */ public void touch(IProgressMonitor monitor) throws CoreException { monitor = Policy.monitorFor(monitor); try { String message = Policy.bind("resource.touch", getFullPath().toString()); //$NON-NLS-1$ monitor.beginTask(message, Policy.totalWork); try { workspace.prepareOperation(); workspace.broadcastEvent(LifecycleEvent.newEvent(LifecycleEvent.PRE_PROJECT_CHANGE, this)); workspace.beginOperation(true); super.touch(Policy.subMonitorFor(monitor, Policy.opWork)); } catch (OperationCanceledException e) { workspace.getWorkManager().operationCanceled(); throw e; } finally { workspace.endOperation(true, Policy.subMonitorFor(monitor, Policy.buildWork)); } } finally { monitor.done(); } } /** * The project description file on disk is better than the description in memory. * Make sure the project description in memory is synchronized with the * description file contents. */ protected void updateDescription() throws CoreException { if (ProjectDescription.isWriting) return; ProjectDescription.isReading = true; try { workspace.broadcastEvent(LifecycleEvent.newEvent(LifecycleEvent.PRE_PROJECT_CHANGE, this)); ProjectDescription description = getLocalManager().read(this, false); //links can only be created if the project is open if (isOpen()) reconcileLinks(description); internalSetDescription(description, true); } finally { ProjectDescription.isReading = false; } } /** * Writes the project description file to disk. This is the only method * that should ever be writing the description, because it ensures that * the description isn't then immediately discovered as an incoming * change and read back from disk. */ public void writeDescription(int updateFlags) throws CoreException { writeDescription(internalGetDescription(), updateFlags); } /** * Writes the project description file to disk. This is the only method * that should ever be writing the description, because it ensures that * the description isn't then immediately discovered as an incoming * change and read back from disk. */ public void writeDescription(IProjectDescription description, int updateFlags) throws CoreException { if (ProjectDescription.isReading) return; ProjectDescription.isWriting = true; try { getLocalManager().internalWrite(this, description, updateFlags); } finally { ProjectDescription.isWriting = false; } } }
true
false
null
null
diff --git a/embedded/opendj-embedded-server/src/main/java/org/codice/opendj/embedded/server/LDAPManager.java b/embedded/opendj-embedded-server/src/main/java/org/codice/opendj/embedded/server/LDAPManager.java index 97a8dbc..bce0a2b 100644 --- a/embedded/opendj-embedded-server/src/main/java/org/codice/opendj/embedded/server/LDAPManager.java +++ b/embedded/opendj-embedded-server/src/main/java/org/codice/opendj/embedded/server/LDAPManager.java @@ -1,703 +1,694 @@ /** * Copyright (c) Codice Foundation * * This is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either * version 3 of the License, or 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 Lesser General Public License for more details. A copy of the GNU Lesser General Public License is distributed along with this program and can be found at * <http://www.gnu.org/licenses/lgpl.html>. * **/ package org.codice.opendj.embedded.server; -import org.apache.commons.io.FileDeleteStrategy; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.opends.messages.Message; import org.opends.server.api.Backend; import org.opends.server.config.ConfigException; import org.opends.server.core.DirectoryServer; import org.opends.server.core.LockFileManager; import org.opends.server.types.DirectoryEnvironmentConfig; import org.opends.server.types.DirectoryException; import org.opends.server.types.InitializationException; import org.opends.server.types.LDIFImportConfig; import org.opends.server.types.LDIFImportResult; import org.opends.server.util.EmbeddedUtils; import org.osgi.framework.BundleContext; import org.slf4j.LoggerFactory; import org.slf4j.ext.XLogger; import org.slf4j.ext.XLogger.Level; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.StringReader; import java.io.StringWriter; import java.net.URL; import java.util.Enumeration; import java.util.Map; import java.util.Map.Entry; import java.util.Set; /** * Manages the starting and stopping of an embedded LDAP server. Utilizes OpenDJ * as the server software with a Berkeley DB Java Edition backend. * */ public class LDAPManager { private static final int DEFAULT_LDAP_PORT = 1389; private static final int DEFAULT_LDAPS_PORT = 1636; private static final int DEFAULT_ADMIN_PORT = 4444; private static final String BASE_LDIF_STR = "base.ldif"; private static final String DEFAULT_CONFIG_LOC = "/config/config.ldif"; private static final String DEFAULT_ADMIN_BACKEND_LOC = "/config/admin-backend.ldif"; private static final String DEFAULT_SCHEMA_LOC = "/config/schema/"; private static final String DEFAULT_UPGRADE_SCHEMA_LOC = "/config/upgrade/schema.ldif.8102"; private XLogger logger = new XLogger(LoggerFactory.getLogger(LDAPManager.class)); private String dataPath = "etc/org.codice.opendj/ldap"; private String installDir; private BundleContext context; private boolean isFreshInstall; private static final String DEFAULT_DB_ID = "userRoot"; /** * Enumeration used to describe the various types of connectors used in the * LDAP server. This is used to keep track of their current status (ports) * and also variables in the config file. * */ private enum ConnectorType { LDAP( "LDAP", "ldap.port", "ldap.enable", DEFAULT_LDAP_PORT ), LDAPS( "LDAPS", "ldaps.port", "ldaps.enable", DEFAULT_LDAPS_PORT ), ADMIN( "ADMIN", "admin.port", "admin.enable", DEFAULT_ADMIN_PORT ); private String connectorName; private String portVariable; private String enableVariable; private int currentPort; private int defaultPort; /** * Default constructor for a connector. * * @param connectorName Name of the connector (ie LDAP) that will be * used in logs. * @param portVariable Variable for the port that is inside the config * file (ex: ldap.port) * @param enableVariable Variable for the enable setting inside the * config file (ex: ldap.enable) * @param defaultPort Default port number for the connector */ ConnectorType( String connectorName, String portVariable, String enableVariable, int defaultPort ) { this.connectorName = connectorName; this.portVariable = portVariable; this.enableVariable = enableVariable; this.currentPort = defaultPort; this.defaultPort = defaultPort; } } /** * Default constructor. Uses a {@link BundleContext} to retrieve files * located inside the bundle. * * @param context Used to obtain {@link InputStream} for files contain * within the bundle resources. */ public LDAPManager( BundleContext context ) { this.context = context; } /** * Starts the underlying LDAP server. This method is set in blueprint and is * used when the bundle is being started. * * @throws LDAPException Generic error thrown when LDAP server is unable to * start. Usually thrown if default files could not be copied * over or there is a port conflict on the system. */ public void startServer() throws LDAPException { logger.info("Starting LDAP Server Configuration."); File installFile = new File(dataPath); installDir = installFile.getAbsolutePath(); if (installFile.exists()) { isFreshInstall = false; logger.debug("Configuration already exists at {}, not setting up defaults.", installDir); } else { isFreshInstall = true; logger.debug("No initial configuration found, setting defaults."); createDirectory(installDir); logger.info("Storing LDAP configuration at: " + installDir); logger.info("Copying default files to configuration location."); copyDefaultFiles(); } try { // General Configuration DirectoryEnvironmentConfig serverConfig = new DirectoryEnvironmentConfig(); serverConfig.setServerRoot(installFile); serverConfig.setDisableConnectionHandlers(false); serverConfig.setMaintainConfigArchive(false); logger.debug("Starting LDAP Server."); EmbeddedUtils.startServer(serverConfig); } catch (InitializationException ie) { LDAPException le = new LDAPException("Could not initialize configuration for LDAP server.", ie); logger.throwing(Level.WARN, le); throw le; } catch (ConfigException ce) { LDAPException le = new LDAPException("Error while starting embedded server.", ce); logger.throwing(Level.WARN, le); throw le; } // post start tasks if first time being started if (isFreshInstall) { InputStream defaultLDIF = null; try { //we use the find because that searches fragments too Enumeration<URL> entries = context.getBundle().findEntries("/", "default-*.ldif", false); if(entries != null) { while(entries.hasMoreElements()) { URL url = entries.nextElement(); defaultLDIF = url.openStream(); logger.debug("Installing default LDIF file: "+url); // load into backend loadLDIF(defaultLDIF); } } } catch (IOException ioe) { // need to make sure that the server is stopped on error logger.warn("Error encountered during LDIF import, stopping server and cleaning up."); stopServer(); throw new LDAPException("Error encountered during LDIF import, stopping server and cleaning up.", ioe); } catch (LDAPException le) { // need to make sure that the server is stopped on error logger.warn("Error encountered during LDIF import, stopping server and cleaning up."); stopServer(); throw le; } finally { IOUtils.closeQuietly(defaultLDIF); } } logger.info("LDAP server successfully started."); } /** * Stops the underlying LDAP server. This method is set in blueprint and is * used when the bundle is being stopped. */ public void stopServer() throws LDAPException { logger.info("Stopping LDAP Server"); if (EmbeddedUtils.isRunning()) { EmbeddedUtils.stopServer(LDAPManager.class.getName(), Message.EMPTY); - try { - File lockDir = new File(installDir+"/locks"); - if (lockDir.exists()) - { - for (File file : lockDir.listFiles()) { - FileDeleteStrategy.FORCE.delete(file); - } - } - } catch (IOException ioe) + StringBuilder lockReleaseError = new StringBuilder(); + if (!LockFileManager.releaseLock(LockFileManager.getServerLockFileName(), lockReleaseError)) { - LDAPException le = new LDAPException("Could not delete locks directory", ioe); - logger.throwing(Level.WARN, le); - throw le; + logger.warn("Could not release the main server lock file. You may need to terminate the JVM to " + + "restart the server. ERROR: {}", lockReleaseError.toString()); } logger.info("LDAP Server successfully stopped."); } else { logger.info("Server was not started, it is still stopped."); } } /** * Restarts the underlying LDAP server. This method calls stopServer and * then startServer. It does not use the embedded LDAP server's restart * command due to a system.exit() that is in it. * * @throws LDAPException */ public void restartServer() throws LDAPException { logger.info("--Restarting LDAP Server--"); stopServer(); startServer(); logger.info("LDAP Server successfully restarted."); } /** * Retrieves the current port set to listen for LDAP calls. This * <i>should</i> be the current listening port, but if it was just changed * it will take calling the restartServer command to re-bind to ports. * * @return the integer value of the port */ public int getLDAPPort() { return ConnectorType.LDAP.currentPort; } /** * Set the LDAP port for the server to listen on. <br/> * <br/> * <b>NOTE:</b> this will NOT automatically update the server to listen on * the new port. The configuration will need to be updated and the server * restarted for it to listen on the new port. * * @param ldapPortNumber new port to listen on. */ public void setLDAPPort( int ldapPortNumber ) { ConnectorType.LDAP.currentPort = ldapPortNumber; } /** * Retrieves the current port set to listen for LDAPS (SSL) calls. This * <i>should</i> be the current listening port, but if it was just changed * it will take calling the restartServer command to re-bind to ports. * * @return the integer value of the port */ public int getLDAPSPort() { return ConnectorType.LDAPS.currentPort; } /** * Set the LDAPS port for the server to listen on. <br/> * <br/> * <b>NOTE:</b> this will NOT automatically update the server to listen on * the new port. The configuration will need to be updated and the server * restarted for it to listen on the new port. * * @param ldapsPortNumber new port to listen on. */ public void setLDAPSPort( int ldapsPortNumber ) { ConnectorType.LDAPS.currentPort = ldapsPortNumber; } /** * Retrieves the current port set to listen for ADMIN calls. This * <i>should</i> be the current listening port, but if it was just changed * it will take calling the restartServer command to re-bind to ports. * * @return the integer value of the port */ public int getAdminPort() { return ConnectorType.ADMIN.currentPort; } /** * Set the ADMIN port for the server to listen on. <br/> * <br/> * <b>NOTE:</b> this will NOT automatically update the server to listen on * the new port. The configuration will need to be updated and the server * restarted for it to listen on the new port. * * @param adminPortNumber new port to listen on. */ public void setAdminPort( int adminPortNumber ) { ConnectorType.ADMIN.currentPort = adminPortNumber; } public String getDataPath() { return this.dataPath; } public void setDataPath(String dataPath) { this.dataPath = dataPath; } /** * Callback method to update the properties for the server. This method will * restart the server if any of the properties being updated require a * restart. * * @param properties Map of properties to be updated. * @throws LDAPException If any error occurs during the updating process, * including an error on server restart. */ public void updateCallback( Map<String, Object> properties ) throws LDAPException { boolean needsRestart = false; logger.debug("Got an update with {} items in it.", properties.size()); Set<Entry<String, Object>> entries = properties.entrySet(); for ( Entry<String, Object> curEntry : entries ) { logger.debug(curEntry.toString()); if (ConnectorType.LDAP.portVariable.equals(curEntry.getKey())) { int newPort = Integer.parseInt(curEntry.getValue().toString()); if (newPort == ConnectorType.LDAP.currentPort) { logger.debug("LDAP Port unchanged, not updating."); continue; } setLDAPPort(newPort); needsRestart = true; } else if (ConnectorType.LDAPS.portVariable.equals(curEntry.getKey())) { int newPort = Integer.parseInt(curEntry.getValue().toString()); if (newPort == ConnectorType.LDAPS.currentPort) { logger.debug("LDAPS Port unchanged, not updating."); continue; } setLDAPSPort(newPort); needsRestart = true; } else if (BASE_LDIF_STR.equals(curEntry.getKey())) { InputStream ldifStream = null; String ldifLocation = curEntry.getValue().toString(); if (ldifLocation.isEmpty()) { logger.debug("No new base ldif file, not loading."); continue; } try { ldifStream = new FileInputStream(ldifLocation); loadLDIF(ldifStream); } catch (FileNotFoundException fnfe) { logger.warn("Base LDIF file not found at {}. Could not update base entries.", ldifLocation); } finally { IOUtils.closeQuietly(ldifStream); } } else if ("dataPath".equals(curEntry.getKey())) { String newDataPath = curEntry.getValue().toString(); if (StringUtils.equals(dataPath, newDataPath)) { logger.debug("Data path unchanged, not updating."); continue; } setDataPath(newDataPath); needsRestart = true; } } if (needsRestart) { copyConfig(DEFAULT_CONFIG_LOC, installDir + DEFAULT_CONFIG_LOC); logger.debug("Calling restart to update configurations."); restartServer(); } } /** * Loads a LDIF file into the default backend db. All existing data in the * backend will be cleared and only the entries from this LDIF will be * available. * * @param ldifStream InputStream of an LDIF file to load. * @throws LDAPException Thrown if any errors occur during import process. */ private void loadLDIF( InputStream ldifStream ) throws LDAPException { LDIFImportConfig ldifConfig = null; try { ldifConfig = new LDIFImportConfig(ldifStream); ldifConfig.setAppendToExistingData(false); ldifConfig.setClearBackend(true); ldifConfig.setValidateSchema(false); ldifConfig.setSkipDNValidation(false); Backend backend = DirectoryServer.getBackend(DEFAULT_DB_ID); logger.debug("Got reference to backend: " + backend.getBackendID()); String lockFile = LockFileManager.getBackendLockFileName(backend); LockFileManager.acquireExclusiveLock(lockFile, new StringBuilder()); backend.finalizeBackend(); LDIFImportResult importResult = backend.importLDIF(ldifConfig); logger.debug("Complete result of import: " + importResult); backend.initializeBackend(); LockFileManager.releaseLock(lockFile, new StringBuilder()); logger.info(importResult.getEntriesImported() + " entries imported."); } catch (DirectoryException de) { LDAPException le = new LDAPException("Error while trying to import LDIF.", de); logger.throwing(Level.WARN, le); throw le; } catch (ConfigException ce) { LDAPException le = new LDAPException("Error with configuration while re-starting backend database.", ce); logger.throwing(Level.WARN, le); throw le; } catch (InitializationException ie) { LDAPException le = new LDAPException("Error while trying to re-initialize backend database.", ie); logger.throwing(Level.WARN, le); throw le; } finally { ldifConfig.close(); } } /** * Copies over a default set of configuration files for the LDAP server. The * server generally needs all of these files to function properly and this * method will fail if any of the individual file copies fail. * * @throws IOException Thrown when any of the file copy operations encounter * an error. This should stop the entire starting process and * prevent the server from being started. */ private void copyDefaultFiles() throws LDAPException { // Create default folder locations // Config folders createDirectory(installDir + "/config/schema"); // Lock folder createDirectory(installDir + "/locks"); // Log folder createDirectory(installDir + "/logs"); // DB folders createDirectory(installDir + "/db/userRoot"); // Upgrade folder createDirectory(installDir + "/config/upgrade"); // Default config files, main config uses a different method copyConfig(DEFAULT_CONFIG_LOC, installDir + DEFAULT_CONFIG_LOC); copyFile(DEFAULT_ADMIN_BACKEND_LOC, installDir + DEFAULT_ADMIN_BACKEND_LOC); // Default schema files // This also copies any fragment schema files copyFile(DEFAULT_SCHEMA_LOC, installDir + DEFAULT_SCHEMA_LOC, "*.ldif"); // Default upgrade schema files checks to see if schemas changed copyFile(DEFAULT_UPGRADE_SCHEMA_LOC, installDir + DEFAULT_UPGRADE_SCHEMA_LOC); } /** * Performs a copy of a config file from one area to another. This method is * for configuration files that contain variables to configure during the * copy process. Current variables are ${ldapPort} and ${ldapsPort}. * * @param from location of the original file with variables * @param to location to put the final file with variables converted. * @throws LDAPException if file does not exist or stream could not be * created */ private void copyConfig( String from, String to ) throws LDAPException { InputStream fromStream = null; StringWriter writer = new StringWriter(); OutputStream toStream = null; StringReader reader = null; try { fromStream = context.getBundle().getResource(from).openStream(); toStream = new FileOutputStream(to); IOUtils.copy(fromStream, writer); String configStr = writer.toString(); configStr = updatePort(ConnectorType.LDAP, configStr); configStr = updatePort(ConnectorType.LDAPS, configStr); configStr = updatePort(ConnectorType.ADMIN, configStr); reader = new StringReader(configStr); logger.debug("Copying {} to {}", from, to); IOUtils.copy(reader, toStream); } catch (IOException ioe) { LDAPException le = new LDAPException("Could not copy file " + from + " to " + to, ioe); logger.throwing(Level.WARN, le); throw le; } finally { IOUtils.closeQuietly(fromStream); IOUtils.closeQuietly(writer); IOUtils.closeQuietly(toStream); IOUtils.closeQuietly(reader); } } /** * Updates the port for a connector in the given configuration file. * Replaces the variables in the config file. * * @param connector Connector to update * @param configStr String containing the entire configuration file * @return The configuration file as a string with the ports updated in it. */ private String updatePort( ConnectorType connector, String configStr ) { String newConfig = configStr.trim(); if (connector.currentPort == 0) { logger.info("Disabling " + connector.connectorName + " connector."); newConfig = newConfig.replaceFirst(connector.enableVariable, Boolean.FALSE.toString()); // server does not like 0 in the config for the port, resetting it // to the default even though it is disabled newConfig = newConfig.replaceFirst(connector.portVariable, Integer.toString(connector.defaultPort)); } else { logger.info("Updating port for " + connector.connectorName + " connector to " + connector.currentPort); newConfig = newConfig.replaceFirst(connector.enableVariable, Boolean.TRUE.toString()); newConfig = newConfig.replaceFirst(connector.portVariable, Integer.toString(connector.currentPort)); } return newConfig; } /** * Performs a copy of a file from one area to another. In the context of * this class it is used to put files into the persistent cache location. * * @param from File name to copy (within the current class's context. Paths ending in "/" are assumed to be directories * @param to Area to store file, should be within the persistent cache. Paths ending in "/" are assumed to be directories * @throws IOException if file does not exist or stream could not be created */ private void copyFile( String from, String to ) throws LDAPException { if(StringUtils.isNotEmpty(from) && StringUtils.isNotEmpty(to)) { if(from.endsWith("/") && to.endsWith("/")) { copyFile(from, to, "*"); } else if(from.endsWith("/")) { copyFile(from, to.substring(0, to.lastIndexOf("/")+1), to.substring(to.lastIndexOf("/")+1)); } else if(to.endsWith("/")) { copyFile(from.substring(0, from.lastIndexOf("/")+1), to, from.substring(from.lastIndexOf("/")+1)); } else { copyFile(from.substring(0, from.lastIndexOf("/")+1), to.substring(0, to.lastIndexOf("/")+1), from.substring(from.lastIndexOf("/")+1)); } } } /** * Performs a copy of a file from one area to another. In the context of * this class it is used to put files into the persistent cache location. * * @param from File name to copy (within the current class's context * @param to Area to store file, should be within the persistent cache. * @param pattern FileFilter pattern String to search for * @throws LDAPException */ private void copyFile(String from, String to, String pattern) throws LDAPException { InputStream fromStream = null; OutputStream toStream = null; Enumeration<URL> entries = context.getBundle().findEntries(from, pattern, false); URL currentURL = null; if(entries != null) { while(entries.hasMoreElements()) { currentURL = entries.nextElement(); try { logger.debug("Copying {} to {}", currentURL, to); fromStream = currentURL.openStream(); if(to.endsWith("/")) { String urlString = currentURL.toString(); toStream = new FileOutputStream(to + urlString.substring(urlString.lastIndexOf("/") + 1)); } else { toStream = new FileOutputStream(to); } IOUtils.copy(fromStream, toStream); } catch (IOException ioe) { LDAPException le = new LDAPException("Could not copy file " + currentURL + " to " + to, ioe); logger.throwing(Level.WARN, le); throw le; } finally { IOUtils.closeQuietly(fromStream); IOUtils.closeQuietly(toStream); } } } } /** * Creates a directory (and all sub-directories). Throws an exception if * they were not all created. * * @param dir Absolute path of all of the directories to create. * @throws LDAPException Thrown if any of the underlying directories could * not be created. */ private void createDirectory( String dir ) throws LDAPException { if (!new File(dir).mkdirs()) { throw new LDAPException("Could not create folders for " + dir); } } }
false
false
null
null