diff
stringlengths
262
553k
is_single_chunk
bool
2 classes
is_single_function
bool
1 class
buggy_function
stringlengths
20
391k
fixed_function
stringlengths
0
392k
diff --git a/x10.compiler/src/x10/visit/Desugarer.java b/x10.compiler/src/x10/visit/Desugarer.java index 4b912a7b8..4cf09a065 100644 --- a/x10.compiler/src/x10/visit/Desugarer.java +++ b/x10.compiler/src/x10/visit/Desugarer.java @@ -1,858 +1,869 @@ /* * This file is part of the X10 project (http://x10-lang.org). * * This file is licensed to You under the Eclipse Public License (EPL); * 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/eclipse-1.0.php * * (C) Copyright IBM Corporation 2006-2010. */ package x10.visit; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Arrays; import polyglot.ast.Assign; import polyglot.ast.Binary; import polyglot.ast.Block; import polyglot.ast.Call; import polyglot.ast.CanonicalTypeNode; import polyglot.ast.Eval; import polyglot.ast.Expr; import polyglot.ast.Field; import polyglot.ast.FieldAssign; import polyglot.ast.FloatLit; import polyglot.ast.Formal; import polyglot.ast.IntLit; import polyglot.ast.Local; import polyglot.ast.LocalAssign; import polyglot.ast.LocalDecl; import polyglot.ast.Node; import polyglot.ast.NodeFactory; import polyglot.ast.Stmt; import polyglot.ast.TypeNode; import polyglot.ast.Unary; import polyglot.ast.New; import polyglot.ast.AmbExpr; import polyglot.ast.If; import polyglot.ast.Receiver; import polyglot.ast.ProcedureCall; import polyglot.ast.Special; import polyglot.ast.BooleanLit; import polyglot.frontend.Job; import polyglot.types.Context; import polyglot.types.LocalDef; import polyglot.types.LocalInstance; import polyglot.types.Name; import polyglot.types.SemanticException; import polyglot.types.Type; import polyglot.types.TypeSystem; import polyglot.types.Types; import polyglot.types.VarInstance; import polyglot.types.QName; import polyglot.types.ProcedureInstance; import polyglot.types.ProcedureDef; import polyglot.types.ClassType; import polyglot.types.ClassDef; import polyglot.types.Ref; import polyglot.util.CollectionUtil; import x10.util.CollectionFactory; import polyglot.util.InternalCompilerError; import polyglot.util.Position; import polyglot.visit.ContextVisitor; import polyglot.visit.NodeVisitor; import x10.X10CompilerOptions; import x10.errors.Warnings; import x10.ast.Closure; import x10.ast.DepParameterExpr; import x10.ast.ParExpr; import x10.ast.SettableAssign; import x10.ast.X10Binary_c; import x10.ast.X10Call; import x10.ast.X10CanonicalTypeNode; import x10.ast.X10Cast; import x10.ast.X10Instanceof; import x10.ast.X10Special; import x10.ast.X10Unary_c; import x10.ast.X10ClassDecl_c; import x10.constraint.XFailure; import x10.constraint.XVar; import x10.types.EnvironmentCapture; import x10.types.ThisDef; import x10.types.X10ConstructorInstance; import x10.types.X10MemberDef; import x10.types.MethodInstance; import x10.types.TypeParamSubst; import x10.types.ReinstantiatedMethodInstance; import x10.types.ReinstantiatedConstructorInstance; import x10.types.X10ConstructorInstance_c; import x10.types.ParameterType; import x10.types.checker.Converter; import x10.types.checker.PlaceChecker; import x10.types.constraints.CConstraint; import x10.types.constraints.XConstrainedTerm; import x10.util.Synthesizer; /** * Visitor to desugar the AST before code generation. * * NOTE: all the nodes created in the Desugarer must have the appropriate type information. * The NodeFactory methods do not fill in the type information. Use the helper methods available * in the Desugarer to create expressions, or see how the type information is filled in for other * types of nodes elsewhere in the Desugarer. TODO: factor out the helper methods into the * {@link Synthesizer}. */ public class Desugarer extends ContextVisitor { public Desugarer(Job job, TypeSystem ts, NodeFactory nf) { super(job, ts, nf); } private static int count; private static Name getTmp() { return Name.make("__desugarer__var__" + (count++) + "__"); } @Override public Node override(Node parent, Node n) { if (n instanceof Eval) { Stmt s = adjustEval((Eval) n); return visitEdgeNoOverride(parent, s); } return null; } @Override public Node leaveCall(Node old, Node n, NodeVisitor v) { if (n instanceof ParExpr) return visitParExpr((ParExpr) n); if (n instanceof Assign) return visitAssign((Assign) n); if (n instanceof Binary) return visitBinary((Binary) n); if (n instanceof Unary) return visitUnary((Unary) n); if (n instanceof X10Cast) return visitCast((X10Cast) n); if (n instanceof X10Instanceof) return visitInstanceof((X10Instanceof) n); if (n instanceof New) return desugarNew((New) n, this); if (n instanceof Call) return desugarCall((Call) n, this); // todo: also ctor calls (this&super), operators return n; } /** * Remove parenthesized expressions. */ protected Expr visitParExpr(ParExpr e) { return e.expr(); } // desugar binary operators private Expr visitBinary(Binary n) { return desugarBinary(n, this); } public static Expr desugarBinary(Binary n, ContextVisitor v) { Call c = X10Binary_c.desugarBinaryOp(n, v); if (c != null) { MethodInstance mi = (MethodInstance) c.methodInstance(); if (mi.error() != null) throw new InternalCompilerError("Unexpected exception when desugaring "+n, n.position(), mi.error()); return desugarCall(c, v); } return n; } private Expr getLiteral(Position pos, Type type, long val) { type = Types.baseType(type); Expr lit = null; if (ts.isIntOrLess(type)) { lit = nf.IntLit(pos, IntLit.INT, val); } else if (ts.isLong(type)) { lit = nf.IntLit(pos, IntLit.LONG, val); } else if (ts.isUInt(type)) { lit = nf.IntLit(pos, IntLit.UINT, val); } else if (ts.isULong(type)) { lit = nf.IntLit(pos, IntLit.ULONG, val); } else if (ts.isFloat(type)) { lit = nf.FloatLit(pos, FloatLit.FLOAT, val); } else if (ts.isDouble(type)) { lit = nf.FloatLit(pos, FloatLit.DOUBLE, val); } else if (ts.isChar(type)) { // Don't want to cast return (Expr) nf.IntLit(pos, IntLit.INT, val).typeCheck(this); } else throw new InternalCompilerError(pos, "Unknown literal type: "+type); lit = (Expr) lit.typeCheck(this); if (!ts.isSubtype(lit.type(), type)) { lit = nf.X10Cast(pos, nf.CanonicalTypeNode(pos, type), lit, Converter.ConversionType.PRIMITIVE).type(type); } return lit; } protected Expr getLiteral(Position pos, Type type, boolean val) { type = Types.baseType(type); if (ts.isBoolean(type)) { Type t = ts.Boolean(); t = Types.addSelfBinding(t, val ? ts.TRUE() : ts.FALSE()); return nf.BooleanLit(pos, val).type(t); } else throw new InternalCompilerError(pos, "Unknown literal type: "+type); } // ++x -> x+=1 or --x -> x-=1 private Expr unaryPre(Position pos, Unary.Operator op, Expr e) { Type ret = e.type(); Expr one = getLiteral(pos, ret, 1); Assign.Operator asgn = (op == Unary.PRE_INC) ? Assign.ADD_ASSIGN : Assign.SUB_ASSIGN; Expr a = assign(pos, e, asgn, one); a = visitAssign((Assign) a); return a; } // x++ -> (x+=1)-1 or x-- -> (x-=1)+1 private Expr unaryPost(Position pos, Unary.Operator op, Expr e) { Type ret = e.type(); Expr one = getLiteral(pos, ret, 1); Assign.Operator asgn = (op == Unary.POST_INC) ? Assign.ADD_ASSIGN : Assign.SUB_ASSIGN; Binary.Operator bin = (op == Unary.POST_INC) ? Binary.SUB : Binary.ADD; Expr incr = assign(pos, e, asgn, one); incr = visitAssign((Assign) incr); return visitBinary((Binary) nf.Binary(pos, incr, bin, one).type(ret)); } // desugar unary operators private Expr visitUnary(Unary n) { Unary.Operator op = n.operator(); if (op == Unary.PRE_DEC || op == Unary.PRE_INC) { return unaryPre(n.position(), op, n.expr()); } if (op == Unary.POST_DEC || op == Unary.POST_INC) { return unaryPost(n.position(), op, n.expr()); } return desugarUnary(n, this); } public static Expr desugarUnary(Unary n, ContextVisitor v) { Call c = X10Unary_c.desugarUnaryOp(n, v); if (c != null) { MethodInstance mi = (MethodInstance) c.methodInstance(); if (mi.error() != null) throw new InternalCompilerError("Unexpected exception when desugaring "+n, n.position(), mi.error()); return desugarCall(c, v); } return n; } // This is called from override, so we just need to transform the statement, not desugar // x++; -> ++x; or x--; -> --x; (to avoid creating an extra closure) private Stmt adjustEval(Eval n) { Position pos = n.position(); if (n.expr() instanceof Unary) { Unary e = (Unary) n.expr(); if (e.operator() == Unary.POST_DEC) return n.expr(e.operator(Unary.PRE_DEC)); if (e.operator() == Unary.POST_INC) return n.expr(e.operator(Unary.PRE_INC)); } return n; } private Assign assign(Position pos, Expr e, Assign.Operator asgn, Expr val) { return assign(pos, e, asgn, val, this); } private static Assign assign(Position pos, Expr e, Assign.Operator asgn, Expr val, ContextVisitor v) { try { Synthesizer synth = new Synthesizer(v.nodeFactory(), v.typeSystem()); return synth.makeAssign(pos, e, asgn, val, v.context()); } catch (SemanticException z) { throw new InternalCompilerError("Unexpected exception while creating assignment", pos, z); } } private Closure closure(Position pos, Type retType, List<Formal> parms, Block body) { return closure(pos, retType, parms, body, this); } private static Closure closure(Position pos, Type retType, List<Formal> parms, Block body, ContextVisitor v) { Synthesizer synth = new Synthesizer(v.nodeFactory(), v.typeSystem()); return synth.makeClosure(pos, retType, parms, body, v.context()); } public static class ClosureCaptureVisitor extends NodeVisitor { private final Context context; private final EnvironmentCapture cd; public ClosureCaptureVisitor(Context context, EnvironmentCapture cd) { this.context = context; this.cd = cd; } @Override public Node leave(Node old, Node n, NodeVisitor v) { if (n instanceof Local) { LocalInstance li = ((Local) n).localInstance(); VarInstance<?> o = context.findVariableSilent(li.name()); if (li == o || (o != null && li.def() == o.def())) { cd.addCapturedVariable(li); } } else if (n instanceof Field) { if (((Field) n).target() instanceof X10Special) { cd.addCapturedVariable(((Field) n).fieldInstance()); } } else if (n instanceof X10Special) { X10MemberDef code = (X10MemberDef) context.currentCode(); ThisDef thisDef = code.thisDef(); if (null == thisDef) { throw new InternalCompilerError(n.position(), "ClosureCaptureVisitor.leave: thisDef is null for containing code " +code); } assert (thisDef != null); cd.addCapturedVariable(thisDef.asInstance()); } return n; } } private Expr visitAssign(Assign n) { if (n instanceof SettableAssign) return visitSettableAssign((SettableAssign) n); if (n instanceof LocalAssign) return visitLocalAssign((LocalAssign) n); if (n instanceof FieldAssign) return visitFieldAssign((FieldAssign) n); return n; } public static Expr desugarAssign(Assign n, ContextVisitor v) { if (n instanceof SettableAssign) return desugarSettableAssign((SettableAssign) n, v); if (n instanceof LocalAssign) return desugarLocalAssign((LocalAssign) n, v); if (n instanceof FieldAssign) return desugarFieldAssign((FieldAssign) n, v); return n; } private Expr visitLocalAssign(LocalAssign n) { return desugarLocalAssign(n, this); } // x op=v -> x = x op v public static Expr desugarLocalAssign(LocalAssign n, ContextVisitor v) { Position pos = n.position(); if (n.operator() == Assign.ASSIGN) return n; Binary.Operator op = n.operator().binaryOperator(); Local left = (Local) n.left(); Expr right = n.right(); Type R = left.type(); Expr val = desugarBinary((Binary) v.nodeFactory().Binary(pos, left, op, right).type(R), v); return assign(pos, left, Assign.ASSIGN, val, v); } protected Expr visitFieldAssign(FieldAssign n) { return desugarFieldAssign(n, this); } // def n(a:T, b:S){EXPR(this,a,b)} { ... } // def this(a:T, b:S){EXPR(a,b)} { ... } // if the Call/New has a ProcedureInstance with checkGuardAtRuntime, then we do this transformation: // e.n(e1, e2) -> ((r:C, a:T, b:S)=>{if (!(EXPR(r,a,b))) throw new FailedDynamicCheckException(...); return r.n(a,b); })(e, e1, e2) // (there are two special cases: if e is empty (so it's either "this" or nothing if the "n" is static) // new X(e1, e2) -> ((a:T, b:S)=>{if (!(EXPR(a,b))) throw new FailedDynamicCheckException(...); return new X(a,b); })(e1, e2) private static Expr desugarCall(Expr expr, ContextVisitor v) { if (expr instanceof Call) return desugarCall((Call)expr, v); if (expr instanceof Binary) return desugarCall(expr, null, null, (Binary)expr, v); if (expr instanceof Unary) { Unary unary = (Unary) expr; // TODO: how to get the methodInstance out of an unary? do we even need to worry about it or is an unary always desugared into a Call (which I handle)? } if (expr instanceof SettableAssign) { SettableAssign settableAssign = (SettableAssign) expr; // todo: what about SettableAssign ? is it always desugared into a Call or ClosureCall (because I handle both cases correctly)? } return expr; } private static Expr desugarCall(Call call_c, ContextVisitor v) { return desugarCall(call_c, call_c, null, null, v); } private static Expr desugarNew(final New new_c, ContextVisitor v) { return desugarCall(new_c, null, new_c, null, v); } private static Expr addCheck(Expr booleanGuard, CConstraint constraint, final Name selfName, final NodeFactory nf, final TypeSystem ts, final Position pos) { if (constraint==null) return booleanGuard; final List<Expr> guardExpr = new Synthesizer(nf, ts).makeExpr(constraint, pos); // note: this doesn't typecheck the expression, so we're missing type info. for (Expr e : guardExpr) { e = (Expr) e.visit( new NodeVisitor() { @Override public Node override(Node n) { if (n instanceof Special){ Special special = (Special) n; if (special.kind()== Special.Kind.SELF) { assert selfName!=null; // self cannot appear in a method guard return nf.AmbExpr(pos,nf.Id(pos,selfName)); } } return null; } }); booleanGuard = nf.Binary(pos, booleanGuard, Binary.Operator.COND_AND, e).type(ts.Boolean()); } return booleanGuard; } private static <T> T reinstantiate(TypeParamSubst typeParamSubst, T t) { return typeParamSubst==null ? t : typeParamSubst.reinstantiate(t); } private static Expr desugarCall(final Expr n, final Call call_c, final New new_c, final Binary binary_c, ContextVisitor v) { final NodeFactory nf = v.nodeFactory(); final TypeSystem ts = v.typeSystem(); final Job job = v.job(); assert n!=null && (call_c==n || new_c==n || binary_c==n); ProcedureCall procCall = call_c!=null || new_c!=null ? (ProcedureCall) n : null; final ProcedureInstance<? extends ProcedureDef> procInst = binary_c!=null ? binary_c.methodInstance() : procCall.procedureInstance(); if (procInst==null || // for binary ops (like ==), the methodInstance is null !procInst.checkConstraintsAtRuntime()) return (Expr)n; Warnings.dynamicCall(v.job(), Warnings.GeneratedDynamicCheck(n.position())); final Position pos = n.position(); List<Expr> args = binary_c!=null ? Arrays.asList(binary_c.left(), binary_c.right()) : procCall.arguments(); // we shouldn't use the def, because sometimes the constraints come from the instance, // e.g., new Box[Int{self!=0}](v) // dynamically checks that v!=0 (but you can't see it in the def! only in the instance). // However, the instance has also the arguments (that exists in the context), // and for some reason formalNames of the instance doesn't return the constraint that self!=0 (and Vijay thinks it shouldn't do it anyway) // so I need to take the paramSubst and do it myself on the def. // E.g., // new Box[Int{self!=0}](i) in the instance returns a formal arg123:Int{self==arg123, arg123==i} but without i!=0 ! // so I take the original formal from the def (x:T) and do the paramSubst on it to get x:Int{self!=0} final ProcedureDef procDef = procInst.def(); TypeParamSubst typeParamSubst = procInst instanceof ReinstantiatedMethodInstance ? ((ReinstantiatedMethodInstance)procInst).typeParamSubst() : procInst instanceof ReinstantiatedConstructorInstance ? ((ReinstantiatedConstructorInstance)procInst).typeParamSubst() : null; // this can happen when procInst is X10ConstructorInstance_c (see XTENLANG_2330). But creating an empty TypeParamSubst would also work final List<Type> typeParam = procInst.typeParameters(); // note that X10ConstructorInstance_c.typeParameters returns an empty list! (there is a todo there!) if (typeParam!=null && typeParam.size()>0) { if (typeParamSubst==null) typeParamSubst = new TypeParamSubst(ts,Collections.EMPTY_LIST,Collections.EMPTY_LIST); final ArrayList<Type> newArgs = typeParamSubst.copyTypeArguments(); newArgs.addAll(typeParam); final ArrayList<ParameterType> newParams = typeParamSubst.copyTypeParameters(); newParams.addAll(procDef.typeParameters()); typeParamSubst = new TypeParamSubst(ts, newArgs,newParams); } final List<LocalDef> oldFormals = procDef.formalNames(); assert oldFormals.size()==args.size(); Expr oldReceiver = null; final Receiver target; if (binary_c!=null) target = null; else target = (call_c==null ? new_c.qualifier() : call_c.target()); if (target!=null && target instanceof Expr) { // making sure that the receiver is not a TypeNode oldReceiver = (Expr) target; args = new ArrayList<Expr>(args); args.add(0, (Expr) oldReceiver); } ArrayList<Expr> newArgs = new ArrayList<Expr>(args.size()); ArrayList<Formal> params = new ArrayList<Formal>(args.size()); - final Context closureContext = v.context().pushBlock(); + final Context context = v.context(); + final Context closureContext = context.pushBlock(); int i=0; for (Expr arg : args) { // The argument might be null, e.g., def m(b:Z) {b.x!=null} = 1; ... m(null); final LocalDef oldFormal = arg==oldReceiver ? null : oldFormals.get(oldReceiver==null ? i : i-1); Name xn = oldFormal!=null ? oldFormal.name() : Name.make("x$"+i); // to make sure it doesn't conflict/shaddow an existing field i++; final Type type = oldFormal!=null ? reinstantiate(typeParamSubst, Types.get(oldFormal.type())) : arg.type(); LocalDef xDef = ts.localDef(pos, ts.Final(), Types.ref(type), xn); Formal x = nf.Formal(pos, nf.FlagsNode(pos, ts.Final()), nf.CanonicalTypeNode(pos,type), nf.Id(pos, xn)).localDef(xDef); params.add(x); final Local local = (Local) nf.Local(pos, nf.Id(pos, xn)).localInstance(xDef.asInstance()).type(type); newArgs.add(local); closureContext.addVariable(local.localInstance()); } final Expr newReceiver = oldReceiver==null ? null : newArgs.remove(0); final ProcedureCall newProcCall; if (newReceiver==null) newProcCall = procCall; else newProcCall = (call_c!=null ? call_c.target(newReceiver) : new_c.qualifier(newReceiver)); Expr newExpr; if (binary_c!=null) newExpr = binary_c.left(newArgs.get(0)).right(newArgs.get(1)); else newExpr = (Expr) newProcCall.arguments(newArgs); // we add the guard to the body, then the return stmt. // if (!(GUARDEXPR(a,b))) throw new FailedDynamicCheckException(...); return ... final Ref<CConstraint> guardRefConstraint = procDef.guard(); Expr booleanGuard = (BooleanLit) nf.BooleanLit(pos, true).type(ts.Boolean()); if (guardRefConstraint!=null) { final CConstraint guard = reinstantiate(typeParamSubst, guardRefConstraint.get()); booleanGuard = addCheck(booleanGuard,guard, null, nf, ts, pos); } // add the constraints of the formals for (LocalDef localDef : procDef.formalNames()) { CConstraint constraint = Types.xclause(reinstantiate(typeParamSubst, Types.get(localDef.type()))); booleanGuard = addCheck(booleanGuard,constraint, localDef.name(), nf, ts, pos); } // replace old formals in depExpr with the new locals final Map<Name,Expr> old2new = CollectionFactory.newHashMap(oldFormals.size()); for (int k=0; k<newArgs.size(); k++) { Expr newE = newArgs.get(k); old2new.put(oldFormals.get(k).name(),newE); } // replace all AmbExpr with the new locals final X10TypeBuilder builder = new X10TypeBuilder(job, ts, nf); final ContextVisitor checker = new X10TypeChecker(job, ts, nf, job.nodeMemo()).context(closureContext); NodeVisitor replace = new NodeVisitor() { @Override public Node override(Node n) { if (n instanceof Special){ // if it's an outer instance, then we need to access the outer field Special special = (Special) n; TypeNode qualifer = special.qualifier(); if (qualifer==null) return newReceiver; // qualifer doesn't have type info because it was created in Synthesizer.makeExpr qualifer = (TypeNode) qualifer.visit(builder).visit(checker); ClassType ct = qualifer.type().toClass(); - final ClassDef newReceiverDef = newReceiver.type().toClass().def(); + Type receiverType = newReceiver.type(); + final Type baseType = Types.baseType(receiverType); + if (baseType instanceof ParameterType) { + final List<Type> upperBounds = ts.env(context).upperBounds(baseType, false); + receiverType = ts.Any(); + for (Type up : upperBounds) { + if (!(Types.baseType(up) instanceof ParameterType)) + receiverType = up; + } + } + final ClassDef newReceiverDef = receiverType.toClass().def(); final ClassDef qualifierDef = ct.def(); if (newReceiverDef==qualifierDef) return newReceiver; return nf.Call(pos,newReceiver, nf.Id(pos,X10ClassDecl_c.getThisMethod(newReceiverDef.fullName(),ct.fullName()))); } if (n instanceof AmbExpr) { AmbExpr amb = (AmbExpr) n; Name name = amb.name().id(); Expr newE = old2new.get(name); if (newE==null) throw new InternalCompilerError("Didn't find name="+name+ " in old2new="+old2new); return newE; } return null; } }; Expr newDep = (Expr)booleanGuard.visit(replace); // if (!newDep) throw new FailedDynamicCheckException(); return ... final Type resType = newExpr.type(); newDep = nf.Unary(pos, Unary.Operator.NOT, newDep).type(ts.Boolean()); If anIf = nf.If(pos, newDep, nf.Throw(pos, nf.New(pos, nf.TypeNodeFromQualifiedName(pos, QName.make("x10.lang.FailedDynamicCheckException")), CollectionUtil.<Expr>list(nf.StringLit(pos, newDep.toString()))).type(ts.Throwable()))); // if resType is void, then we shouldn't use return final boolean isVoid = ts.isVoid(resType); newExpr = (Expr) newExpr.visit(builder).visit(checker); anIf = (If) anIf.visit(builder).visit(checker); Block body = nf.Block(pos, anIf, isVoid ? nf.Eval(pos,newExpr) : nf.Return(pos, newExpr)); //body = (Block) body.visit(builder).visit(checker); - there is a problem type-checking the return statement Type closureRet = procInst.returnType(); Closure c = closure(pos, closureRet, params, body, v); MethodInstance ci = c.closureDef().asType().applyMethod(); return nf.ClosureCall(pos, c, args).closureInstance(ci).type(resType); } // T.f op=v -> T.f = T.f op v or e.f op=v -> ((x:E,y:T)=>x.f=x.f op y)(e,v) public static Expr desugarFieldAssign(FieldAssign n, ContextVisitor v) { NodeFactory nf = v.nodeFactory(); TypeSystem ts = v.typeSystem(); Position pos = n.position(); if (n.operator() == Assign.ASSIGN) return n; Binary.Operator op = n.operator().binaryOperator(); Field left = (Field) n.left(); Expr right = n.right(); Type R = left.type(); if (left.flags().isStatic()) { Expr val = desugarBinary((Binary) nf.Binary(pos, left, op, right).type(R), v); return assign(pos, left, Assign.ASSIGN, val, v); } Expr e = (Expr) left.target(); Type E = e.type(); List<Formal> parms = new ArrayList<Formal>(); Name xn = Name.make("x"); LocalDef xDef = ts.localDef(pos, ts.Final(), Types.ref(E), xn); Formal x = nf.Formal(pos, nf.FlagsNode(pos, ts.Final()), nf.CanonicalTypeNode(pos, E), nf.Id(pos, xn)).localDef(xDef); parms.add(x); Name yn = Name.make("y"); Type T = right.type(); LocalDef yDef = ts.localDef(pos, ts.Final(), Types.ref(T), yn); Formal y = nf.Formal(pos, nf.FlagsNode(pos, ts.Final()), nf.CanonicalTypeNode(pos, T), nf.Id(pos, yn)).localDef(yDef); parms.add(y); Expr lhs = nf.Field(pos, nf.Local(pos, nf.Id(pos, xn)).localInstance(xDef.asInstance()).type(E), nf.Id(pos, left.name().id())).fieldInstance(left.fieldInstance()).type(R); Expr val = desugarBinary((Binary) nf.Binary(pos, lhs, op, nf.Local(pos, nf.Id(pos, yn)).localInstance(yDef.asInstance()).type(T)).type(R), v); Expr res = assign(pos, lhs, Assign.ASSIGN, val, v); Block body = nf.Block(pos, nf.Return(pos, res)); Closure c = closure(pos, R, parms, body, v); MethodInstance ci = c.closureDef().asType().applyMethod(); List<Expr> args = new ArrayList<Expr>(); args.add(0, e); args.add(right); return nf.ClosureCall(pos, c, args).closureInstance(ci).type(R); } protected Expr visitSettableAssign(SettableAssign n) { return desugarSettableAssign(n, this); } // a(i)=v -> a.operator()=(i,v) or a(i)op=v -> ((x:A,y:I,z:T)=>x.operator()=(y,x.operator()(y) op z))(a,i,v) public static Expr desugarSettableAssign(SettableAssign n, ContextVisitor v) { NodeFactory nf = v.nodeFactory(); TypeSystem ts = v.typeSystem(); Position pos = n.position(); MethodInstance mi = n.methodInstance(); List<Expr> args = new ArrayList<Expr>(n.index()); Expr a = n.array(); if (n.operator() == Assign.ASSIGN) { args.add(n.right()); return desugarCall(nf.Call(pos, a, nf.Id(pos, mi.name()), args).methodInstance(mi).type(mi.returnType()), v); } Binary.Operator op = n.operator().binaryOperator(); X10Call left = (X10Call) n.left(); MethodInstance ami = left.methodInstance(); List<Formal> parms = new ArrayList<Formal>(); Name xn = Name.make("x"); Type aType = a.type(); assert (ts.isSubtype(aType, mi.container(), v.context())); LocalDef xDef = ts.localDef(pos, ts.Final(), Types.ref(aType), xn); Formal x = nf.Formal(pos, nf.FlagsNode(pos, ts.Final()), nf.CanonicalTypeNode(pos, aType), nf.Id(pos, xn)).localDef(xDef); parms.add(x); List<Expr> idx1 = new ArrayList<Expr>(); int i = 0; assert (ami.formalTypes().size()==n.index().size()); for (Expr e : n.index()) { Type t = e.type(); Name yn = Name.make("y"+i); LocalDef yDef = ts.localDef(pos, ts.Final(), Types.ref(t), yn); Formal y = nf.Formal(pos, nf.FlagsNode(pos, ts.Final()), nf.CanonicalTypeNode(pos, t), nf.Id(pos, yn)).localDef(yDef); parms.add(y); idx1.add(nf.Local(pos, nf.Id(pos, yn)).localInstance(yDef.asInstance()).type(t)); i++; } Name zn = Name.make("z"); Type T = mi.formalTypes().get(mi.formalTypes().size()-1); Type vType = n.right().type(); assert (ts.isSubtype(ami.returnType(), T, v.context())); assert (ts.isSubtype(vType, T, v.context())); LocalDef zDef = ts.localDef(pos, ts.Final(), Types.ref(vType), zn); Formal z = nf.Formal(pos, nf.FlagsNode(pos, ts.Final()), nf.CanonicalTypeNode(pos, vType), nf.Id(pos, zn)).localDef(zDef); parms.add(z); Expr val = desugarBinary((Binary) nf.Binary(pos, desugarCall(nf.Call(pos, nf.Local(pos, nf.Id(pos, xn)).localInstance(xDef.asInstance()).type(aType), nf.Id(pos, ami.name()), idx1).methodInstance(ami).type(ami.returnType()), v), op, nf.Local(pos, nf.Id(pos, zn)).localInstance(zDef.asInstance()).type(vType)).type(T), v); Type rType = val.type(); Name rn = Name.make("r"); LocalDef rDef = ts.localDef(pos, ts.Final(), Types.ref(rType), rn); LocalDecl r = nf.LocalDecl(pos, nf.FlagsNode(pos, ts.Final()), nf.CanonicalTypeNode(pos, rType), nf.Id(pos, rn), val).localDef(rDef); List<Expr> args1 = new ArrayList<Expr>(idx1); args1.add(nf.Local(pos, nf.Id(pos, rn)).localInstance(rDef.asInstance()).type(rType)); Expr res = desugarCall(nf.Call(pos, nf.Local(pos, nf.Id(pos, xn)).localInstance(xDef.asInstance()).type(aType), nf.Id(pos, mi.name()), args1).methodInstance(mi).type(mi.returnType()), v); Block block = nf.Block(pos, r, nf.Eval(pos, res), nf.Return(pos, nf.Local(pos, nf.Id(pos, rn)).localInstance(rDef.asInstance()).type(rType))); Closure c = closure(pos, rType, parms, block, v); MethodInstance ci = c.closureDef().asType().applyMethod(); args.add(0, a); args.add(n.right()); return desugarCall(nf.ClosureCall(pos, c, args).closureInstance(ci).type(rType), v); } /** * Concatenates the given list of clauses with &&, creating a conjunction. * Any occurrence of "self" in the list of clauses is replaced by self. */ private Expr conjunction(Position pos, List<Expr> clauses, Expr self) { if (clauses.isEmpty()) { // FIXME: HACK: need to ensure that source expressions are preserved return getLiteral(pos, ts.Boolean(), true); } assert clauses.size() > 0; Substitution<Expr> subst = new Substitution<Expr>(Expr.class, Collections.singletonList(self)) { protected Expr subst(Expr n) { if (n instanceof X10Special && ((X10Special) n).kind() == X10Special.SELF) return by.get(0); return n; } }; Expr left = null; for (Expr clause : clauses) { Expr right = (Expr) clause.visit(subst); right = (Expr) right.visit(this); if (left == null) left = right; else { left = nf.Binary(pos, left, Binary.COND_AND, right).type(ts.Boolean()); left = visitBinary((Binary) left); } } return left; } private DepParameterExpr getClause(TypeNode tn) { Type t = tn.type(); if (tn instanceof X10CanonicalTypeNode) { CConstraint c = Types.xclause(t); if (c == null || c.valid()) return null; XConstrainedTerm here = context().currentPlaceTerm(); if (here != null && here.term() instanceof XVar) { try { c = c.substitute(PlaceChecker.here(), (XVar) here.term()); } catch (XFailure e) { } } DepParameterExpr res = nf.DepParameterExpr(tn.position(), new Synthesizer(nf, ts).makeExpr(c, tn.position())); res = (DepParameterExpr) res.visit(new X10TypeBuilder(job, ts, nf)).visit(new X10TypeChecker(job, ts, nf, job.nodeMemo()).context(context().pushDepType(tn.typeRef()))); return res; } throw new InternalCompilerError("Unknown type node type: "+tn.getClass(), tn.position()); } private TypeNode stripClause(TypeNode tn) { Type t = tn.type(); if (tn instanceof X10CanonicalTypeNode) { X10CanonicalTypeNode ctn = (X10CanonicalTypeNode) tn; Type baseType = Types.baseType(t); if (baseType != t) { return ctn.typeRef(Types.ref(baseType)); } return ctn; } throw new InternalCompilerError("Unknown type node type: "+tn.getClass(), tn.position()); } // e as T{c} -> ((x:T):T{c}=>{if (x!=null&&!c[self/x]) throwCCE(); return x;})(e as T) private Expr visitCast(X10Cast n) { // We give the DYNAMIC_CALLS warning here (and not in type-checking), because we create a lot of temp cast nodes in the process that are discarded later. if (n.conversionType()==Converter.ConversionType.DESUGAR_LATER) { Warnings.dynamicCall(job(), Warnings.CastingExprToType(n.expr(),n.type(),n.position())); n = n.conversionType(Converter.ConversionType.CHECKED); } Position pos = n.position(); Expr e = n.expr(); TypeNode tn = n.castType(); Type ot = tn.type(); DepParameterExpr depClause = getClause(tn); tn = stripClause(tn); X10CompilerOptions opts = (X10CompilerOptions) job.extensionInfo().getOptions(); if (depClause == null || opts.x10_config.NO_CHECKS) return n.castType(tn); Name xn = getTmp(); Type t = tn.type(); // the base type of the cast LocalDef xDef = ts.localDef(pos, ts.Final(), Types.ref(t), xn); Formal x = nf.Formal(pos, nf.FlagsNode(pos, ts.Final()), nf.CanonicalTypeNode(pos, t), nf.Id(pos, xn)).localDef(xDef); Expr xl = nf.Local(pos, nf.Id(pos, xn)).localInstance(xDef.asInstance()).type(t); List<Expr> condition = depClause.condition(); Expr cond = nf.Unary(pos, conjunction(depClause.position(), condition, xl), Unary.NOT).type(ts.Boolean()); if (ts.isSubtype(t, ts.Object(), context())) { Expr nonnull = nf.Binary(pos, xl, Binary.NE, nf.NullLit(pos).type(ts.Null())).type(ts.Boolean()); cond = nf.Binary(pos, nonnull, Binary.COND_AND, cond).type(ts.Boolean()); } Type ccet = ts.ClassCastException(); CanonicalTypeNode CCE = nf.CanonicalTypeNode(pos, ccet); Expr msg = nf.StringLit(pos, ot.toString()).type(ts.String()); X10ConstructorInstance ni; try { ni = ts.findConstructor(ccet, ts.ConstructorMatcher(ccet, Collections.singletonList(ts.String()), context())); } catch (SemanticException z) { throw new InternalCompilerError("Unexpected exception while desugaring "+n, pos, z); } Expr newCCE = nf.New(pos, CCE, Collections.singletonList(msg)).constructorInstance(ni).type(ccet); Stmt throwCCE = nf.Throw(pos, newCCE); Stmt check = nf.If(pos, cond, throwCCE); Block body = nf.Block(pos, check, nf.Return(pos, xl)); Closure c = closure(pos, ot, Collections.singletonList(x), body); c.visit(new ClosureCaptureVisitor(this.context(), c.closureDef())); //if (!c.closureDef().capturedEnvironment().isEmpty()) // System.out.println(c+" at "+c.position()+" captures "+c.closureDef().capturedEnvironment()); Expr cast = nf.X10Cast(pos, tn, e, Converter.ConversionType.CHECKED).type(t); MethodInstance ci = c.closureDef().asType().applyMethod(); return nf.ClosureCall(pos, c, Collections.singletonList(cast)).closureInstance(ci).type(ot); } // e instanceof T{c} -> ((x:F)=>x instanceof T && c[self/x as T])(e) private Expr visitInstanceof(X10Instanceof n) { Position pos = n.position(); Expr e = n.expr(); TypeNode tn = n.compareType(); DepParameterExpr depClause = getClause(tn); tn = stripClause(tn); if (depClause == null) return n; Name xn = getTmp(); Type et = e.type(); LocalDef xDef = ts.localDef(pos, ts.Final(), Types.ref(et), xn); Formal x = nf.Formal(pos, nf.FlagsNode(pos, ts.Final()), nf.CanonicalTypeNode(pos, et), nf.Id(pos, xn)).localDef(xDef); Expr xl = nf.Local(pos, nf.Id(pos, xn)).localInstance(xDef.asInstance()).type(et); Expr iof = nf.Instanceof(pos, xl, tn).type(ts.Boolean()); Expr cast = nf.X10Cast(pos, tn, xl, Converter.ConversionType.CHECKED).type(tn.type()); List<Expr> condition = depClause.condition(); Expr cond = conjunction(depClause.position(), condition, cast); Expr rval = nf.Binary(pos, iof, Binary.COND_AND, cond).type(ts.Boolean()); Block body = nf.Block(pos, nf.Return(pos, rval)); Closure c = closure(pos, ts.Boolean(), Collections.singletonList(x), body); c.visit(new ClosureCaptureVisitor(this.context(), c.closureDef())); //if (!c.closureDef().capturedEnvironment().isEmpty()) // System.out.println(c+" at "+c.position()+" captures "+c.closureDef().capturedEnvironment()); MethodInstance ci = c.closureDef().asType().applyMethod(); return nf.ClosureCall(pos, c, Collections.singletonList(e)).closureInstance(ci).type(ts.Boolean()); } public static class Substitution<T extends Node> extends NodeVisitor { protected final List<T> by; private final Class<T> cz; public Substitution(Class<T> cz, List<T> by) { this.cz = cz; this.by = by; } @SuppressWarnings("unchecked") // Casting to a generic type parameter @Override public Node leave(Node old, Node n, NodeVisitor v) { if (cz.isInstance(n)) return subst((T)n); return n; } protected T subst(T n) { return n; } } }
false
true
private static Expr desugarCall(final Expr n, final Call call_c, final New new_c, final Binary binary_c, ContextVisitor v) { final NodeFactory nf = v.nodeFactory(); final TypeSystem ts = v.typeSystem(); final Job job = v.job(); assert n!=null && (call_c==n || new_c==n || binary_c==n); ProcedureCall procCall = call_c!=null || new_c!=null ? (ProcedureCall) n : null; final ProcedureInstance<? extends ProcedureDef> procInst = binary_c!=null ? binary_c.methodInstance() : procCall.procedureInstance(); if (procInst==null || // for binary ops (like ==), the methodInstance is null !procInst.checkConstraintsAtRuntime()) return (Expr)n; Warnings.dynamicCall(v.job(), Warnings.GeneratedDynamicCheck(n.position())); final Position pos = n.position(); List<Expr> args = binary_c!=null ? Arrays.asList(binary_c.left(), binary_c.right()) : procCall.arguments(); // we shouldn't use the def, because sometimes the constraints come from the instance, // e.g., new Box[Int{self!=0}](v) // dynamically checks that v!=0 (but you can't see it in the def! only in the instance). // However, the instance has also the arguments (that exists in the context), // and for some reason formalNames of the instance doesn't return the constraint that self!=0 (and Vijay thinks it shouldn't do it anyway) // so I need to take the paramSubst and do it myself on the def. // E.g., // new Box[Int{self!=0}](i) in the instance returns a formal arg123:Int{self==arg123, arg123==i} but without i!=0 ! // so I take the original formal from the def (x:T) and do the paramSubst on it to get x:Int{self!=0} final ProcedureDef procDef = procInst.def(); TypeParamSubst typeParamSubst = procInst instanceof ReinstantiatedMethodInstance ? ((ReinstantiatedMethodInstance)procInst).typeParamSubst() : procInst instanceof ReinstantiatedConstructorInstance ? ((ReinstantiatedConstructorInstance)procInst).typeParamSubst() : null; // this can happen when procInst is X10ConstructorInstance_c (see XTENLANG_2330). But creating an empty TypeParamSubst would also work final List<Type> typeParam = procInst.typeParameters(); // note that X10ConstructorInstance_c.typeParameters returns an empty list! (there is a todo there!) if (typeParam!=null && typeParam.size()>0) { if (typeParamSubst==null) typeParamSubst = new TypeParamSubst(ts,Collections.EMPTY_LIST,Collections.EMPTY_LIST); final ArrayList<Type> newArgs = typeParamSubst.copyTypeArguments(); newArgs.addAll(typeParam); final ArrayList<ParameterType> newParams = typeParamSubst.copyTypeParameters(); newParams.addAll(procDef.typeParameters()); typeParamSubst = new TypeParamSubst(ts, newArgs,newParams); } final List<LocalDef> oldFormals = procDef.formalNames(); assert oldFormals.size()==args.size(); Expr oldReceiver = null; final Receiver target; if (binary_c!=null) target = null; else target = (call_c==null ? new_c.qualifier() : call_c.target()); if (target!=null && target instanceof Expr) { // making sure that the receiver is not a TypeNode oldReceiver = (Expr) target; args = new ArrayList<Expr>(args); args.add(0, (Expr) oldReceiver); } ArrayList<Expr> newArgs = new ArrayList<Expr>(args.size()); ArrayList<Formal> params = new ArrayList<Formal>(args.size()); final Context closureContext = v.context().pushBlock(); int i=0; for (Expr arg : args) { // The argument might be null, e.g., def m(b:Z) {b.x!=null} = 1; ... m(null); final LocalDef oldFormal = arg==oldReceiver ? null : oldFormals.get(oldReceiver==null ? i : i-1); Name xn = oldFormal!=null ? oldFormal.name() : Name.make("x$"+i); // to make sure it doesn't conflict/shaddow an existing field i++; final Type type = oldFormal!=null ? reinstantiate(typeParamSubst, Types.get(oldFormal.type())) : arg.type(); LocalDef xDef = ts.localDef(pos, ts.Final(), Types.ref(type), xn); Formal x = nf.Formal(pos, nf.FlagsNode(pos, ts.Final()), nf.CanonicalTypeNode(pos,type), nf.Id(pos, xn)).localDef(xDef); params.add(x); final Local local = (Local) nf.Local(pos, nf.Id(pos, xn)).localInstance(xDef.asInstance()).type(type); newArgs.add(local); closureContext.addVariable(local.localInstance()); } final Expr newReceiver = oldReceiver==null ? null : newArgs.remove(0); final ProcedureCall newProcCall; if (newReceiver==null) newProcCall = procCall; else newProcCall = (call_c!=null ? call_c.target(newReceiver) : new_c.qualifier(newReceiver)); Expr newExpr; if (binary_c!=null) newExpr = binary_c.left(newArgs.get(0)).right(newArgs.get(1)); else newExpr = (Expr) newProcCall.arguments(newArgs); // we add the guard to the body, then the return stmt. // if (!(GUARDEXPR(a,b))) throw new FailedDynamicCheckException(...); return ... final Ref<CConstraint> guardRefConstraint = procDef.guard(); Expr booleanGuard = (BooleanLit) nf.BooleanLit(pos, true).type(ts.Boolean()); if (guardRefConstraint!=null) { final CConstraint guard = reinstantiate(typeParamSubst, guardRefConstraint.get()); booleanGuard = addCheck(booleanGuard,guard, null, nf, ts, pos); } // add the constraints of the formals for (LocalDef localDef : procDef.formalNames()) { CConstraint constraint = Types.xclause(reinstantiate(typeParamSubst, Types.get(localDef.type()))); booleanGuard = addCheck(booleanGuard,constraint, localDef.name(), nf, ts, pos); } // replace old formals in depExpr with the new locals final Map<Name,Expr> old2new = CollectionFactory.newHashMap(oldFormals.size()); for (int k=0; k<newArgs.size(); k++) { Expr newE = newArgs.get(k); old2new.put(oldFormals.get(k).name(),newE); } // replace all AmbExpr with the new locals final X10TypeBuilder builder = new X10TypeBuilder(job, ts, nf); final ContextVisitor checker = new X10TypeChecker(job, ts, nf, job.nodeMemo()).context(closureContext); NodeVisitor replace = new NodeVisitor() { @Override public Node override(Node n) { if (n instanceof Special){ // if it's an outer instance, then we need to access the outer field Special special = (Special) n; TypeNode qualifer = special.qualifier(); if (qualifer==null) return newReceiver; // qualifer doesn't have type info because it was created in Synthesizer.makeExpr qualifer = (TypeNode) qualifer.visit(builder).visit(checker); ClassType ct = qualifer.type().toClass(); final ClassDef newReceiverDef = newReceiver.type().toClass().def(); final ClassDef qualifierDef = ct.def(); if (newReceiverDef==qualifierDef) return newReceiver; return nf.Call(pos,newReceiver, nf.Id(pos,X10ClassDecl_c.getThisMethod(newReceiverDef.fullName(),ct.fullName()))); } if (n instanceof AmbExpr) { AmbExpr amb = (AmbExpr) n; Name name = amb.name().id(); Expr newE = old2new.get(name); if (newE==null) throw new InternalCompilerError("Didn't find name="+name+ " in old2new="+old2new); return newE; } return null; } }; Expr newDep = (Expr)booleanGuard.visit(replace); // if (!newDep) throw new FailedDynamicCheckException(); return ... final Type resType = newExpr.type(); newDep = nf.Unary(pos, Unary.Operator.NOT, newDep).type(ts.Boolean()); If anIf = nf.If(pos, newDep, nf.Throw(pos, nf.New(pos, nf.TypeNodeFromQualifiedName(pos, QName.make("x10.lang.FailedDynamicCheckException")), CollectionUtil.<Expr>list(nf.StringLit(pos, newDep.toString()))).type(ts.Throwable()))); // if resType is void, then we shouldn't use return final boolean isVoid = ts.isVoid(resType); newExpr = (Expr) newExpr.visit(builder).visit(checker); anIf = (If) anIf.visit(builder).visit(checker); Block body = nf.Block(pos, anIf, isVoid ? nf.Eval(pos,newExpr) : nf.Return(pos, newExpr)); //body = (Block) body.visit(builder).visit(checker); - there is a problem type-checking the return statement Type closureRet = procInst.returnType(); Closure c = closure(pos, closureRet, params, body, v); MethodInstance ci = c.closureDef().asType().applyMethod(); return nf.ClosureCall(pos, c, args).closureInstance(ci).type(resType); }
private static Expr desugarCall(final Expr n, final Call call_c, final New new_c, final Binary binary_c, ContextVisitor v) { final NodeFactory nf = v.nodeFactory(); final TypeSystem ts = v.typeSystem(); final Job job = v.job(); assert n!=null && (call_c==n || new_c==n || binary_c==n); ProcedureCall procCall = call_c!=null || new_c!=null ? (ProcedureCall) n : null; final ProcedureInstance<? extends ProcedureDef> procInst = binary_c!=null ? binary_c.methodInstance() : procCall.procedureInstance(); if (procInst==null || // for binary ops (like ==), the methodInstance is null !procInst.checkConstraintsAtRuntime()) return (Expr)n; Warnings.dynamicCall(v.job(), Warnings.GeneratedDynamicCheck(n.position())); final Position pos = n.position(); List<Expr> args = binary_c!=null ? Arrays.asList(binary_c.left(), binary_c.right()) : procCall.arguments(); // we shouldn't use the def, because sometimes the constraints come from the instance, // e.g., new Box[Int{self!=0}](v) // dynamically checks that v!=0 (but you can't see it in the def! only in the instance). // However, the instance has also the arguments (that exists in the context), // and for some reason formalNames of the instance doesn't return the constraint that self!=0 (and Vijay thinks it shouldn't do it anyway) // so I need to take the paramSubst and do it myself on the def. // E.g., // new Box[Int{self!=0}](i) in the instance returns a formal arg123:Int{self==arg123, arg123==i} but without i!=0 ! // so I take the original formal from the def (x:T) and do the paramSubst on it to get x:Int{self!=0} final ProcedureDef procDef = procInst.def(); TypeParamSubst typeParamSubst = procInst instanceof ReinstantiatedMethodInstance ? ((ReinstantiatedMethodInstance)procInst).typeParamSubst() : procInst instanceof ReinstantiatedConstructorInstance ? ((ReinstantiatedConstructorInstance)procInst).typeParamSubst() : null; // this can happen when procInst is X10ConstructorInstance_c (see XTENLANG_2330). But creating an empty TypeParamSubst would also work final List<Type> typeParam = procInst.typeParameters(); // note that X10ConstructorInstance_c.typeParameters returns an empty list! (there is a todo there!) if (typeParam!=null && typeParam.size()>0) { if (typeParamSubst==null) typeParamSubst = new TypeParamSubst(ts,Collections.EMPTY_LIST,Collections.EMPTY_LIST); final ArrayList<Type> newArgs = typeParamSubst.copyTypeArguments(); newArgs.addAll(typeParam); final ArrayList<ParameterType> newParams = typeParamSubst.copyTypeParameters(); newParams.addAll(procDef.typeParameters()); typeParamSubst = new TypeParamSubst(ts, newArgs,newParams); } final List<LocalDef> oldFormals = procDef.formalNames(); assert oldFormals.size()==args.size(); Expr oldReceiver = null; final Receiver target; if (binary_c!=null) target = null; else target = (call_c==null ? new_c.qualifier() : call_c.target()); if (target!=null && target instanceof Expr) { // making sure that the receiver is not a TypeNode oldReceiver = (Expr) target; args = new ArrayList<Expr>(args); args.add(0, (Expr) oldReceiver); } ArrayList<Expr> newArgs = new ArrayList<Expr>(args.size()); ArrayList<Formal> params = new ArrayList<Formal>(args.size()); final Context context = v.context(); final Context closureContext = context.pushBlock(); int i=0; for (Expr arg : args) { // The argument might be null, e.g., def m(b:Z) {b.x!=null} = 1; ... m(null); final LocalDef oldFormal = arg==oldReceiver ? null : oldFormals.get(oldReceiver==null ? i : i-1); Name xn = oldFormal!=null ? oldFormal.name() : Name.make("x$"+i); // to make sure it doesn't conflict/shaddow an existing field i++; final Type type = oldFormal!=null ? reinstantiate(typeParamSubst, Types.get(oldFormal.type())) : arg.type(); LocalDef xDef = ts.localDef(pos, ts.Final(), Types.ref(type), xn); Formal x = nf.Formal(pos, nf.FlagsNode(pos, ts.Final()), nf.CanonicalTypeNode(pos,type), nf.Id(pos, xn)).localDef(xDef); params.add(x); final Local local = (Local) nf.Local(pos, nf.Id(pos, xn)).localInstance(xDef.asInstance()).type(type); newArgs.add(local); closureContext.addVariable(local.localInstance()); } final Expr newReceiver = oldReceiver==null ? null : newArgs.remove(0); final ProcedureCall newProcCall; if (newReceiver==null) newProcCall = procCall; else newProcCall = (call_c!=null ? call_c.target(newReceiver) : new_c.qualifier(newReceiver)); Expr newExpr; if (binary_c!=null) newExpr = binary_c.left(newArgs.get(0)).right(newArgs.get(1)); else newExpr = (Expr) newProcCall.arguments(newArgs); // we add the guard to the body, then the return stmt. // if (!(GUARDEXPR(a,b))) throw new FailedDynamicCheckException(...); return ... final Ref<CConstraint> guardRefConstraint = procDef.guard(); Expr booleanGuard = (BooleanLit) nf.BooleanLit(pos, true).type(ts.Boolean()); if (guardRefConstraint!=null) { final CConstraint guard = reinstantiate(typeParamSubst, guardRefConstraint.get()); booleanGuard = addCheck(booleanGuard,guard, null, nf, ts, pos); } // add the constraints of the formals for (LocalDef localDef : procDef.formalNames()) { CConstraint constraint = Types.xclause(reinstantiate(typeParamSubst, Types.get(localDef.type()))); booleanGuard = addCheck(booleanGuard,constraint, localDef.name(), nf, ts, pos); } // replace old formals in depExpr with the new locals final Map<Name,Expr> old2new = CollectionFactory.newHashMap(oldFormals.size()); for (int k=0; k<newArgs.size(); k++) { Expr newE = newArgs.get(k); old2new.put(oldFormals.get(k).name(),newE); } // replace all AmbExpr with the new locals final X10TypeBuilder builder = new X10TypeBuilder(job, ts, nf); final ContextVisitor checker = new X10TypeChecker(job, ts, nf, job.nodeMemo()).context(closureContext); NodeVisitor replace = new NodeVisitor() { @Override public Node override(Node n) { if (n instanceof Special){ // if it's an outer instance, then we need to access the outer field Special special = (Special) n; TypeNode qualifer = special.qualifier(); if (qualifer==null) return newReceiver; // qualifer doesn't have type info because it was created in Synthesizer.makeExpr qualifer = (TypeNode) qualifer.visit(builder).visit(checker); ClassType ct = qualifer.type().toClass(); Type receiverType = newReceiver.type(); final Type baseType = Types.baseType(receiverType); if (baseType instanceof ParameterType) { final List<Type> upperBounds = ts.env(context).upperBounds(baseType, false); receiverType = ts.Any(); for (Type up : upperBounds) { if (!(Types.baseType(up) instanceof ParameterType)) receiverType = up; } } final ClassDef newReceiverDef = receiverType.toClass().def(); final ClassDef qualifierDef = ct.def(); if (newReceiverDef==qualifierDef) return newReceiver; return nf.Call(pos,newReceiver, nf.Id(pos,X10ClassDecl_c.getThisMethod(newReceiverDef.fullName(),ct.fullName()))); } if (n instanceof AmbExpr) { AmbExpr amb = (AmbExpr) n; Name name = amb.name().id(); Expr newE = old2new.get(name); if (newE==null) throw new InternalCompilerError("Didn't find name="+name+ " in old2new="+old2new); return newE; } return null; } }; Expr newDep = (Expr)booleanGuard.visit(replace); // if (!newDep) throw new FailedDynamicCheckException(); return ... final Type resType = newExpr.type(); newDep = nf.Unary(pos, Unary.Operator.NOT, newDep).type(ts.Boolean()); If anIf = nf.If(pos, newDep, nf.Throw(pos, nf.New(pos, nf.TypeNodeFromQualifiedName(pos, QName.make("x10.lang.FailedDynamicCheckException")), CollectionUtil.<Expr>list(nf.StringLit(pos, newDep.toString()))).type(ts.Throwable()))); // if resType is void, then we shouldn't use return final boolean isVoid = ts.isVoid(resType); newExpr = (Expr) newExpr.visit(builder).visit(checker); anIf = (If) anIf.visit(builder).visit(checker); Block body = nf.Block(pos, anIf, isVoid ? nf.Eval(pos,newExpr) : nf.Return(pos, newExpr)); //body = (Block) body.visit(builder).visit(checker); - there is a problem type-checking the return statement Type closureRet = procInst.returnType(); Closure c = closure(pos, closureRet, params, body, v); MethodInstance ci = c.closureDef().asType().applyMethod(); return nf.ClosureCall(pos, c, args).closureInstance(ci).type(resType); }
diff --git a/src/java/com/scriptographer/adm/ModalDialog.java b/src/java/com/scriptographer/adm/ModalDialog.java index 4f066055..506034a3 100644 --- a/src/java/com/scriptographer/adm/ModalDialog.java +++ b/src/java/com/scriptographer/adm/ModalDialog.java @@ -1,151 +1,152 @@ /* * 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 14.03.2005. */ package com.scriptographer.adm; import java.util.EnumSet; import com.scratchdisk.util.EnumUtils; import com.scriptographer.ScriptographerEngine; /** * @author lehni */ public class ModalDialog extends Dialog { private boolean modal; private boolean fixModal; protected ModalDialog(int style, EnumSet<DialogOption> options) { // Always create ModalDialogs hidden, as they need to be shown // explicitly super(style, getOptions(options)); } public ModalDialog(EnumSet<DialogOption> options) { this(getStyle(options), options); } public ModalDialog(DialogOption[] options) { this(EnumUtils.asSet(options)); } public ModalDialog() { this((EnumSet<DialogOption>) null); } private static EnumSet<DialogOption> getOptions( EnumSet<DialogOption> options) { options = options != null ? options.clone() : EnumSet.noneOf(DialogOption.class); // Always create modal dialogs hidden, and they show them in doModal() options.add(DialogOption.HIDDEN); return options; } /* * Extract the style from the pseudo options: */ private static int getStyle(EnumSet<DialogOption> options) { if (options != null) { if (options.contains(DialogOption.RESIZING)) { return STYLE_RESIZING_MODAL; } else if (options.contains(DialogOption.ALERT)) { return STYLE_ALERT; } else if (options.contains(DialogOption.SYSTEM_ALERT)) { return STYLE_SYSTEM_ALERT; } } return STYLE_MODAL; } private native Item nativeDoModal(); public Item doModal() { boolean progressVisible = ScriptographerEngine.getProgressVisible(); ScriptographerEngine.setProgressVisible(false); try { modal = true; // Before showing the dialog, we need to initialize it, in order // to avoid flicker. initialize(true, false); Item item = nativeDoModal(); ScriptographerEngine.setProgressVisible(progressVisible); return item; } finally { modal = false; } } public native void endModal(); protected void onHide() { endModal(); super.onHide(); } protected void onActivate() { // This is part of a workaround for a bug in Illustrator: Invisible and // inactive modal dialogs seem to get active but remain invisible after // another modal dialog was deactivated, blocking the whole interface. // So if we receive an onActivate event but are not in a modal loop, // execute fixModal, which uses a native timer to deactivate the dialog // again right after activation. The fixModal field is used to let // onDeactivate know about this, and filter out the event. if (!modal) { fixModal = true; // Deactivates the invisible modal dialog right after it was // accidentally activated by a Illustrator CS3 bug. Immediately // deactivating it does not work. invokeLater(new Runnable() { public void run() { if (!isVisible()) { // Make sure that the focus goes back to whoever was // active before this invisible modal dialog got wrongly // activated. - if (previousActiveDialog != null) + if (previousActiveDialog != null + && previousActiveDialog != ModalDialog.this) previousActiveDialog.setActive(true); setActive(false); } } }); } else { super.onActivate(); } } protected void onDeactivate() { if (fixModal) { fixModal = false; } else { super.onDeactivate(); } } }
true
true
protected void onActivate() { // This is part of a workaround for a bug in Illustrator: Invisible and // inactive modal dialogs seem to get active but remain invisible after // another modal dialog was deactivated, blocking the whole interface. // So if we receive an onActivate event but are not in a modal loop, // execute fixModal, which uses a native timer to deactivate the dialog // again right after activation. The fixModal field is used to let // onDeactivate know about this, and filter out the event. if (!modal) { fixModal = true; // Deactivates the invisible modal dialog right after it was // accidentally activated by a Illustrator CS3 bug. Immediately // deactivating it does not work. invokeLater(new Runnable() { public void run() { if (!isVisible()) { // Make sure that the focus goes back to whoever was // active before this invisible modal dialog got wrongly // activated. if (previousActiveDialog != null) previousActiveDialog.setActive(true); setActive(false); } } }); } else { super.onActivate(); } }
protected void onActivate() { // This is part of a workaround for a bug in Illustrator: Invisible and // inactive modal dialogs seem to get active but remain invisible after // another modal dialog was deactivated, blocking the whole interface. // So if we receive an onActivate event but are not in a modal loop, // execute fixModal, which uses a native timer to deactivate the dialog // again right after activation. The fixModal field is used to let // onDeactivate know about this, and filter out the event. if (!modal) { fixModal = true; // Deactivates the invisible modal dialog right after it was // accidentally activated by a Illustrator CS3 bug. Immediately // deactivating it does not work. invokeLater(new Runnable() { public void run() { if (!isVisible()) { // Make sure that the focus goes back to whoever was // active before this invisible modal dialog got wrongly // activated. if (previousActiveDialog != null && previousActiveDialog != ModalDialog.this) previousActiveDialog.setActive(true); setActive(false); } } }); } else { super.onActivate(); } }
diff --git a/serenity-app/src/main/java/us/nineworlds/serenity/core/services/ShowRetrievalIntentService.java b/serenity-app/src/main/java/us/nineworlds/serenity/core/services/ShowRetrievalIntentService.java index 9caebc48..47bd0fa9 100644 --- a/serenity-app/src/main/java/us/nineworlds/serenity/core/services/ShowRetrievalIntentService.java +++ b/serenity-app/src/main/java/us/nineworlds/serenity/core/services/ShowRetrievalIntentService.java @@ -1,166 +1,166 @@ /** * The MIT License (MIT) * Copyright (c) 2012 David Carver * 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 us.nineworlds.serenity.core.services; import java.io.IOException; import java.util.ArrayList; import java.util.List; import us.nineworlds.plex.rest.model.impl.Directory; import us.nineworlds.plex.rest.model.impl.Genre; import us.nineworlds.plex.rest.model.impl.MediaContainer; import us.nineworlds.serenity.core.model.impl.TVShowSeriesInfo; import android.content.Intent; import android.os.Bundle; import android.os.Message; import android.os.Messenger; import android.os.RemoteException; import android.util.Log; /** * @author dcarver * */ public class ShowRetrievalIntentService extends AbstractPlexRESTIntentService { private List<TVShowSeriesInfo> tvShowList = null; protected String key; protected String category; public ShowRetrievalIntentService() { super("ShowRetrievalIntentService"); tvShowList = new ArrayList<TVShowSeriesInfo>(); } @Override public void sendMessageResults(Intent intent) { Bundle extras = intent.getExtras(); if (extras != null) { Messenger messenger = (Messenger) extras.get("MESSENGER"); Message msg = Message.obtain(); msg.obj = tvShowList; try { messenger.send(msg); } catch (RemoteException ex) { Log.e(getClass().getName(), "Unable to send message", ex); } } } @Override protected void onHandleIntent(Intent intent) { key = intent.getExtras().getString("key"); category = intent.getExtras().getString("category"); createBanners(); sendMessageResults(intent); } protected void createBanners() { MediaContainer mc = null; String baseUrl = null; try { mc = retrieveVideos(); baseUrl = factory.baseURL(); } catch (IOException ex) { Log.e(getClass().getName(), "Unable to talk to server: ", ex); } catch (Exception e) { Log.e(getClass().getName(), "Oops.", e); } if (mc != null && mc.getSize() > 0) { List<Directory> shows = mc.getDirectories(); if (shows != null) { for (Directory show : shows) { TVShowSeriesInfo mpi = new TVShowSeriesInfo(); if (show.getSummary() != null) { mpi.setPlotSummary(show.getSummary()); } String burl = factory.baseURL() + ":/resources/show-fanart.jpg"; if (show.getArt() != null) { burl = baseUrl + show.getArt().replaceFirst("/", ""); } mpi.setBackgroundURL(burl); String turl = ""; if (show.getBanner() != null) { turl = baseUrl + show.getBanner().replaceFirst("/", ""); } mpi.setPosterURL(turl); String thumbURL = ""; if (show.getThumb() != null) { thumbURL = baseUrl + show.getThumb().replaceFirst("/", ""); } mpi.setThumbNailURL(thumbURL); mpi.setTitle(show.getTitle()); mpi.setContentRating(show.getContentRating()); List<String> genres = processGeneres(show); mpi.setGeneres(genres); - mpi.setShowsWatched(show.getViewedLeafCount()); int totalEpisodes = 0; int viewedEpisodes = 0; if (show.getLeafCount() != null) { totalEpisodes = Integer.parseInt(show.getLeafCount()); } if (show.getViewedLeafCount() != null) { viewedEpisodes = Integer.parseInt(show.getViewedLeafCount()); } int unwatched = totalEpisodes - viewedEpisodes; mpi.setShowsUnwatched(Integer.toString(unwatched)); + mpi.setShowsWatched(Integer.toString(viewedEpisodes)); mpi.setKey(show.getKey()); tvShowList.add(mpi); } } } } protected MediaContainer retrieveVideos() throws Exception { if (category == null) { category = "all"; } return factory.retrieveSections(key, category); } protected List<String> processGeneres(Directory show) { ArrayList<String> genres = new ArrayList<String>(); if (show.getGenres() != null) { for (Genre genre : show.getGenres()) { genres.add(genre.getTag()); } } return genres; } }
false
true
protected void createBanners() { MediaContainer mc = null; String baseUrl = null; try { mc = retrieveVideos(); baseUrl = factory.baseURL(); } catch (IOException ex) { Log.e(getClass().getName(), "Unable to talk to server: ", ex); } catch (Exception e) { Log.e(getClass().getName(), "Oops.", e); } if (mc != null && mc.getSize() > 0) { List<Directory> shows = mc.getDirectories(); if (shows != null) { for (Directory show : shows) { TVShowSeriesInfo mpi = new TVShowSeriesInfo(); if (show.getSummary() != null) { mpi.setPlotSummary(show.getSummary()); } String burl = factory.baseURL() + ":/resources/show-fanart.jpg"; if (show.getArt() != null) { burl = baseUrl + show.getArt().replaceFirst("/", ""); } mpi.setBackgroundURL(burl); String turl = ""; if (show.getBanner() != null) { turl = baseUrl + show.getBanner().replaceFirst("/", ""); } mpi.setPosterURL(turl); String thumbURL = ""; if (show.getThumb() != null) { thumbURL = baseUrl + show.getThumb().replaceFirst("/", ""); } mpi.setThumbNailURL(thumbURL); mpi.setTitle(show.getTitle()); mpi.setContentRating(show.getContentRating()); List<String> genres = processGeneres(show); mpi.setGeneres(genres); mpi.setShowsWatched(show.getViewedLeafCount()); int totalEpisodes = 0; int viewedEpisodes = 0; if (show.getLeafCount() != null) { totalEpisodes = Integer.parseInt(show.getLeafCount()); } if (show.getViewedLeafCount() != null) { viewedEpisodes = Integer.parseInt(show.getViewedLeafCount()); } int unwatched = totalEpisodes - viewedEpisodes; mpi.setShowsUnwatched(Integer.toString(unwatched)); mpi.setKey(show.getKey()); tvShowList.add(mpi); } } } }
protected void createBanners() { MediaContainer mc = null; String baseUrl = null; try { mc = retrieveVideos(); baseUrl = factory.baseURL(); } catch (IOException ex) { Log.e(getClass().getName(), "Unable to talk to server: ", ex); } catch (Exception e) { Log.e(getClass().getName(), "Oops.", e); } if (mc != null && mc.getSize() > 0) { List<Directory> shows = mc.getDirectories(); if (shows != null) { for (Directory show : shows) { TVShowSeriesInfo mpi = new TVShowSeriesInfo(); if (show.getSummary() != null) { mpi.setPlotSummary(show.getSummary()); } String burl = factory.baseURL() + ":/resources/show-fanart.jpg"; if (show.getArt() != null) { burl = baseUrl + show.getArt().replaceFirst("/", ""); } mpi.setBackgroundURL(burl); String turl = ""; if (show.getBanner() != null) { turl = baseUrl + show.getBanner().replaceFirst("/", ""); } mpi.setPosterURL(turl); String thumbURL = ""; if (show.getThumb() != null) { thumbURL = baseUrl + show.getThumb().replaceFirst("/", ""); } mpi.setThumbNailURL(thumbURL); mpi.setTitle(show.getTitle()); mpi.setContentRating(show.getContentRating()); List<String> genres = processGeneres(show); mpi.setGeneres(genres); int totalEpisodes = 0; int viewedEpisodes = 0; if (show.getLeafCount() != null) { totalEpisodes = Integer.parseInt(show.getLeafCount()); } if (show.getViewedLeafCount() != null) { viewedEpisodes = Integer.parseInt(show.getViewedLeafCount()); } int unwatched = totalEpisodes - viewedEpisodes; mpi.setShowsUnwatched(Integer.toString(unwatched)); mpi.setShowsWatched(Integer.toString(viewedEpisodes)); mpi.setKey(show.getKey()); tvShowList.add(mpi); } } } }
diff --git a/NewsBlurPlus/src/com/asafge/newsblurplus/NewsBlurPlus.java b/NewsBlurPlus/src/com/asafge/newsblurplus/NewsBlurPlus.java index b976d2c..a220829 100644 --- a/NewsBlurPlus/src/com/asafge/newsblurplus/NewsBlurPlus.java +++ b/NewsBlurPlus/src/com/asafge/newsblurplus/NewsBlurPlus.java @@ -1,376 +1,376 @@ package com.asafge.newsblurplus; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import android.os.RemoteException; import com.noinnion.android.reader.api.ReaderException; import com.noinnion.android.reader.api.ReaderExtension; import com.noinnion.android.reader.api.internal.IItemIdListHandler; import com.noinnion.android.reader.api.internal.IItemListHandler; import com.noinnion.android.reader.api.internal.ISubscriptionListHandler; import com.noinnion.android.reader.api.internal.ITagListHandler; import com.noinnion.android.reader.api.provider.IItem; import com.noinnion.android.reader.api.provider.ISubscription; public class NewsBlurPlus extends ReaderExtension { private Context c; /* * Constructor */ @Override public void onCreate() { super.onCreate(); c = getApplicationContext(); }; /* * Main sync function to get folders, feeds, and counts. * 1. Get the folders (tags) and their feeds. * 2. Ask NewsBlur to Refresh feed counts + save to feeds. * 3. Send handler the tags and feeds. */ @Override public void handleReaderList(ITagListHandler tagHandler, ISubscriptionListHandler subHandler, long syncTime) throws ReaderException { SubsStruct.InstanceRefresh(c); APIHelper.updateFeedCounts(c, SubsStruct.Instance(c).Subs); if (SubsStruct.Instance(c).Subs.size() == 0) throw new ReaderException("No subscriptions available"); try { subHandler.subscriptions(SubsStruct.Instance(c).Subs); tagHandler.tags(SubsStruct.Instance(c).Tags); } catch (RemoteException e) { throw new ReaderException("Sub/tag handler error", e); } } /* * Get a list of unread story IDS (URLs), UI will mark all other as read. * This really speeds up the sync process. */ @Override public void handleItemIdList(IItemIdListHandler handler, long syncTime) throws ReaderException { try { int limit = handler.limit(); String uid = handler.stream(); if (uid.startsWith(ReaderExtension.STATE_STARRED)) handler.items(APIHelper.getStarredHashes(c, limit, -60)); else if (uid.startsWith(ReaderExtension.STATE_READING_LIST)) { List<String> hashes = APIHelper.getUnreadHashes(c, limit, null, null); if (SubsStruct.Instance(c).IsPremium) hashes = APIHelper.filterLowIntelligence(hashes, c); handler.items(hashes); } else throw new ReaderException("Unknown reading state"); } catch (RemoteException e) { throw new ReaderException("ItemID handler error", e); } } /* * Handle a single item list (a feed or a folder). * This functions calls the parseItemList function. */ @Override public void handleItemList(IItemListHandler handler, long syncTime) throws ReaderException { try { String uid = handler.stream(); int limit = handler.limit(); int story_count = 1; // Load the seen hashes from prefs - RotateQueue<String> seenHashes = new RotateQueue<String>(10, Prefs.getHashesList(c)); + RotateQueue<String> seenHashes = new RotateQueue<String>(1000, Prefs.getHashesList(c)); if (uid.startsWith(ReaderExtension.STATE_STARRED)) { Integer page = 1; while ((limit > 0) && story_count > 0) { APICall ac = new APICall(APICall.API_URL_STARRED_STORIES, c); ac.addGetParam("page", page.toString()); ac.sync(); story_count = ac.Json.getJSONArray("stories").length(); if (story_count > 0) { parseItemList(ac.Json, handler, seenHashes); limit -= story_count; page++; } } } else { List<String> hashes = new ArrayList<String>(); int chunk = (SubsStruct.Instance(c).IsPremium ? 100 : 5 ); if (uid.equals(ReaderExtension.STATE_READING_LIST)) { List<String> unread_hashes = APIHelper.getUnreadHashes(c, limit, null, seenHashes); for (String h : unread_hashes) if (!handler.excludedStreams().contains(APIHelper.getFeedUrlFromFeedId(h))) hashes.add(h); } else if (uid.startsWith("FEED:")) { List<String> feeds = Arrays.asList(APIHelper.getFeedIdFromFeedUrl(uid)); hashes = APIHelper.getUnreadHashes(c, limit, feeds, seenHashes); } else throw new ReaderException("Unknown reading state"); for (int start=0; start < hashes.size(); start += chunk) { APICall ac = new APICall(APICall.API_URL_RIVER, c); int end = (start+chunk < hashes.size()) ? start + chunk : hashes.size(); ac.addGetParams("h", hashes.subList(start, end)); ac.sync(); parseItemList(ac.Json, handler, seenHashes); } } // Save the seen hashes as a large String Prefs.setHashesList(c, seenHashes.toString()); } catch (JSONException e) { throw new ReaderException("ItemList handler error", e); } catch (RemoteException e) { throw new ReaderException("ItemList handler error", e); } } /* * Parse an array of items that are in the NewsBlur JSON format. */ public void parseItemList(JSONObject json, IItemListHandler handler, RotateQueue<String> seenHashes) throws ReaderException { try { int length = 0; List<IItem> items = new ArrayList<IItem>(); JSONArray arr = json.getJSONArray("stories"); for (int i=0; i<arr.length(); i++) { JSONObject story = arr.getJSONObject(i); IItem item = new IItem(); item.subUid = APIHelper.getFeedUrlFromFeedId(story.getString("story_feed_id")); item.title = story.getString("story_title"); item.link = story.getString("story_permalink"); item.uid = story.getString("story_hash"); item.author = story.getString("story_authors"); item.updatedTime = story.getLong("story_timestamp"); item.publishedTime = story.getLong("story_timestamp"); item.read = (story.getInt("read_status") == 1) || (APIHelper.getIntelligence(story) < 0); item.content = story.getString("story_content"); item.starred = (story.has("starred") && story.getString("starred") == "true"); if (item.starred) item.addCategory(StarredTag.get().uid); items.add(item); seenHashes.AddElement(item.uid); length += item.getLength(); if (items.size() % 200 == 0 || length > 300000) { handler.items(items, 0); items.clear(); length = 0; } } handler.items(items, 0); } catch (JSONException e) { throw new ReaderException("ParseItemList parse error", e); } catch (RemoteException e) { throw new ReaderException("SingleItem handler error", e); } } /* * Main function for marking stories (and their feeds) as read/unread. */ private boolean markAs(boolean read, String[] itemUids, String[] subUIds) throws ReaderException { APICall ac; if (itemUids == null && subUIds == null) { ac = new APICall(APICall.API_URL_MARK_ALL_AS_READ, c); } else { if (itemUids == null) { ac = new APICall(APICall.API_URL_MARK_FEED_AS_READ, c); for (String sub : subUIds) ac.addGetParam("feed_id", sub); } else { if (read) { ac = new APICall(APICall.API_URL_MARK_STORY_AS_READ, c); ac.addGetParams("story_hash", Arrays.asList(itemUids)); } else { ac = new APICall(APICall.API_URL_MARK_STORY_AS_UNREAD, c); for (int i=0; i<itemUids.length; i++) { ac.addPostParam("story_id", itemUids[i]); ac.addPostParam("feed_id", APIHelper.getFeedIdFromFeedUrl(subUIds[i])); } } } } return ac.syncGetResultOk(); } /* * Mark a list of stories (and their feeds) as read */ @Override public boolean markAsRead(String[] itemUids, String[] subUIds) throws ReaderException { return markAs(true, itemUids, subUIds); } /* * Mark a list of stories (and their feeds) as unread */ @Override public boolean markAsUnread(String[] itemUids, String[] subUids, boolean keepUnread) throws ReaderException { return markAs(false, itemUids, subUids); } /* * Mark all stories on all feeds as read. Iterate all feeds in order to avoid marking excluded feeds as read. * Note: s = subscription (feed), t = tag */ @Override public boolean markAllAsRead(String s, String t, String[] excluded_subs, long syncTime) throws ReaderException { if (s != null && s.startsWith("FEED:")) { String[] feed = { APIHelper.getFeedIdFromFeedUrl(s) }; return this.markAs(true, null, feed); } else { List<String> excluded = (excluded_subs != null) ? Arrays.asList(excluded_subs) : new ArrayList<String>(); List<String> subUIDs = new ArrayList<String>(); if (s == null && t == null) { for (ISubscription sub : SubsStruct.Instance(c).Subs) if (!excluded.contains(sub.uid)) subUIDs.add(sub.uid); return subUIDs.isEmpty() ? false : this.markAs(true, null, subUIDs.toArray(new String[0])); } else if (s.startsWith("FOL:")) { for (ISubscription sub : SubsStruct.Instance(c).Subs) if (!excluded.contains(sub.uid) && sub.getCategories().contains(s)) subUIDs.add(APIHelper.getFeedIdFromFeedUrl(sub.uid)); return subUIDs.isEmpty() ? false : this.markAs(true, null, subUIDs.toArray(new String[0])); } return false; } } /* * Edit an item's tag - currently supports only starring/unstarring items */ @Override public boolean editItemTag(String[] itemUids, String[] subUids, String[] addTags, String[] removeTags) throws ReaderException { boolean result = true; for (int i=0; i<itemUids.length; i++) { String url; if ((addTags != null) && addTags[i].startsWith(StarredTag.get().uid)) { url = APICall.API_URL_MARK_STORY_AS_STARRED; } else if ((removeTags != null) && removeTags[i].startsWith(StarredTag.get().uid)) { url = APICall.API_URL_MARK_STORY_AS_UNSTARRED; } else { result = false; throw new ReaderException("Unsupported tag type"); } APICall ac = new APICall(url, c); ac.addPostParam("story_id", itemUids[i]); ac.addPostParam("feed_id", APIHelper.getFeedIdFromFeedUrl(subUids[i])); if (!ac.syncGetResultOk()) { result = false; break; } } return result; } /* * Rename a top level folder both in News+ and in NewsBlur server */ @Override public boolean renameTag(String tagUid, String oldLabel, String newLabel) throws ReaderException { if (!tagUid.startsWith("FOL:")) return false; else { APICall ac = new APICall(APICall.API_URL_FOLDER_RENAME, c); ac.addPostParam("folder_to_rename", oldLabel); ac.addPostParam("new_folder_name", newLabel); ac.addPostParam("in_folder", ""); return ac.syncGetResultOk(); } } /* * Delete a top level folder both in News+ and in NewsBlur server * This just removes the folder, not the feeds in it */ @Override public boolean disableTag(String tagUid, String label) throws ReaderException { if (tagUid.startsWith("STAR:")) return false; else { for (ISubscription sub : SubsStruct.Instance(c).Subs) if ((sub.getCategories().contains(label) && !APIHelper.moveFeedToFolder(c, APIHelper.getFeedIdFromFeedUrl(sub.uid), label, ""))) return false; APICall ac = new APICall(APICall.API_URL_FOLDER_DEL, c); ac.addPostParam("folder_to_delete", label); return ac.syncGetResultOk(); } } /* * Main function for editing subscriptions - add/delete/rename/change-folder */ @Override public boolean editSubscription(String uid, String title, String feed_url, String[] tags, int action, long syncTime) throws ReaderException { switch (action) { // Feed - add/delete/rename case ReaderExtension.SUBSCRIPTION_ACTION_SUBCRIBE: { APICall ac = new APICall(APICall.API_URL_FEED_ADD, c); ac.addPostParam("url", feed_url); return ac.syncGetResultOk() && SubsStruct.Instance(c).Refresh(); } case ReaderExtension.SUBSCRIPTION_ACTION_UNSUBCRIBE: { APICall ac = new APICall(APICall.API_URL_FEED_DEL, c); ac.addPostParam("feed_id", APIHelper.getFeedIdFromFeedUrl(uid)); return ac.syncGetResultOk() && SubsStruct.Instance(c).Refresh(); } case ReaderExtension.SUBSCRIPTION_ACTION_EDIT: { APICall ac = new APICall(APICall.API_URL_FEED_RENAME, c); ac.addPostParam("feed_id", APIHelper.getFeedIdFromFeedUrl(uid)); ac.addPostParam("feed_title", title); return ac.syncGetResultOk(); } // Feed's parent folder - new_folder/add_to_folder/delete_from_folder case ReaderExtension.SUBSCRIPTION_ACTION_NEW_LABEL: { APICall ac = new APICall(APICall.API_URL_FOLDER_ADD, c); String newTag = tags[0].replace("FOL:", ""); ac.addPostParam("folder", newTag); return ac.syncGetResultOk(); } case ReaderExtension.SUBSCRIPTION_ACTION_ADD_LABEL: { String newTag = tags[0].replace("FOL:", ""); return APIHelper.moveFeedToFolder(c, APIHelper.getFeedIdFromFeedUrl(uid), "", newTag); } case ReaderExtension.SUBSCRIPTION_ACTION_REMOVE_LABEL: { String newTag = tags[0].replace("FOL:", ""); return APIHelper.moveFeedToFolder(c, APIHelper.getFeedIdFromFeedUrl(uid), newTag, ""); } default: return false; } } }
true
true
public void handleItemList(IItemListHandler handler, long syncTime) throws ReaderException { try { String uid = handler.stream(); int limit = handler.limit(); int story_count = 1; // Load the seen hashes from prefs RotateQueue<String> seenHashes = new RotateQueue<String>(10, Prefs.getHashesList(c)); if (uid.startsWith(ReaderExtension.STATE_STARRED)) { Integer page = 1; while ((limit > 0) && story_count > 0) { APICall ac = new APICall(APICall.API_URL_STARRED_STORIES, c); ac.addGetParam("page", page.toString()); ac.sync(); story_count = ac.Json.getJSONArray("stories").length(); if (story_count > 0) { parseItemList(ac.Json, handler, seenHashes); limit -= story_count; page++; } } } else { List<String> hashes = new ArrayList<String>(); int chunk = (SubsStruct.Instance(c).IsPremium ? 100 : 5 ); if (uid.equals(ReaderExtension.STATE_READING_LIST)) { List<String> unread_hashes = APIHelper.getUnreadHashes(c, limit, null, seenHashes); for (String h : unread_hashes) if (!handler.excludedStreams().contains(APIHelper.getFeedUrlFromFeedId(h))) hashes.add(h); } else if (uid.startsWith("FEED:")) { List<String> feeds = Arrays.asList(APIHelper.getFeedIdFromFeedUrl(uid)); hashes = APIHelper.getUnreadHashes(c, limit, feeds, seenHashes); } else throw new ReaderException("Unknown reading state"); for (int start=0; start < hashes.size(); start += chunk) { APICall ac = new APICall(APICall.API_URL_RIVER, c); int end = (start+chunk < hashes.size()) ? start + chunk : hashes.size(); ac.addGetParams("h", hashes.subList(start, end)); ac.sync(); parseItemList(ac.Json, handler, seenHashes); } } // Save the seen hashes as a large String Prefs.setHashesList(c, seenHashes.toString()); } catch (JSONException e) { throw new ReaderException("ItemList handler error", e); } catch (RemoteException e) { throw new ReaderException("ItemList handler error", e); } }
public void handleItemList(IItemListHandler handler, long syncTime) throws ReaderException { try { String uid = handler.stream(); int limit = handler.limit(); int story_count = 1; // Load the seen hashes from prefs RotateQueue<String> seenHashes = new RotateQueue<String>(1000, Prefs.getHashesList(c)); if (uid.startsWith(ReaderExtension.STATE_STARRED)) { Integer page = 1; while ((limit > 0) && story_count > 0) { APICall ac = new APICall(APICall.API_URL_STARRED_STORIES, c); ac.addGetParam("page", page.toString()); ac.sync(); story_count = ac.Json.getJSONArray("stories").length(); if (story_count > 0) { parseItemList(ac.Json, handler, seenHashes); limit -= story_count; page++; } } } else { List<String> hashes = new ArrayList<String>(); int chunk = (SubsStruct.Instance(c).IsPremium ? 100 : 5 ); if (uid.equals(ReaderExtension.STATE_READING_LIST)) { List<String> unread_hashes = APIHelper.getUnreadHashes(c, limit, null, seenHashes); for (String h : unread_hashes) if (!handler.excludedStreams().contains(APIHelper.getFeedUrlFromFeedId(h))) hashes.add(h); } else if (uid.startsWith("FEED:")) { List<String> feeds = Arrays.asList(APIHelper.getFeedIdFromFeedUrl(uid)); hashes = APIHelper.getUnreadHashes(c, limit, feeds, seenHashes); } else throw new ReaderException("Unknown reading state"); for (int start=0; start < hashes.size(); start += chunk) { APICall ac = new APICall(APICall.API_URL_RIVER, c); int end = (start+chunk < hashes.size()) ? start + chunk : hashes.size(); ac.addGetParams("h", hashes.subList(start, end)); ac.sync(); parseItemList(ac.Json, handler, seenHashes); } } // Save the seen hashes as a large String Prefs.setHashesList(c, seenHashes.toString()); } catch (JSONException e) { throw new ReaderException("ItemList handler error", e); } catch (RemoteException e) { throw new ReaderException("ItemList handler error", e); } }
diff --git a/src/main/groovy/grape/GrabAnnotationTransformation.java b/src/main/groovy/grape/GrabAnnotationTransformation.java index 43a70a33b..9afe69726 100644 --- a/src/main/groovy/grape/GrabAnnotationTransformation.java +++ b/src/main/groovy/grape/GrabAnnotationTransformation.java @@ -1,211 +1,217 @@ /* * Copyright 2003-2008 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 groovy.grape; import groovy.lang.Grab; import groovy.lang.Grapes; import org.codehaus.groovy.ast.*; import org.codehaus.groovy.ast.expr.*; import org.codehaus.groovy.ast.stmt.ExpressionStatement; import org.codehaus.groovy.control.CompilePhase; import org.codehaus.groovy.control.SourceUnit; import org.codehaus.groovy.transform.ASTTransformation; import org.codehaus.groovy.transform.GroovyASTTransformation; import java.util.*; /** * Created by IntelliJ IDEA. * User: Danno * Date: Jan 18, 2008 * Time: 9:48:57 PM */ @GroovyASTTransformation(phase=CompilePhase.CONVERSION) public class GrabAnnotationTransformation extends ClassCodeVisitorSupport implements ASTTransformation { private static final String GRAB_CLASS_NAME = Grab.class.getName(); private static final String GRAB_DOT_NAME = GRAB_CLASS_NAME.substring(GRAB_CLASS_NAME.lastIndexOf(".")); private static final String GRAB_SHORT_NAME = GRAB_DOT_NAME.substring(1); private static final String GRAPES_CLASS_NAME = Grapes.class.getName(); private static final String GRAPES_DOT_NAME = GRAPES_CLASS_NAME.substring(GRAPES_CLASS_NAME.lastIndexOf(".")); private static final String GRAPES_SHORT_NAME = GRAPES_DOT_NAME.substring(1); boolean allowShortGrab; Set<String> grabAliases; List<AnnotationNode> grabAnnotations; boolean allowShortGrapes; Set<String> grapesAliases; List<AnnotationNode> grapesAnnotations; SourceUnit sourceUnit; public SourceUnit getSourceUnit() { return sourceUnit; } public void visit(ASTNode[] nodes, SourceUnit source) { sourceUnit = source; ModuleNode mn = (ModuleNode) nodes[0]; allowShortGrab = true; allowShortGrapes = true; grabAliases = new HashSet(); grapesAliases = new HashSet(); Iterator i = mn.getImports().iterator(); while (i.hasNext()) { ImportNode im = (ImportNode) i.next(); String alias = im.getAlias(); String className = im.getClassName(); if ((className.endsWith(GRAB_DOT_NAME) && ((alias == null) || (alias.length() == 0))) || (GRAB_CLASS_NAME.equals(alias))) { allowShortGrab = false; } else if (GRAB_CLASS_NAME.equals(className)) { grabAliases.add(im.getAlias()); } if ((className.endsWith(GRAPES_DOT_NAME) && ((alias == null) || (alias.length() == 0))) || (GRAPES_CLASS_NAME.equals(alias))) { allowShortGrapes = false; } else if (GRAPES_CLASS_NAME.equals(className)) { grapesAliases.add(im.getAlias()); } } List<Map<String,Object>> grabMaps = new ArrayList(); for (ClassNode classNode : (List<ClassNode>) sourceUnit.getAST().getClasses()) { grabAnnotations = new ArrayList<AnnotationNode>(); grapesAnnotations = new ArrayList<AnnotationNode>(); visitClass(classNode); ClassNode grapeClassNode = new ClassNode(Grape.class); - //TODO process @Grapes if (!grapesAnnotations.isEmpty()) { for (int j = 0; j < grapesAnnotations.size(); j++) { AnnotationNode node = grapesAnnotations.get(j); Expression init = node.getMember("initClass"); Expression value = node.getMember("value"); if (value instanceof ListExpression) { for (Object o : ((ListExpression)value).getExpressions()) { if (o instanceof AnnotationConstantExpression) { if (((AnnotationConstantExpression)o).getValue() instanceof AnnotationNode) { AnnotationNode annotation = (AnnotationNode) ((AnnotationConstantExpression)o).getValue(); if ((init != null) && (annotation.getMember("initClass") != null)) { annotation.setMember("initClass", init); } String name = annotation.getClassNode().getName(); if ((GRAB_CLASS_NAME.equals(name)) || (allowShortGrab && GRAB_SHORT_NAME.equals(name)) || (grabAliases.contains(name))) { grabAnnotations.add(annotation); } } } } } // don't worry if it's not a ListExpression, or AnnotationConstant, etc. // the rest of GroovyC will flag it as a syntax error later, so we don't // need to raise the error ourselves } } if (!grabAnnotations.isEmpty()) { + grabAnnotationLoop: for (int j = 0; j < grabAnnotations.size(); j++) { AnnotationNode node = grabAnnotations.get(j); Map<String,Object> grabMap = new HashMap(); + for (String s : new String[] {"group", "module", "version"}) { + if (node.getMember(s) == null) { + addError("The missing attribute \"" + s + "\" is required in @" + node.getClassNode().getNameWithoutPackage() + " annotations", node); + continue grabAnnotationLoop; + } + } grabMap.put("group", ((ConstantExpression)node.getMember("group")).getValue()); grabMap.put("module", ((ConstantExpression)node.getMember("module")).getValue()); grabMap.put("version", ((ConstantExpression)node.getMember("version")).getValue()); grabMaps.add(grabMap); if ((node.getMember("initClass") == null) || (node.getMember("initClass") == ConstantExpression.TRUE)) { List grabInitializers = new ArrayList(); // add Grape.grab([group:group, module:module, version:version]) MapExpression me = new MapExpression(); me.addMapEntryExpression(new ConstantExpression("group"),node.getMember("group")); me.addMapEntryExpression(new ConstantExpression("module"),node.getMember("module")); me.addMapEntryExpression(new ConstantExpression("version"),node.getMember("version")); grabInitializers.add(new ExpressionStatement( new StaticMethodCallExpression( grapeClassNode, "grab", new ArgumentListExpression(me)))); // insert at beginning so we have the classloader set up before the class is called classNode.addStaticInitializerStatements(grabInitializers, true); } } } } if (!grabMaps.isEmpty()) { Map basicArgs = new HashMap(); basicArgs.put("classLoader", sourceUnit.getClassLoader()); Grape.grab(basicArgs, grabMaps.toArray(new Map[grabMaps.size()])); } } protected void visitConstructorOrMethod(MethodNode node, boolean isConstructor) { super.visitConstructorOrMethod(node, isConstructor); // this should be pushed into the super class... for (Parameter param : node.getParameters()) { visitAnnotations(param); } } /** * Adds the annotation to the internal target list if a match is found * @param node */ public void visitAnnotations(AnnotatedNode node) { super.visitAnnotations(node); Iterator i = node.getAnnotations().iterator(); while (i.hasNext()) { AnnotationNode an = (AnnotationNode) i.next(); String name = an.getClassNode().getName(); if ((GRAB_CLASS_NAME.equals(name)) || (allowShortGrab && GRAB_SHORT_NAME.equals(name)) || (grabAliases.contains(name))) { grabAnnotations.add(an); } if ((GRAPES_CLASS_NAME.equals(name)) || (allowShortGrapes && GRAPES_SHORT_NAME.equals(name)) || (grapesAliases.contains(name))) { grapesAnnotations.add(an); } } } }
false
true
public void visit(ASTNode[] nodes, SourceUnit source) { sourceUnit = source; ModuleNode mn = (ModuleNode) nodes[0]; allowShortGrab = true; allowShortGrapes = true; grabAliases = new HashSet(); grapesAliases = new HashSet(); Iterator i = mn.getImports().iterator(); while (i.hasNext()) { ImportNode im = (ImportNode) i.next(); String alias = im.getAlias(); String className = im.getClassName(); if ((className.endsWith(GRAB_DOT_NAME) && ((alias == null) || (alias.length() == 0))) || (GRAB_CLASS_NAME.equals(alias))) { allowShortGrab = false; } else if (GRAB_CLASS_NAME.equals(className)) { grabAliases.add(im.getAlias()); } if ((className.endsWith(GRAPES_DOT_NAME) && ((alias == null) || (alias.length() == 0))) || (GRAPES_CLASS_NAME.equals(alias))) { allowShortGrapes = false; } else if (GRAPES_CLASS_NAME.equals(className)) { grapesAliases.add(im.getAlias()); } } List<Map<String,Object>> grabMaps = new ArrayList(); for (ClassNode classNode : (List<ClassNode>) sourceUnit.getAST().getClasses()) { grabAnnotations = new ArrayList<AnnotationNode>(); grapesAnnotations = new ArrayList<AnnotationNode>(); visitClass(classNode); ClassNode grapeClassNode = new ClassNode(Grape.class); //TODO process @Grapes if (!grapesAnnotations.isEmpty()) { for (int j = 0; j < grapesAnnotations.size(); j++) { AnnotationNode node = grapesAnnotations.get(j); Expression init = node.getMember("initClass"); Expression value = node.getMember("value"); if (value instanceof ListExpression) { for (Object o : ((ListExpression)value).getExpressions()) { if (o instanceof AnnotationConstantExpression) { if (((AnnotationConstantExpression)o).getValue() instanceof AnnotationNode) { AnnotationNode annotation = (AnnotationNode) ((AnnotationConstantExpression)o).getValue(); if ((init != null) && (annotation.getMember("initClass") != null)) { annotation.setMember("initClass", init); } String name = annotation.getClassNode().getName(); if ((GRAB_CLASS_NAME.equals(name)) || (allowShortGrab && GRAB_SHORT_NAME.equals(name)) || (grabAliases.contains(name))) { grabAnnotations.add(annotation); } } } } } // don't worry if it's not a ListExpression, or AnnotationConstant, etc. // the rest of GroovyC will flag it as a syntax error later, so we don't // need to raise the error ourselves } } if (!grabAnnotations.isEmpty()) { for (int j = 0; j < grabAnnotations.size(); j++) { AnnotationNode node = grabAnnotations.get(j); Map<String,Object> grabMap = new HashMap(); grabMap.put("group", ((ConstantExpression)node.getMember("group")).getValue()); grabMap.put("module", ((ConstantExpression)node.getMember("module")).getValue()); grabMap.put("version", ((ConstantExpression)node.getMember("version")).getValue()); grabMaps.add(grabMap); if ((node.getMember("initClass") == null) || (node.getMember("initClass") == ConstantExpression.TRUE)) { List grabInitializers = new ArrayList(); // add Grape.grab([group:group, module:module, version:version]) MapExpression me = new MapExpression(); me.addMapEntryExpression(new ConstantExpression("group"),node.getMember("group")); me.addMapEntryExpression(new ConstantExpression("module"),node.getMember("module")); me.addMapEntryExpression(new ConstantExpression("version"),node.getMember("version")); grabInitializers.add(new ExpressionStatement( new StaticMethodCallExpression( grapeClassNode, "grab", new ArgumentListExpression(me)))); // insert at beginning so we have the classloader set up before the class is called classNode.addStaticInitializerStatements(grabInitializers, true); } } } } if (!grabMaps.isEmpty()) { Map basicArgs = new HashMap(); basicArgs.put("classLoader", sourceUnit.getClassLoader()); Grape.grab(basicArgs, grabMaps.toArray(new Map[grabMaps.size()])); } }
public void visit(ASTNode[] nodes, SourceUnit source) { sourceUnit = source; ModuleNode mn = (ModuleNode) nodes[0]; allowShortGrab = true; allowShortGrapes = true; grabAliases = new HashSet(); grapesAliases = new HashSet(); Iterator i = mn.getImports().iterator(); while (i.hasNext()) { ImportNode im = (ImportNode) i.next(); String alias = im.getAlias(); String className = im.getClassName(); if ((className.endsWith(GRAB_DOT_NAME) && ((alias == null) || (alias.length() == 0))) || (GRAB_CLASS_NAME.equals(alias))) { allowShortGrab = false; } else if (GRAB_CLASS_NAME.equals(className)) { grabAliases.add(im.getAlias()); } if ((className.endsWith(GRAPES_DOT_NAME) && ((alias == null) || (alias.length() == 0))) || (GRAPES_CLASS_NAME.equals(alias))) { allowShortGrapes = false; } else if (GRAPES_CLASS_NAME.equals(className)) { grapesAliases.add(im.getAlias()); } } List<Map<String,Object>> grabMaps = new ArrayList(); for (ClassNode classNode : (List<ClassNode>) sourceUnit.getAST().getClasses()) { grabAnnotations = new ArrayList<AnnotationNode>(); grapesAnnotations = new ArrayList<AnnotationNode>(); visitClass(classNode); ClassNode grapeClassNode = new ClassNode(Grape.class); if (!grapesAnnotations.isEmpty()) { for (int j = 0; j < grapesAnnotations.size(); j++) { AnnotationNode node = grapesAnnotations.get(j); Expression init = node.getMember("initClass"); Expression value = node.getMember("value"); if (value instanceof ListExpression) { for (Object o : ((ListExpression)value).getExpressions()) { if (o instanceof AnnotationConstantExpression) { if (((AnnotationConstantExpression)o).getValue() instanceof AnnotationNode) { AnnotationNode annotation = (AnnotationNode) ((AnnotationConstantExpression)o).getValue(); if ((init != null) && (annotation.getMember("initClass") != null)) { annotation.setMember("initClass", init); } String name = annotation.getClassNode().getName(); if ((GRAB_CLASS_NAME.equals(name)) || (allowShortGrab && GRAB_SHORT_NAME.equals(name)) || (grabAliases.contains(name))) { grabAnnotations.add(annotation); } } } } } // don't worry if it's not a ListExpression, or AnnotationConstant, etc. // the rest of GroovyC will flag it as a syntax error later, so we don't // need to raise the error ourselves } } if (!grabAnnotations.isEmpty()) { grabAnnotationLoop: for (int j = 0; j < grabAnnotations.size(); j++) { AnnotationNode node = grabAnnotations.get(j); Map<String,Object> grabMap = new HashMap(); for (String s : new String[] {"group", "module", "version"}) { if (node.getMember(s) == null) { addError("The missing attribute \"" + s + "\" is required in @" + node.getClassNode().getNameWithoutPackage() + " annotations", node); continue grabAnnotationLoop; } } grabMap.put("group", ((ConstantExpression)node.getMember("group")).getValue()); grabMap.put("module", ((ConstantExpression)node.getMember("module")).getValue()); grabMap.put("version", ((ConstantExpression)node.getMember("version")).getValue()); grabMaps.add(grabMap); if ((node.getMember("initClass") == null) || (node.getMember("initClass") == ConstantExpression.TRUE)) { List grabInitializers = new ArrayList(); // add Grape.grab([group:group, module:module, version:version]) MapExpression me = new MapExpression(); me.addMapEntryExpression(new ConstantExpression("group"),node.getMember("group")); me.addMapEntryExpression(new ConstantExpression("module"),node.getMember("module")); me.addMapEntryExpression(new ConstantExpression("version"),node.getMember("version")); grabInitializers.add(new ExpressionStatement( new StaticMethodCallExpression( grapeClassNode, "grab", new ArgumentListExpression(me)))); // insert at beginning so we have the classloader set up before the class is called classNode.addStaticInitializerStatements(grabInitializers, true); } } } } if (!grabMaps.isEmpty()) { Map basicArgs = new HashMap(); basicArgs.put("classLoader", sourceUnit.getClassLoader()); Grape.grab(basicArgs, grabMaps.toArray(new Map[grabMaps.size()])); } }
diff --git a/src/main/java/org/basex/gui/layout/BaseXTree.java b/src/main/java/org/basex/gui/layout/BaseXTree.java index 5e520f20e..87d7d7349 100644 --- a/src/main/java/org/basex/gui/layout/BaseXTree.java +++ b/src/main/java/org/basex/gui/layout/BaseXTree.java @@ -1,47 +1,46 @@ package org.basex.gui.layout; import java.awt.Window; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.JTree; import javax.swing.SwingUtilities; import javax.swing.tree.DefaultMutableTreeNode; /** * Project specific tree implementation. * * @author BaseX Team 2005-12, BSD License * @author Christian Gruen */ public class BaseXTree extends JTree { /** * Constructor. * @param root root node * @param w window reference */ public BaseXTree(final DefaultMutableTreeNode root, final Window w) { super(root); - final BaseXTree t = this; BaseXLayout.addInteraction(this, w); this.addMouseListener(new MouseListener() { @Override public void mouseReleased(final MouseEvent e) { } @Override public void mousePressed(final MouseEvent e) { + if(SwingUtilities.isRightMouseButton(e)) + setSelectionRow(getClosestRowForLocation(e.getX(), e.getY())); } @Override public void mouseExited(final MouseEvent e) { } @Override public void mouseEntered(final MouseEvent e) { } @Override public void mouseClicked(final MouseEvent e) { - if(SwingUtilities.isRightMouseButton(e)) - t.setSelectionRow(t.getClosestRowForLocation(e.getX(), e.getY())); } }); } }
false
true
public BaseXTree(final DefaultMutableTreeNode root, final Window w) { super(root); final BaseXTree t = this; BaseXLayout.addInteraction(this, w); this.addMouseListener(new MouseListener() { @Override public void mouseReleased(final MouseEvent e) { } @Override public void mousePressed(final MouseEvent e) { } @Override public void mouseExited(final MouseEvent e) { } @Override public void mouseEntered(final MouseEvent e) { } @Override public void mouseClicked(final MouseEvent e) { if(SwingUtilities.isRightMouseButton(e)) t.setSelectionRow(t.getClosestRowForLocation(e.getX(), e.getY())); } }); }
public BaseXTree(final DefaultMutableTreeNode root, final Window w) { super(root); BaseXLayout.addInteraction(this, w); this.addMouseListener(new MouseListener() { @Override public void mouseReleased(final MouseEvent e) { } @Override public void mousePressed(final MouseEvent e) { if(SwingUtilities.isRightMouseButton(e)) setSelectionRow(getClosestRowForLocation(e.getX(), e.getY())); } @Override public void mouseExited(final MouseEvent e) { } @Override public void mouseEntered(final MouseEvent e) { } @Override public void mouseClicked(final MouseEvent e) { } }); }
diff --git a/cyklotron-ui/src/main/java/net/cyklotron/cms/modules/views/forum/Forum.java b/cyklotron-ui/src/main/java/net/cyklotron/cms/modules/views/forum/Forum.java index edf828df2..2a86824ec 100644 --- a/cyklotron-ui/src/main/java/net/cyklotron/cms/modules/views/forum/Forum.java +++ b/cyklotron-ui/src/main/java/net/cyklotron/cms/modules/views/forum/Forum.java @@ -1,634 +1,634 @@ package net.cyklotron.cms.modules.views.forum; 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 java.util.StringTokenizer; import org.jcontainer.dna.Logger; import org.objectledge.context.Context; import org.objectledge.coral.entity.EntityDoesNotExistException; import org.objectledge.coral.query.MalformedQueryException; import org.objectledge.coral.query.QueryResults; import org.objectledge.coral.schema.ResourceClass; import org.objectledge.coral.security.Permission; import org.objectledge.coral.session.CoralSession; import org.objectledge.coral.store.Resource; import org.objectledge.coral.table.ResourceListTableModel; import org.objectledge.i18n.I18nContext; import org.objectledge.parameters.Parameters; import org.objectledge.parameters.RequestParameters; import org.objectledge.pipeline.ProcessingException; import org.objectledge.table.TableException; import org.objectledge.table.TableFilter; import org.objectledge.table.TableModel; import org.objectledge.table.TableRow; import org.objectledge.table.TableState; import org.objectledge.table.TableStateManager; import org.objectledge.table.TableTool; import org.objectledge.templating.TemplatingContext; import org.objectledge.web.HttpContext; import org.objectledge.web.mvc.finders.MVCFinder; import net.cyklotron.cms.CmsData; import net.cyklotron.cms.CmsDataFactory; import net.cyklotron.cms.forum.DiscussionResource; import net.cyklotron.cms.forum.DiscussionResourceImpl; import net.cyklotron.cms.forum.ForumException; import net.cyklotron.cms.forum.ForumResource; import net.cyklotron.cms.forum.ForumService; import net.cyklotron.cms.forum.MessageResource; import net.cyklotron.cms.forum.MessageResourceImpl; import net.cyklotron.cms.forum.MessageTableModel; import net.cyklotron.cms.modules.views.BaseSkinableScreen; import net.cyklotron.cms.preferences.PreferencesService; import net.cyklotron.cms.skins.SkinService; import net.cyklotron.cms.structure.StructureService; import net.cyklotron.cms.style.StyleService; import net.cyklotron.cms.util.CollectionFilter; import net.cyklotron.cms.util.ProtectedViewFilter; import net.cyklotron.cms.workflow.AutomatonResource; import net.cyklotron.cms.workflow.StateResource; import net.cyklotron.cms.workflow.WorkflowException; import net.cyklotron.cms.workflow.WorkflowService; /** * Stateful screen for forum application. * * @author <a href="mailto:[email protected]">Pawe� Potempski</a> * @version $Id: Forum.java,v 1.16 2008-05-29 22:55:43 rafal Exp $ */ public class Forum extends BaseSkinableScreen { /** forum serivce. */ protected ForumService forumService; protected WorkflowService workflowService; private Set<String> allowedStates = new HashSet<String>(); private final List<String> REQUIRES_AUTHENTICATED_USER = Arrays.asList("ModeratorTasks", "EditMessage"); public Forum(org.objectledge.context.Context context, Logger logger, PreferencesService preferencesService, CmsDataFactory cmsDataFactory, StructureService structureService, StyleService styleService, SkinService skinService, MVCFinder mvcFinder, TableStateManager tableStateManager, ForumService forumService, WorkflowService workflowService) { super(context, logger, preferencesService, cmsDataFactory, structureService, styleService, skinService, mvcFinder, tableStateManager); this.forumService = forumService; this.workflowService = workflowService; allowedStates.add("Discussions"); allowedStates.add("EditMessage"); allowedStates.add("Messages"); allowedStates.add("Message"); allowedStates.add("NewMessage"); allowedStates.add("NewDiscussion"); allowedStates.add("ModeratorTasks"); } public String getState() throws ProcessingException { CmsData cmsData = cmsDataFactory.getCmsData(context); Parameters screenConfig = cmsData.getEmbeddedScreenConfig(); long did = screenConfig.getLong("did", -1); String defaultState = (did == -1) ? "Discussions" : "Messages"; Parameters parameters = RequestParameters.getRequestParameters(context); String state = parameters.get("state", defaultState); if(!allowedStates.contains(state)) { return null; } else if(did != -1 && "Discussions".equals(state)) { return defaultState; } return state; } public void prepareDiscussions(Context context) throws ProcessingException { Parameters parameters = RequestParameters.getRequestParameters(context); CoralSession coralSession = (CoralSession)context.getAttribute(CoralSession.class); HttpContext httpContext = HttpContext.getHttpContext(context); I18nContext i18nContext = I18nContext.getI18nContext(context); TemplatingContext templatingContext = TemplatingContext.getTemplatingContext(context); try { ForumResource forum = forumService.getForum(coralSession, getSite()); templatingContext.put("forum",forum); Resource[] res = coralSession.getStore().getResource(forum, "discussions"); if(res.length != 1) { screenError(getNode(), context, "discussions node not found in "+forum.getPath()); } Resource[] discussions = coralSession.getStore().getResource(res[0]); TableState state = tableStateManager.getState(context, "cms:screens:forum,Forum:discussions"); if(state.isNew()) { state.setTreeView(false); state.setPageSize(10); state.setSortColumnName("creation.time"); state.setAscSort(false); } TableModel model = new ResourceListTableModel(discussions, i18nContext.getLocale()); ArrayList<TableFilter> filters = new ArrayList<TableFilter>(); filters.add(new ProtectedViewFilter(coralSession, coralSession.getUserSubject())); TableTool helper = new TableTool(state, filters, model); templatingContext.put("discussions_table", helper); templatingContext.put("forum_tool", new ForumTool(coralSession)); res = coralSession.getStore().getResource(forum, "comments"); if(res.length != 1) { screenError(getNode(), context, "comments node not found in "+forum.getPath()); } Resource[] comments = coralSession.getStore().getResource(res[0]); TableState state2 = tableStateManager.getState(context, "cms:screens:forum,Forum:comments"); if(state2.isNew()) { state2.setTreeView(false); state2.setPageSize(10); state2.setSortColumnName("creation.time"); state2.setAscSort(false); } TableModel model2 = new ResourceListTableModel(comments, i18nContext.getLocale()); ArrayList<TableFilter> filters2 = new ArrayList<TableFilter>(); filters2.add(new ProtectedViewFilter(coralSession, coralSession.getUserSubject())); TableTool helper2 = new TableTool(state2, filters2, model2); templatingContext.put("comments_table", helper2); } catch(ForumException e) { screenError(getNode(), context, "resource not found", e); } catch(TableException e) { screenError(getNode(), context, "resource not found", e); } } public void prepareMessages(Context context) throws ProcessingException { Parameters parameters = RequestParameters.getRequestParameters(context); CoralSession coralSession = (CoralSession)context.getAttribute(CoralSession.class); HttpContext httpContext = HttpContext.getHttpContext(context); I18nContext i18nContext = I18nContext.getI18nContext(context); TemplatingContext templatingContext = TemplatingContext.getTemplatingContext(context); CmsData cmsData = cmsDataFactory.getCmsData(context); Parameters screenConfig = cmsData.getEmbeddedScreenConfig(); long level_expanded = screenConfig.getLong("level_expanded", 0); Long mid = parameters.getLong("mid", -1); long did = screenConfig.getLong("did", parameters.getLong("did", -1)); if(did == -1) { screenError(getNode(), context, "discussion id not found"); return; } try { DiscussionResource discussion = DiscussionResourceImpl.getDiscussionResource(coralSession,did); templatingContext.put("discussion",discussion); String tableInstance = "cms:screen:forum:ForumMessages:"+getNode().getIdString()+":"+discussion.getIdString(); String rootId = discussion.getIdString(); boolean showRoot = false; if(mid != -1) { tableInstance += ":" + mid.toString(); rootId = mid.toString(); showRoot = true; templatingContext.put("mid", mid); } TableState state = tableStateManager.getState(context, tableInstance); if(state.isNew()) { state.setTreeView(true); state.setRootId(rootId); state.setCurrentPage(0); state.setShowRoot(showRoot); state.setExpanded(rootId); state.setAllExpanded(false); state.setPageSize(10); state.setSortColumnName("creation.time"); state.setAscSort(false); } TableModel model = new MessageTableModel(coralSession, i18nContext.getLocale()); ArrayList<TableFilter> filters = new ArrayList<TableFilter>(); filters.add(new ProtectedViewFilter(coralSession, coralSession.getUserSubject())); - if(mid == -1 && level_expanded > 0 && state.isNew()) + if(mid == -1 && level_expanded > 0) { TableFilter[] filtersArray = new TableFilter[filters.size()]; filters.toArray(filtersArray); setLevelExpanded(model, filtersArray, state, level_expanded); } TableTool helper = new TableTool(state, filters, model); templatingContext.put("table",helper); templatingContext.put("forum_tool", new ForumTool(coralSession)); } catch(EntityDoesNotExistException e) { screenError(getNode(), context, "resource not fount ", e); } catch(TableException e) { screenError(getNode(), context, "failed to initialize table toolkit: ", e); } catch(Exception e) { screenError(getNode(), context, "Component exception: ", e); } } public void prepareModeratorTasks(Context context) throws ProcessingException { Parameters parameters = RequestParameters.getRequestParameters(context); CoralSession coralSession = (CoralSession)context.getAttribute(CoralSession.class); I18nContext i18nContext = I18nContext.getI18nContext(context); TemplatingContext templatingContext = TemplatingContext.getTemplatingContext(context); long mid = parameters.getLong("mid", -1); try { ForumResource forum = forumService.getForum(coralSession, getSite()); templatingContext.put("forum", forum); CmsData cmsData = cmsDataFactory.getCmsData(context); Parameters screenConfig = cmsData.getEmbeddedScreenConfig(); Long did = screenConfig.getLong("did", parameters.getLong("did", -1)); List messages = getModeratorTasks(coralSession, forum, did); if(messages.size() > 0 && mid == -1) { templatingContext.put("mid", ((Resource)messages.get(messages.size()-1)).getId()); } else { templatingContext.put("mid", mid); } String tableInstance = "cms:screen:forum:ModeratorTasks:"+getSite().getIdString(); TableState state = tableStateManager.getState(context, tableInstance); if(state.isNew()) { state.setTreeView(false); state.setPageSize(10); state.setSortColumnName("creation.time"); state.setAscSort(false); } TableModel model = new ResourceListTableModel(messages,i18nContext.getLocale()); TableTool helper = new TableTool(state, null, model); templatingContext.put("table", helper); templatingContext.put("forum_tool", new ForumTool(coralSession)); } catch(Exception e) { screenError(getNode(), context, "Component exception: ", e); } } public void prepareMessage(Context context) throws ProcessingException { Parameters parameters = RequestParameters.getRequestParameters(context); CoralSession coralSession = (CoralSession)context.getAttribute(CoralSession.class); HttpContext httpContext = HttpContext.getHttpContext(context); I18nContext i18nContext = I18nContext.getI18nContext(context); TemplatingContext templatingContext = TemplatingContext.getTemplatingContext(context); long mid = parameters.getLong("mid", -1); if(mid == -1) { screenError(getNode(), context, "Message id not found"); return; } try { MessageResource message = MessageResourceImpl.getMessageResource(coralSession,mid); templatingContext.put("message",message); List<Resource> children = new ArrayList<Resource>(Arrays.asList(coralSession.getStore().getResource( message))); CollectionFilter.apply(children, new ProtectedViewFilter(coralSession, coralSession.getUserSubject())); templatingContext.put("children", children); } catch(EntityDoesNotExistException e) { screenError(getNode(), context, "Resource not found", e); } } public void prepareEditMessage(Context context) throws ProcessingException { Parameters parameters = RequestParameters.getRequestParameters(context); CoralSession coralSession = (CoralSession)context.getAttribute(CoralSession.class); TemplatingContext templatingContext = TemplatingContext.getTemplatingContext(context); long mid = parameters.getLong("mid", -1); if(mid == -1) { screenError(getNode(), context, "Message id not found"); return; } try { MessageResource message = MessageResourceImpl.getMessageResource(coralSession, mid); templatingContext.put("message", message); } catch(EntityDoesNotExistException e) { screenError(getNode(), context, "Resource not found", e); } } public void prepareNewMessage(Context context) throws ProcessingException { Parameters parameters = RequestParameters.getRequestParameters(context); CoralSession coralSession = (CoralSession)context.getAttribute(CoralSession.class); HttpContext httpContext = HttpContext.getHttpContext(context); I18nContext i18nContext = I18nContext.getI18nContext(context); TemplatingContext templatingContext = TemplatingContext.getTemplatingContext(context); long did = parameters.getLong("did", -1); long mid = parameters.getLong("mid", -1); long resid = parameters.getLong("resid", -1); if(mid == -1 && did == -1 && resid == -1) { screenError(getNode(), context, "Discussion nor Message nor Resource id not found"); } try { if(did != -1) { DiscussionResource discussion = DiscussionResourceImpl.getDiscussionResource(coralSession,did); templatingContext.put("discussion",discussion); templatingContext.put("parent",discussion); } else if(mid != -1) { MessageResource message = MessageResourceImpl.getMessageResource(coralSession,mid); DiscussionResource discussion = message.getDiscussion(); templatingContext.put("parent_content",prepareContent(message.getContent())); templatingContext.put("discussion",discussion); templatingContext.put("parent",message); } else { templatingContext.put("resource", coralSession.getStore().getResource(resid)); } ForumResource forum = forumService.getForum(coralSession, getSite()); templatingContext.put("add_captcha",forum.getCaptchaEnabled(false)); } catch(EntityDoesNotExistException e) { screenError(getNode(), context, "Resource not found", e); } catch(ForumException e) { screenError(getNode(), context, "resource not found", e); } } public void prepareNewDiscussion(Context context) throws ProcessingException { try { CoralSession coralSession = (CoralSession)context.getAttribute(CoralSession.class); TemplatingContext templatingContext = TemplatingContext.getTemplatingContext(context); ForumResource forum = forumService.getForum(coralSession, getSite()); templatingContext.put("add_captcha",forum.getCaptchaEnabled(false)); } catch(ForumException e) { screenError(getNode(), context, "resource not found", e); } } private String prepareContent(String content) { StringBuilder sb = new StringBuilder(""); StringTokenizer st = new StringTokenizer(content, "\n", false); while (st.hasMoreTokens()) { sb.append(">"); sb.append(st.nextToken()); sb.append("\n"); } return sb.toString(); } private List getModeratorTasks(CoralSession coralSession, ForumResource forum, Long discussionId) throws ProcessingException { List messages = new ArrayList(); try { Resource[] nodes = null; ResourceClass messageClass = coralSession.getSchema().getResourceClass( "cms.forum.message"); AutomatonResource automaton = workflowService.getPrimaryAutomaton(coralSession, getSite().getParent().getParent(), messageClass); StateResource state = workflowService.getState(coralSession, automaton, "new"); QueryResults results = coralSession.getQuery().executeQuery( "FIND RESOURCE FROM cms.forum.message WHERE state = " + state.getIdString()); nodes = results.getArray(1); for(int i = 0; i < nodes.length; i++) { MessageResource message = (MessageResource)nodes[i]; if(discussionId == null || discussionId <= 0) { if(message.getDiscussion().getForum().equals(forum)) { messages.add(message); } } else { if(discussionId.equals(message.getDiscussion().getId())) { messages.add(message); } } } } catch(MalformedQueryException e) { throw new ProcessingException("Malformed query", e); } catch(EntityDoesNotExistException e) { throw new ProcessingException("cms.forum.message resource does not exist", e); } catch(WorkflowException e) { throw new ProcessingException("Workflow state does not exist", e); } catch(ProcessingException e) { throw new ProcessingException("Processing Exception", e); } return messages; } void setLevelExpanded(TableModel model, TableFilter[] filtersArray, TableState state, Long level_expanded) { TableRow[] rows = model.getRowSet(state, filtersArray).getRows(); for(int i = 0; i < rows.length; i++) { if(!state.isExpanded(rows[i].getId()) && rows[i].getDepth() < level_expanded) { state.setExpanded(rows[i].getId()); if(rows[i].getChildCount() > 0) { setLevelExpanded(model, filtersArray, state, level_expanded); } } } } @Override public boolean requiresAuthenticatedUser(Context context) throws Exception { return REQUIRES_AUTHENTICATED_USER.contains(getState()); } @Override public boolean checkAccessRights(Context context) throws ProcessingException { CoralSession coralSession = (CoralSession)context.getAttribute(CoralSession.class); CmsData cmsData = cmsDataFactory.getCmsData(context); String state = getState(); if("ModeratorTasks".equals(state)) { try { Permission moderatePermission = coralSession.getSecurity().getUniquePermission( "cms.forum.moderate"); ForumResource forum = forumService.getForum(coralSession, getSite()); return getNode().canView(coralSession, cmsData, cmsData.getUserData().getSubject()) && coralSession.getUserSubject().hasPermission(forum, moderatePermission); } catch(Exception e) { return false; } } else if("EditMessage".equals(state)) { try { Permission modifyPermission = coralSession.getSecurity().getUniquePermission( "cms.forum.modify"); ForumResource forum = forumService.getForum(coralSession, getSite()); return getNode().canView(coralSession, cmsData, cmsData.getUserData().getSubject()) && coralSession.getUserSubject().hasPermission(forum, modifyPermission); } catch(Exception e) { return false; } } else { if(isNodeDefined()) { return getNode().canView(coralSession, cmsData, cmsData.getUserData().getSubject()); } else { return true; } } } public class ForumTool { final protected CoralSession coralSession; ForumTool(CoralSession coralSession) { this.coralSession = coralSession; } /* * return VisibleMessages count */ public int getVisibleMessages(DiscussionResource discussion) { return forumService.getVisibleMessages(coralSession, discussion, coralSession.getUserSubject()); } /* * return Visible sub messages count of message */ public int getVisibleSubMessages(MessageResource message) { return forumService.getVisibleSubMessages(coralSession, message, coralSession.getUserSubject()); } /* * return the date of last modified message or discussion child visible to a particular subject. */ public Date getLastModifiedMessage(Resource message) { return forumService.getLastModifiedMessage(coralSession, message, coralSession.getUserSubject()); } /* * return ModeratorTasks count form defined discussion */ public int getModeratorTasks(Long discussionId) { try { ForumResource forum = forumService.getForum(coralSession, getSite()); return Forum.this.getModeratorTasks(coralSession, forum, discussionId).size(); } catch(ProcessingException e) { return 0; } catch(ForumException e) { return 0; } } /* * return ModeratorTasks count for all discussions */ public int getModeratorTasks() { return getModeratorTasks(null); } } }
true
true
public void prepareMessages(Context context) throws ProcessingException { Parameters parameters = RequestParameters.getRequestParameters(context); CoralSession coralSession = (CoralSession)context.getAttribute(CoralSession.class); HttpContext httpContext = HttpContext.getHttpContext(context); I18nContext i18nContext = I18nContext.getI18nContext(context); TemplatingContext templatingContext = TemplatingContext.getTemplatingContext(context); CmsData cmsData = cmsDataFactory.getCmsData(context); Parameters screenConfig = cmsData.getEmbeddedScreenConfig(); long level_expanded = screenConfig.getLong("level_expanded", 0); Long mid = parameters.getLong("mid", -1); long did = screenConfig.getLong("did", parameters.getLong("did", -1)); if(did == -1) { screenError(getNode(), context, "discussion id not found"); return; } try { DiscussionResource discussion = DiscussionResourceImpl.getDiscussionResource(coralSession,did); templatingContext.put("discussion",discussion); String tableInstance = "cms:screen:forum:ForumMessages:"+getNode().getIdString()+":"+discussion.getIdString(); String rootId = discussion.getIdString(); boolean showRoot = false; if(mid != -1) { tableInstance += ":" + mid.toString(); rootId = mid.toString(); showRoot = true; templatingContext.put("mid", mid); } TableState state = tableStateManager.getState(context, tableInstance); if(state.isNew()) { state.setTreeView(true); state.setRootId(rootId); state.setCurrentPage(0); state.setShowRoot(showRoot); state.setExpanded(rootId); state.setAllExpanded(false); state.setPageSize(10); state.setSortColumnName("creation.time"); state.setAscSort(false); } TableModel model = new MessageTableModel(coralSession, i18nContext.getLocale()); ArrayList<TableFilter> filters = new ArrayList<TableFilter>(); filters.add(new ProtectedViewFilter(coralSession, coralSession.getUserSubject())); if(mid == -1 && level_expanded > 0 && state.isNew()) { TableFilter[] filtersArray = new TableFilter[filters.size()]; filters.toArray(filtersArray); setLevelExpanded(model, filtersArray, state, level_expanded); } TableTool helper = new TableTool(state, filters, model); templatingContext.put("table",helper); templatingContext.put("forum_tool", new ForumTool(coralSession)); } catch(EntityDoesNotExistException e) { screenError(getNode(), context, "resource not fount ", e); } catch(TableException e) { screenError(getNode(), context, "failed to initialize table toolkit: ", e); } catch(Exception e) { screenError(getNode(), context, "Component exception: ", e); } }
public void prepareMessages(Context context) throws ProcessingException { Parameters parameters = RequestParameters.getRequestParameters(context); CoralSession coralSession = (CoralSession)context.getAttribute(CoralSession.class); HttpContext httpContext = HttpContext.getHttpContext(context); I18nContext i18nContext = I18nContext.getI18nContext(context); TemplatingContext templatingContext = TemplatingContext.getTemplatingContext(context); CmsData cmsData = cmsDataFactory.getCmsData(context); Parameters screenConfig = cmsData.getEmbeddedScreenConfig(); long level_expanded = screenConfig.getLong("level_expanded", 0); Long mid = parameters.getLong("mid", -1); long did = screenConfig.getLong("did", parameters.getLong("did", -1)); if(did == -1) { screenError(getNode(), context, "discussion id not found"); return; } try { DiscussionResource discussion = DiscussionResourceImpl.getDiscussionResource(coralSession,did); templatingContext.put("discussion",discussion); String tableInstance = "cms:screen:forum:ForumMessages:"+getNode().getIdString()+":"+discussion.getIdString(); String rootId = discussion.getIdString(); boolean showRoot = false; if(mid != -1) { tableInstance += ":" + mid.toString(); rootId = mid.toString(); showRoot = true; templatingContext.put("mid", mid); } TableState state = tableStateManager.getState(context, tableInstance); if(state.isNew()) { state.setTreeView(true); state.setRootId(rootId); state.setCurrentPage(0); state.setShowRoot(showRoot); state.setExpanded(rootId); state.setAllExpanded(false); state.setPageSize(10); state.setSortColumnName("creation.time"); state.setAscSort(false); } TableModel model = new MessageTableModel(coralSession, i18nContext.getLocale()); ArrayList<TableFilter> filters = new ArrayList<TableFilter>(); filters.add(new ProtectedViewFilter(coralSession, coralSession.getUserSubject())); if(mid == -1 && level_expanded > 0) { TableFilter[] filtersArray = new TableFilter[filters.size()]; filters.toArray(filtersArray); setLevelExpanded(model, filtersArray, state, level_expanded); } TableTool helper = new TableTool(state, filters, model); templatingContext.put("table",helper); templatingContext.put("forum_tool", new ForumTool(coralSession)); } catch(EntityDoesNotExistException e) { screenError(getNode(), context, "resource not fount ", e); } catch(TableException e) { screenError(getNode(), context, "failed to initialize table toolkit: ", e); } catch(Exception e) { screenError(getNode(), context, "Component exception: ", e); } }
diff --git a/src/com/parworks/androidlibrary/response/ImageOverlayInfo.java b/src/com/parworks/androidlibrary/response/ImageOverlayInfo.java index 2663fda..cb31055 100644 --- a/src/com/parworks/androidlibrary/response/ImageOverlayInfo.java +++ b/src/com/parworks/androidlibrary/response/ImageOverlayInfo.java @@ -1,105 +1,106 @@ package com.parworks.androidlibrary.response; import java.io.IOException; import java.io.Serializable; import java.util.List; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; @SuppressWarnings("serial") public class ImageOverlayInfo implements Serializable { private String site; private String content; private String id; private String imageId; private String accuracy; private String name; private List<OverlayPoint> points; /** * The configuration object by parsing the content value. * * The reason to not replace content String with this object * is to better handle old overlay content without the JSON * format. */ private OverlayConfiguration configuration; public String getSite() { return site; } public void setSite(String site) { this.site = site; } public String getContent() { return content; } public void setContent(String content) { this.content = content; // parse the content whenever this is set parseOverlayContent(); } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getImageId() { return imageId; } public void setImageId(String imageId) { this.imageId = imageId; } public String getAccuracy() { return accuracy; } public void setAccuracy(String accuracy) { this.accuracy = accuracy; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<OverlayPoint> getPoints() { return points; } public void setPoints(List<OverlayPoint> points) { this.points = points; } public OverlayConfiguration getConfiguration() { return configuration; } private void parseOverlayContent() { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); try { - this.configuration = mapper.readValue(content, OverlayConfiguration.class); + this.configuration = content == null ? new OverlayConfiguration() + : mapper.readValue(content, OverlayConfiguration.class); } catch (IOException e) { // when failing to parse the overlay content, // generate an empty object and use default for everything this.configuration = new OverlayConfiguration(); } } }
true
true
private void parseOverlayContent() { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); try { this.configuration = mapper.readValue(content, OverlayConfiguration.class); } catch (IOException e) { // when failing to parse the overlay content, // generate an empty object and use default for everything this.configuration = new OverlayConfiguration(); } }
private void parseOverlayContent() { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); try { this.configuration = content == null ? new OverlayConfiguration() : mapper.readValue(content, OverlayConfiguration.class); } catch (IOException e) { // when failing to parse the overlay content, // generate an empty object and use default for everything this.configuration = new OverlayConfiguration(); } }
diff --git a/src/routeagents/Car.java b/src/routeagents/Car.java index 9edf4aa..e875b57 100644 --- a/src/routeagents/Car.java +++ b/src/routeagents/Car.java @@ -1,237 +1,238 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package routeagents; import jade.core.AID; import jade.core.Agent; import jade.lang.acl.ACLMessage; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import java.util.Hashtable; import java.util.concurrent.CopyOnWriteArrayList; /** * * @author Felipe V Nambara */ public class Car extends Agent { int current = 0; boolean wait = false; ArrayList<Pair> pairs = new ArrayList<Pair>(); // route done by car @Override protected void setup() { super.setup(); RouteAgents.agents.add(this); addBehaviour(new CarReceiving(this)); addBehaviour(new CarBehavior(this)); } void startWay() { while (this.current != RouteAgents.graphRoute.length - 1) { ArrayList<Integer> neibhgours = getNeighbours(); // Creating message to ask for route options StringBuffer message = new StringBuffer(); message.append("01\n"); for (int n : neibhgours) { message.append(this.current); message.append(";"); message.append(n); message.append(";"); message.append("0"); message.append(";"); message.append("0"); message.append("\n"); } ArrayList <Pair> ways = new ArrayList<Pair>(); // Ask antoher agents for options ACLMessage msg = new ACLMessage(ACLMessage.REQUEST); for (Agent a : RouteAgents.agents) { if (!a.getAID().getLocalName().equals(this.getAID().getLocalName())) { msg.addReceiver(new AID(a.getLocalName(), AID.ISLOCALNAME)); } } msg.setContent(message.toString()); this.send(msg); String[] parse; ACLMessage rec; while ((rec = receive()) != null) { if (rec != null) { parse = rec.getContent().split("\n"); if (parse[0].equals("02")) { for (int i = 1; i < parse.length; i++) { String[] pair = parse[i].split(";"); Pair p = new Pair(Integer.parseInt(pair[0]), Integer.parseInt(pair[1]), Double.parseDouble(pair[2])); ways.add(p); } } } } boolean withoutOptions = true; //int loops = 0; for (Pair p : ways) { withoutOptions = withoutOptions && neibhgours.indexOf(p.getEnd()) == -1; } + withoutOptions = withoutOptions && ways.size() == neibhgours.size(); // Trying to find options 15 times... /*while (ways.size() == 0 && loops <= 1) { // Doesn't have options if none of the agents did the same way for (Pair p : ways) { withoutOptions = withoutOptions && neibhgours.indexOf(p.getEnd()) == -1; } //System.out.println("agente " + this.getAID().getLocalName() + " aguardando resposta..."); if (ways.size() > 0) { System.out.println("agente " + this.getAID().getLocalName() + " encontrou outros agentes que fizeram este caminho !!!!!!!!!!!!!!!!!!!!!!!!!"); } // Give a time to agents make the wanted way try { Thread.sleep(100); } catch (InterruptedException ex) { Logger.getLogger(Car.class.getName()).log(Level.SEVERE, null, ex); } loops++; }*/ Hashtable prob = new Hashtable(); // Probabilities are the same if doesn't have options... if (withoutOptions) { for (int n : neibhgours) { prob.put(n, 100.00 / neibhgours.size()); } } else { // ...or are proportional to the routes's intervals double inverseTotal = 0; Hashtable inverses = new Hashtable(); for (Pair pair : ways) { double inverse = 1 / pair.getInterval(); inverses.put(pair.getEnd(), inverse); inverseTotal += inverse; } for (int n : neibhgours) { double p = ((Double) inverses.get(n)) * 100.00 / inverseTotal; prob.put(n, p); } } // Heuristic route choice based on the probabilities int v = 0; double x = Math.random() * 100; double y = 0; for (int n : neibhgours) { y += (Double) prob.get(n); if (x < y) { v = n; break; } } System.out.println("agente " + this.getAID().getLocalName() + " saiu do vértice " + this.current + " para o " + v); moveTo(this.current, v); } System.out.println("agente " + this.getAID().getLocalName() + " finalizando caminho"); } ArrayList<Integer> getNeighbours() { ArrayList<Integer> neighbours = new ArrayList<Integer>(); for (int i = 0; i < RouteAgents.graphRoute[current].length; i++) { if (RouteAgents.graphRoute[current][i] == 1) { neighbours.add(i); } } return neighbours; } void moveTo(int start, int end) { Pair pair = new Pair(start, end, calculateInterval(start, end)); pairs.add(pair); this.current = end; } private Double calculateInterval(int start, int end) { Double interval; interval = RouteAgents.graphRoute[start][end] / RouteAgents.graphVelocity[start][end]; return interval; } }
true
true
void startWay() { while (this.current != RouteAgents.graphRoute.length - 1) { ArrayList<Integer> neibhgours = getNeighbours(); // Creating message to ask for route options StringBuffer message = new StringBuffer(); message.append("01\n"); for (int n : neibhgours) { message.append(this.current); message.append(";"); message.append(n); message.append(";"); message.append("0"); message.append(";"); message.append("0"); message.append("\n"); } ArrayList <Pair> ways = new ArrayList<Pair>(); // Ask antoher agents for options ACLMessage msg = new ACLMessage(ACLMessage.REQUEST); for (Agent a : RouteAgents.agents) { if (!a.getAID().getLocalName().equals(this.getAID().getLocalName())) { msg.addReceiver(new AID(a.getLocalName(), AID.ISLOCALNAME)); } } msg.setContent(message.toString()); this.send(msg); String[] parse; ACLMessage rec; while ((rec = receive()) != null) { if (rec != null) { parse = rec.getContent().split("\n"); if (parse[0].equals("02")) { for (int i = 1; i < parse.length; i++) { String[] pair = parse[i].split(";"); Pair p = new Pair(Integer.parseInt(pair[0]), Integer.parseInt(pair[1]), Double.parseDouble(pair[2])); ways.add(p); } } } } boolean withoutOptions = true; //int loops = 0; for (Pair p : ways) { withoutOptions = withoutOptions && neibhgours.indexOf(p.getEnd()) == -1; } // Trying to find options 15 times... /*while (ways.size() == 0 && loops <= 1) { // Doesn't have options if none of the agents did the same way for (Pair p : ways) { withoutOptions = withoutOptions && neibhgours.indexOf(p.getEnd()) == -1; } //System.out.println("agente " + this.getAID().getLocalName() + " aguardando resposta..."); if (ways.size() > 0) { System.out.println("agente " + this.getAID().getLocalName() + " encontrou outros agentes que fizeram este caminho !!!!!!!!!!!!!!!!!!!!!!!!!"); } // Give a time to agents make the wanted way try { Thread.sleep(100); } catch (InterruptedException ex) { Logger.getLogger(Car.class.getName()).log(Level.SEVERE, null, ex); } loops++; }*/ Hashtable prob = new Hashtable(); // Probabilities are the same if doesn't have options... if (withoutOptions) { for (int n : neibhgours) { prob.put(n, 100.00 / neibhgours.size()); } } else { // ...or are proportional to the routes's intervals double inverseTotal = 0; Hashtable inverses = new Hashtable(); for (Pair pair : ways) { double inverse = 1 / pair.getInterval(); inverses.put(pair.getEnd(), inverse); inverseTotal += inverse; } for (int n : neibhgours) { double p = ((Double) inverses.get(n)) * 100.00 / inverseTotal; prob.put(n, p); } } // Heuristic route choice based on the probabilities int v = 0; double x = Math.random() * 100; double y = 0; for (int n : neibhgours) { y += (Double) prob.get(n); if (x < y) { v = n; break; } } System.out.println("agente " + this.getAID().getLocalName() + " saiu do vértice " + this.current + " para o " + v); moveTo(this.current, v); }
void startWay() { while (this.current != RouteAgents.graphRoute.length - 1) { ArrayList<Integer> neibhgours = getNeighbours(); // Creating message to ask for route options StringBuffer message = new StringBuffer(); message.append("01\n"); for (int n : neibhgours) { message.append(this.current); message.append(";"); message.append(n); message.append(";"); message.append("0"); message.append(";"); message.append("0"); message.append("\n"); } ArrayList <Pair> ways = new ArrayList<Pair>(); // Ask antoher agents for options ACLMessage msg = new ACLMessage(ACLMessage.REQUEST); for (Agent a : RouteAgents.agents) { if (!a.getAID().getLocalName().equals(this.getAID().getLocalName())) { msg.addReceiver(new AID(a.getLocalName(), AID.ISLOCALNAME)); } } msg.setContent(message.toString()); this.send(msg); String[] parse; ACLMessage rec; while ((rec = receive()) != null) { if (rec != null) { parse = rec.getContent().split("\n"); if (parse[0].equals("02")) { for (int i = 1; i < parse.length; i++) { String[] pair = parse[i].split(";"); Pair p = new Pair(Integer.parseInt(pair[0]), Integer.parseInt(pair[1]), Double.parseDouble(pair[2])); ways.add(p); } } } } boolean withoutOptions = true; //int loops = 0; for (Pair p : ways) { withoutOptions = withoutOptions && neibhgours.indexOf(p.getEnd()) == -1; } withoutOptions = withoutOptions && ways.size() == neibhgours.size(); // Trying to find options 15 times... /*while (ways.size() == 0 && loops <= 1) { // Doesn't have options if none of the agents did the same way for (Pair p : ways) { withoutOptions = withoutOptions && neibhgours.indexOf(p.getEnd()) == -1; } //System.out.println("agente " + this.getAID().getLocalName() + " aguardando resposta..."); if (ways.size() > 0) { System.out.println("agente " + this.getAID().getLocalName() + " encontrou outros agentes que fizeram este caminho !!!!!!!!!!!!!!!!!!!!!!!!!"); } // Give a time to agents make the wanted way try { Thread.sleep(100); } catch (InterruptedException ex) { Logger.getLogger(Car.class.getName()).log(Level.SEVERE, null, ex); } loops++; }*/ Hashtable prob = new Hashtable(); // Probabilities are the same if doesn't have options... if (withoutOptions) { for (int n : neibhgours) { prob.put(n, 100.00 / neibhgours.size()); } } else { // ...or are proportional to the routes's intervals double inverseTotal = 0; Hashtable inverses = new Hashtable(); for (Pair pair : ways) { double inverse = 1 / pair.getInterval(); inverses.put(pair.getEnd(), inverse); inverseTotal += inverse; } for (int n : neibhgours) { double p = ((Double) inverses.get(n)) * 100.00 / inverseTotal; prob.put(n, p); } } // Heuristic route choice based on the probabilities int v = 0; double x = Math.random() * 100; double y = 0; for (int n : neibhgours) { y += (Double) prob.get(n); if (x < y) { v = n; break; } } System.out.println("agente " + this.getAID().getLocalName() + " saiu do vértice " + this.current + " para o " + v); moveTo(this.current, v); }
diff --git a/src/main/java/com/authdb/util/Util.java b/src/main/java/com/authdb/util/Util.java index c387b2e..601d4af 100644 --- a/src/main/java/com/authdb/util/Util.java +++ b/src/main/java/com/authdb/util/Util.java @@ -1,1366 +1,1366 @@ /** (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.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.StringTokenizer; import java.util.regex.Matcher; import com.mysql.jdbc.Blob; import org.bukkit.Location; import org.bukkit.entity.Player; import com.authdb.AuthDB; import com.authdb.scripts.Custom; import com.authdb.scripts.cms.DLE; import com.authdb.scripts.cms.Drupal; import com.authdb.scripts.cms.Joomla; import com.authdb.scripts.cms.WordPress; import com.authdb.scripts.forum.BBPress; import com.authdb.scripts.forum.IPB; import com.authdb.scripts.forum.MyBB; import com.authdb.scripts.forum.PhpBB; import com.authdb.scripts.forum.PunBB; import com.authdb.scripts.forum.SMF; import com.authdb.scripts.forum.VBulletin; import com.authdb.scripts.forum.Vanilla; import com.authdb.scripts.forum.XenForo; import com.authdb.util.Messages.Message; import com.authdb.util.databases.EBean; import com.authdb.util.databases.MySQL; import com.authdb.util.encryption.Encryption; import com.avaje.ebean.Ebean; import com.craftfire.util.general.GeneralUtil; import com.craftfire.util.managers.CraftFireManager; import com.craftfire.util.managers.DatabaseManager; import com.craftfire.util.managers.LoggingManager; import com.craftfire.util.managers.ServerManager; public class Util { public static LoggingManager logging = new LoggingManager(); public static CraftFireManager craftFire = new CraftFireManager(); public static DatabaseManager databaseManager = new DatabaseManager(); public static GeneralUtil gUtil = new GeneralUtil(); public static com.authdb.util.managers.PlayerManager authDBplayer = new com.authdb.util.managers.PlayerManager(); public static com.craftfire.util.managers.PlayerManager craftFirePlayer = new com.craftfire.util.managers.PlayerManager(); public static ServerManager server = new ServerManager(); static int schedule = 1; public static boolean checkScript(String type, String script, String player, String password, String email, String ipAddress) throws SQLException { if(player != null) { player = player.toLowerCase(); } if (Util.databaseManager.getDatabaseType().equalsIgnoreCase("ebean")) { EBean eBeanClass = EBean.checkPlayer(player, true); if (type.equalsIgnoreCase("checkuser")) { if(eBeanClass.getRegistered().equalsIgnoreCase("true")) { return true; } return false; } else if (type.equalsIgnoreCase("checkpassword")) { String storedPassword = eBeanClass.getPassword(); if (Encryption.SHA512(password).equals(storedPassword)) { return true; } return false; } else if (type.equalsIgnoreCase("adduser")) { Custom.adduser(player, email, password, ipAddress); eBeanClass.setEmail(email); eBeanClass.setPassword(Encryption.SHA512(password)); eBeanClass.setRegistered("true"); eBeanClass.setIp(ipAddress); } else if (type.equalsIgnoreCase("numusers")) { int amount = EBean.getUsers(); logging.Info(amount + " user registrations in database"); } } else if (Config.database_ison) { String usertable = null, usernamefield = null, passwordfield = null, saltfield = ""; boolean bans = false; PreparedStatement ps = null; int number = 0; if (Config.custom_enabled) { if (type.equalsIgnoreCase("checkuser")) { String check = MySQL.getfromtable(Config.custom_table, "*", Config.custom_userfield, player); if (check != "fail") { Config.hasForumBoard = true; return true; } return false; } else if (type.equalsIgnoreCase("checkpassword")) { EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); if (Custom.check_hash(password, storedPassword)) { return true; } String hash = MySQL.getfromtable(Config.custom_table, "`" + Config.custom_passfield + "`", "" + Config.custom_userfield + "", player); EBean.checkPassword(player, hash); if (Custom.check_hash(password, hash)) { return true; } return false; } else if (type.equalsIgnoreCase("syncpassword")) { String hash = MySQL.getfromtable(Config.custom_table, "`" + Config.custom_passfield + "`", "" + Config.custom_userfield + "", player); EBean.checkPassword(player, hash); return true; } else if (type.equalsIgnoreCase("adduser")) { Custom.adduser(player, email, password, ipAddress); EBean.sync(player); return true; } else if (type.equalsIgnoreCase("numusers")) { ps = (PreparedStatement) MySQL.mysql.prepareStatement("SELECT COUNT(*) as `countit` FROM `" + Config.custom_table + "`"); ResultSet rs = ps.executeQuery(); if (rs.next()) { logging.Info(rs.getInt("countit") + " user registrations in database"); } } } else if (script.equalsIgnoreCase(PhpBB.Name) || script.equalsIgnoreCase(PhpBB.ShortName)) { usertable = "users"; //bantable = "banlist"; if (checkVersionInRange(PhpBB.VersionRange)) { usernamefield = "username_clean"; passwordfield = "user_password"; /*useridfield = "user_id"; banipfield = "ban_ip"; bannamefield = "ban_userid"; banreasonfield = "";*/ Config.hasForumBoard = true; number = 1; if (type.equalsIgnoreCase("checkpassword")) { EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); if (storedPassword != null && PhpBB.check_hash(password, storedPassword)) { return true; } String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player); EBean.checkPassword(player, hash); if (PhpBB.check_hash(password, hash)) { return true; } } /*else if (type.equalsIgnoreCase("checkban")) { String check = "fail"; if (ipAddress != null) { String userid = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + useridfield + "`", "" + usernamefield + "", player); check = MySQL.getfromtable(Config.script_tableprefix + "" + bantable + "", "`" + banipfield + "`", "" + bannamefield + "", userid); } else { check = MySQL.getfromtable(Config.script_tableprefix + "" + bantable + "", "`" + banipfield + "`", "" + banipfield + "", ipAddress); } if (check != "fail") { return true; } else { return false; } } */ } else if (checkVersionInRange(PhpBB.VersionRange2)) { usernamefield = "username_clean"; // TODO: use equalsIgnoreCase to allow for all variations? passwordfield = "user_password"; Config.hasForumBoard = true; bans = true; number = 2; if (type.equalsIgnoreCase("checkpassword")) { EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); if (storedPassword != null && PhpBB.check_hash(password, storedPassword)) { return true; } String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player); EBean.checkPassword(player, hash); if (PhpBB.check_hash(password, hash)) { return true; } } } if (type.equalsIgnoreCase("adduser")) { PhpBB.adduser(number, player, email, password, ipAddress); EBean.sync(player); return true; } } else if (script.equalsIgnoreCase(SMF.Name) || script.equalsIgnoreCase(SMF.ShortName)) { usertable = "members"; if (checkVersionInRange(SMF.VersionRange)) { usernamefield = "memberName"; passwordfield = "passwd"; saltfield = "passwordSalt"; Config.hasForumBoard = true; bans = true; number = 1; if (type.equalsIgnoreCase("checkpassword")) { EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); if (storedPassword != null && SMF.check_hash(SMF.hash(1, player, password), storedPassword)) { return true; } String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player); EBean.checkPassword(player, hash); if (SMF.check_hash(SMF.hash(1, player, password), hash)) { return true; } } } else if (checkVersionInRange(SMF.VersionRange2) || checkVersionInRange("2.0-2.0") || checkVersionInRange("2.0.0-2.0.0")) { usernamefield = "member_name"; passwordfield = "passwd"; Config.hasForumBoard = true; bans = true; number = 2; if (type.equalsIgnoreCase("checkpassword")) { EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); if (storedPassword != null && SMF.check_hash(SMF.hash(2, player, password), storedPassword)) { return true; } String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player); EBean.checkPassword(player, hash); if (SMF.check_hash(SMF.hash(2, player, password), hash)) { return true; } } } if (type.equalsIgnoreCase("adduser")) { SMF.adduser(number, player, email, password, ipAddress); EBean.sync(player); return true; } } else if (script.equalsIgnoreCase(MyBB.Name) || script.equalsIgnoreCase(MyBB.ShortName)) { usertable = "users"; if (checkVersionInRange(MyBB.VersionRange)) { saltfield = "salt"; usernamefield = "username"; passwordfield = "password"; Config.hasForumBoard = true; bans = true; number = 1; if (type.equalsIgnoreCase("checkpassword")) { EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); if (storedPassword != null && MyBB.check_hash(MyBB.hash("find", player, password, ""), storedPassword)) { return true; } String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player); EBean.checkPassword(player, hash); if (MyBB.check_hash(MyBB.hash("find", player, password, ""), hash)) { return true; } } } if (type.equalsIgnoreCase("adduser")) { MyBB.adduser(number, player, email, password, ipAddress); EBean.sync(player); return true; } } else if (script.equalsIgnoreCase(VBulletin.Name) || script.equalsIgnoreCase(VBulletin.ShortName)) { usertable = "user"; if (checkVersionInRange(VBulletin.VersionRange)) { saltfield = "salt"; usernamefield = "username"; passwordfield = "password"; Config.hasForumBoard = true; bans = true; number = 1; if (type.equalsIgnoreCase("checkpassword")) { EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); if (storedPassword != null && VBulletin.check_hash(VBulletin.hash("find", player, password, ""), storedPassword)) { return true; } String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player); EBean.checkPassword(player, hash); if (VBulletin.check_hash(VBulletin.hash("find", player, password, ""), hash)) { return true; } } } else if (checkVersionInRange(VBulletin.VersionRange2)) { usernamefield = "username"; passwordfield = "password"; Config.hasForumBoard = true; bans = true; number = 2; if (type.equalsIgnoreCase("checkpassword")) { EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); if (storedPassword != null && VBulletin.check_hash(VBulletin.hash("find", player, password, ""), storedPassword)) { return true; } String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player); EBean.checkPassword(player, hash); if (VBulletin.check_hash(VBulletin.hash("find", player, password, ""), hash)) { return true; } } } if (type.equalsIgnoreCase("adduser")) { VBulletin.adduser(number, player, email, password, ipAddress); EBean.sync(player); return true; } } else if (script.equalsIgnoreCase(Drupal.Name) || script.equalsIgnoreCase(Drupal.ShortName)) { usertable = "users"; if (checkVersionInRange(Drupal.VersionRange)) { usernamefield = "name"; passwordfield = "pass"; Config.hasForumBoard = true; number = 1; if (type.equalsIgnoreCase("checkpassword")) { EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); if (storedPassword != null && Encryption.md5(password).equals(storedPassword)) { return true; } String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player); EBean.checkPassword(player, hash); if (Encryption.md5(password).equals(hash)) { return true; } } } else if (checkVersionInRange(Drupal.VersionRange2)) { usernamefield = "name"; passwordfield = "pass"; Config.hasForumBoard = true; number = 2; if (type.equalsIgnoreCase("checkpassword")) { EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); if (storedPassword != null && storedPassword.equals(Drupal.user_check_password(password, storedPassword))) { return true; } String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player); EBean.checkPassword(player, hash); if (hash.equals(Drupal.user_check_password(password, hash))) { return true; } } } if (type.equalsIgnoreCase("adduser")) { Drupal.adduser(number, player, email, password, ipAddress); EBean.sync(player); return true; } } else if (script.equalsIgnoreCase(Joomla.Name) || script.equalsIgnoreCase(Joomla.ShortName)) { usertable = "users"; if (checkVersionInRange(Joomla.VersionRange)) { usernamefield = "username"; passwordfield = "password"; Config.hasForumBoard = true; number = 1; if (type.equalsIgnoreCase("checkpassword")) { EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); if (storedPassword != null && Joomla.check_hash(password, storedPassword)) { return true; } String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player); EBean.checkPassword(player, hash); if (Joomla.check_hash(password, hash)) { return true; } } } else if (checkVersionInRange(Joomla.VersionRange2)) { usernamefield = "username"; passwordfield = "password"; Config.hasForumBoard = true; number = 2; if (type.equalsIgnoreCase("checkpassword")) { EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); if (storedPassword != null && Joomla.check_hash(password, storedPassword)) { return true; } String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player); EBean.checkPassword(player, hash); if (Joomla.check_hash(password, hash)) { return true; } } } if (type.equalsIgnoreCase("adduser")) { Joomla.adduser(number, player, email, password, ipAddress); EBean.sync(player); return true; } } else if (script.equalsIgnoreCase(Vanilla.Name) || script.equalsIgnoreCase(Vanilla.ShortName)) { if (checkVersionInRange(Vanilla.VersionRange)) { usertable = "User"; usernamefield = "Name"; passwordfield = "Password"; if(Vanilla.check() == 2) { usertable = usertable.toLowerCase(); } Config.hasForumBoard = true; number = Vanilla.check(); if (type.equalsIgnoreCase("checkpassword")) { EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); if (storedPassword != null && Vanilla.check_hash(password, storedPassword)) { return true; } String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player); EBean.checkPassword(player, hash); if (Vanilla.check_hash(password, hash)) { return true; } } } if (type.equalsIgnoreCase("adduser")) { String emailcheck = MySQL.getfromtable(Config.script_tableprefix + usertable, "`Email`", "Email", email); if (emailcheck.equalsIgnoreCase("fail")) { Vanilla.adduser(number, player, email, password, ipAddress); EBean.sync(player); return true; } return false; } } else if (script.equalsIgnoreCase(PunBB.Name) || script.equalsIgnoreCase(PunBB.ShortName)) { usertable = "users"; //bantable = "bans"; if (checkVersionInRange(PunBB.VersionRange)) { // bannamefield = "username"; saltfield = "salt"; usernamefield = "username"; passwordfield = "password"; Config.hasForumBoard = true; number = 1; if (type.equalsIgnoreCase("checkpassword")) { EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); if (storedPassword != null && PunBB.check_hash(PunBB.hash("find", player, password, ""), storedPassword)) { return true; } String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player); EBean.checkPassword(player, hash); if (PunBB.check_hash(PunBB.hash("find", player, password, ""), hash)) { return true; } } } if (type.equalsIgnoreCase("adduser")) { PunBB.adduser(number, player, email, password, ipAddress); EBean.sync(player); return true; } } else if (script.equalsIgnoreCase(XenForo.Name) || script.equalsIgnoreCase(XenForo.ShortName)) { usertable = "user"; if (checkVersionInRange(XenForo.VersionRange)) { String userid = MySQL.getfromtable(Config.script_tableprefix + usertable, "`user_id`", "username", player); usernamefield = "username"; passwordfield = "password"; Config.hasForumBoard = true; number = 1; if (type.equalsIgnoreCase("checkpassword")) { Blob hash = MySQL.getfromtableBlob(Config.script_tableprefix + "user_authenticate", "`data`", "user_id", userid); if (hash != null) { int offset = -1; int chunkSize = 1024; long blobLength = hash.length(); if (chunkSize > blobLength) { chunkSize = (int) blobLength; } char buffer[] = new char[chunkSize]; StringBuilder stringBuffer = new StringBuilder(); Reader reader = new InputStreamReader(hash.getBinaryStream()); try { while ((offset = reader.read(buffer)) != -1) { stringBuffer.append(buffer, 0, offset); } } catch (IOException e) { // TODO Auto-generated catch block logging.StackTrace(e.getStackTrace(), Thread.currentThread().getStackTrace()[1].getMethodName(), Thread.currentThread().getStackTrace()[1].getLineNumber(), Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getFileName()); } String cache = stringBuffer.toString(); String thehash = forumCacheValue(cache, "hash"); String thesalt = forumCacheValue(cache, "salt"); EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); String storedSalt = eBeanClass.getSalt(); if (storedPassword != null && storedSalt != null && XenForo.check_hash(XenForo.hash(1, storedSalt, password), storedPassword)) { return true; } EBean.checkSalt(player, thesalt); EBean.checkPassword(player, thehash); if (XenForo.check_hash(XenForo.hash(1, thesalt, password), thehash)) { return true; } } else { return false; } } } if (type.equalsIgnoreCase("adduser")) { XenForo.adduser(number, player, email, password, ipAddress); EBean.sync(player); return true; } else if (Config.hasForumBoard && type.equalsIgnoreCase("syncpassword") && !Config.custom_enabled) { String userid = MySQL.getfromtable(Config.script_tableprefix + usertable, "`user_id`", "username", player); Blob hash = MySQL.getfromtableBlob(Config.script_tableprefix + "user_authenticate", "`data`", "user_id", userid); int offset = -1; int chunkSize = 1024; long blobLength = hash.length(); if (chunkSize > blobLength) { chunkSize = (int) blobLength; } char buffer[] = new char[chunkSize]; StringBuilder stringBuffer = new StringBuilder(); Reader reader = new InputStreamReader(hash.getBinaryStream()); try { while ((offset = reader.read(buffer)) != -1) { stringBuffer.append(buffer, 0, offset); } } catch (IOException e) { logging.StackTrace(e.getStackTrace(), Thread.currentThread().getStackTrace()[1].getMethodName(), Thread.currentThread().getStackTrace()[1].getLineNumber(), Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getFileName()); } String cache = stringBuffer.toString(); String thehash = forumCacheValue(cache, "hash"); EBean.checkPassword(player, thehash); return true; } else if (Config.hasForumBoard && type.equalsIgnoreCase("syncsalt") && !Config.custom_enabled && saltfield != null && saltfield != "") { String userid = MySQL.getfromtable(Config.script_tableprefix + usertable, "`user_id`", "username", player); Blob hash = MySQL.getfromtableBlob(Config.script_tableprefix + "user_authenticate", "`data`", "user_id", userid); int offset = -1; int chunkSize = 1024; long blobLength = hash.length(); if (chunkSize > blobLength) { chunkSize = (int) blobLength; } char buffer[] = new char[chunkSize]; StringBuilder stringBuffer = new StringBuilder(); Reader reader = new InputStreamReader(hash.getBinaryStream()); try { while ((offset = reader.read(buffer)) != -1) { stringBuffer.append(buffer, 0, offset); } } catch (IOException e) { // TODO Auto-generated catch block logging.StackTrace(e.getStackTrace(), Thread.currentThread().getStackTrace()[1].getMethodName(), Thread.currentThread().getStackTrace()[1].getLineNumber(), Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getFileName()); } String cache = stringBuffer.toString(); String thesalt = forumCacheValue(cache, "salt"); EBean.checkSalt(player, thesalt); return true; } } else if (script.equalsIgnoreCase(BBPress.Name) || script.equalsIgnoreCase(BBPress.ShortName)) { usertable = "users"; if (checkVersionInRange(BBPress.VersionRange)) { usernamefield = "user_login"; passwordfield = "user_pass"; Config.hasForumBoard = true; number = 1; if (type.equalsIgnoreCase("checkpassword")) { EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); if (storedPassword != null && BBPress.check_hash(password, storedPassword)) { return true; } String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player); EBean.checkPassword(player, hash); if (BBPress.check_hash(password, hash)) { return true; } } } if (type.equalsIgnoreCase("adduser")) { BBPress.adduser(number, player, email, password, ipAddress); EBean.sync(player); return true; } } else if (script.equalsIgnoreCase(DLE.Name) || script.equalsIgnoreCase(DLE.ShortName)) { usertable = "users"; if (checkVersionInRange(DLE.VersionRange)) { usernamefield = "name"; passwordfield = "password"; Config.hasForumBoard = true; number = 1; if (type.equalsIgnoreCase("checkpassword")) { EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); if (storedPassword != null && DLE.check_hash(DLE.hash(password), storedPassword)) { return true; } String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player); EBean.checkPassword(player, hash); if (DLE.check_hash(DLE.hash(password), hash)) { return true; } } } if (type.equalsIgnoreCase("adduser")) { DLE.adduser(number, player, email, password, ipAddress); EBean.sync(player); return true; } } else if (script.equalsIgnoreCase(IPB.Name) || script.equalsIgnoreCase(IPB.ShortName)) { usertable = "members"; if (checkVersionInRange(IPB.VersionRange)) { saltfield = "members_pass_salt"; usernamefield = "members_l_username"; passwordfield = "members_pass_hash"; Config.hasForumBoard = true; number = 1; if (type.equalsIgnoreCase("checkpassword")) { player = player.toLowerCase(); EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); if (storedPassword != null && IPB.check_hash(IPB.hash("find", player, password, null), storedPassword)) { return true; } String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", - passwordfield + "`", "" + usernamefield + "", player); + "`" + passwordfield + "`", "" + usernamefield + "", player); EBean.checkPassword(player, hash); if (IPB.check_hash(IPB.hash("find", player, password, null), hash)) { return true; } } } else if (checkVersionInRange(IPB.VersionRange2)) { saltfield = "members_pass_salt"; usernamefield = "members_l_username"; passwordfield = "members_pass_hash"; Config.hasForumBoard = true; number = 2; if (type.equalsIgnoreCase("checkpassword")) { player = player.toLowerCase(); EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); if (storedPassword != null && IPB.check_hash(IPB.hash("find", player, password, null), storedPassword)) { return true; } String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", passwordfield + "`", "" + usernamefield + "", player); EBean.checkPassword(player, hash); if (IPB.check_hash(IPB.hash("find", player, password, null), hash)) { return true; } } } if (type.equalsIgnoreCase("adduser")) { player = player.toLowerCase(); IPB.adduser(number, player, email, password, ipAddress); EBean.sync(player); return true; } } else if (script.equalsIgnoreCase(WordPress.Name) || script.equalsIgnoreCase(WordPress.ShortName)) { usertable = "users"; if (checkVersionInRange(WordPress.VersionRange)) { usernamefield = "user_login"; passwordfield = "user_pass"; Config.hasForumBoard = true; number = 1; if (type.equalsIgnoreCase("checkpassword")) { EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); if (storedPassword != null && WordPress.check_hash(password, storedPassword)) { return true; } String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player); EBean.checkPassword(player, hash); Util.logging.Info("HASH = "+hash); if (WordPress.check_hash(password, hash)) { return true; } } } if (type.equalsIgnoreCase("adduser")) { WordPress.adduser(number, player, email, password, ipAddress); EBean.sync(player); return true; } } /* else if (script.equalsIgnoreCase(Config.Script11_name) || script.equalsIgnoreCase(Config.Script11_shortname)) { usertable = "users"; if (checkVersionInRange(Config.Script11_versionrange)) { usernamefield = "username"; passwordfield = "password"; Config.hasForumBoard = true; number = 1; if (type.equalsIgnoreCase("checkpassword")) { String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player); if (XE.check_hash(password, hash)) { return true; } } } if (type.equalsIgnoreCase("adduser")) { XE.adduser(number, player, email, password, ipAddress); return true; } } */ if (!Config.hasForumBoard) { if (!Config.custom_enabled) { String tempVers = Config.script_version; Config.script_version = scriptVersion(); logging.Info("\n" + "|-----------------------------------------------------------------------------|\n" + "|--------------------------------AUTHDB WARNING-------------------------------|\n" + "|-----------------------------------------------------------------------------|\n" + "| COULD NOT FIND A COMPATIBLE SCRIPT VERSION, |\n" + "| PLEASE CHECK YOUR SCRIPT VERSION AND TRY AGAIN.PLUGIN MAY OR MAY NOT WORK. |\n" + "| YOUR SCRIPT VERSION FOR " + Config.script_name + " HAVE BEEN SET FROM " + tempVers + " TO " + Config.script_version + " |\n" + "| FOR A LIST OF SCRIPT VERSIONS, |\n" + "| CHECK: http://wiki.bukkit.org/AuthDB_(Plugin)#Scripts_Supported |\n" + "|-----------------------------------------------------------------------------|"); } } if (Config.hasForumBoard && type.equalsIgnoreCase("checkuser") && !Config.custom_enabled) { //EBean eBeanClass = EBean.find(player, Column.registered, "true"); //if (eBeanClass != null) { return true; } String check = MySQL.getfromtable(Config.script_tableprefix + usertable, "*", usernamefield, player); if (check != "fail") { return true; } return false; } /*else if (Config.hasForumBoard && type.equalsIgnoreCase("checkban") && !Config.custom_enabled && bantable != null) { String check = MySQL.getfromtable(Config.script_tableprefix + bantable, "*", bannamefield, player); if (check != "fail") { return true; } }*/ else if (Config.hasForumBoard && type.equalsIgnoreCase("numusers") && !Config.custom_enabled) { if (script.equalsIgnoreCase(PhpBB.Name) || script.equalsIgnoreCase(PhpBB.ShortName)) { ps = (PreparedStatement) MySQL.mysql.prepareStatement("SELECT COUNT(*) as `countit` FROM `" + Config.script_tableprefix + usertable + "` WHERE `group_id` !=6"); } else { ps = (PreparedStatement) MySQL.mysql.prepareStatement("SELECT COUNT(*) as `countit` FROM `" + Config.script_tableprefix + usertable + "`"); } ResultSet rs = ps.executeQuery(); if (rs.next()) { logging.Info(rs.getInt("countit") + " user registrations in database"); } } else if (Config.hasForumBoard && type.equalsIgnoreCase("syncpassword") && !Config.custom_enabled) { String hash = MySQL.getfromtable(Config.script_tableprefix + usertable, "`" + passwordfield + "`", usernamefield, player); EBean.checkPassword(player, hash); return true; } else if (Config.hasForumBoard && type.equalsIgnoreCase("syncsalt") && !Config.custom_enabled && saltfield != null && saltfield != "") { String salt = MySQL.getfromtable(Config.script_tableprefix + usertable, "`" + saltfield + "`", usernamefield, player); EBean.checkSalt(player, salt); return true; } } return false; } static String scriptVersion() { String script = Config.script_name; if (script.equalsIgnoreCase(PhpBB.Name) || script.equalsIgnoreCase(PhpBB.ShortName)) { return split(PhpBB.LatestVersionRange, "-")[1]; } else if (script.equalsIgnoreCase(SMF.Name) || script.equalsIgnoreCase(SMF.ShortName)) { return split(SMF.LatestVersionRange, "-")[1]; } else if (script.equalsIgnoreCase(MyBB.Name) || script.equalsIgnoreCase(MyBB.ShortName)) { return split(MyBB.LatestVersionRange, "-")[1]; } else if (script.equalsIgnoreCase(VBulletin.Name) || script.equalsIgnoreCase(VBulletin.ShortName)) { return split(VBulletin.LatestVersionRange, "-")[1]; } else if (script.equalsIgnoreCase(Drupal.Name) || script.equalsIgnoreCase(Drupal.ShortName)) { return split(Drupal.LatestVersionRange, "-")[1]; } else if (script.equalsIgnoreCase(Joomla.Name) || script.equalsIgnoreCase(Joomla.ShortName)) { return split(Joomla.LatestVersionRange, "-")[1]; } else if (script.equalsIgnoreCase(Vanilla.Name) || script.equalsIgnoreCase(Vanilla.ShortName)) { return split(Vanilla.LatestVersionRange, "-")[1]; } else if (script.equalsIgnoreCase(PunBB.Name) || script.equalsIgnoreCase(PunBB.ShortName)) { return split(PunBB.LatestVersionRange, "-")[1]; } else if (script.equalsIgnoreCase(XenForo.Name) || script.equalsIgnoreCase(XenForo.ShortName)) { return split(XenForo.LatestVersionRange, "-")[1]; } else if (script.equalsIgnoreCase(BBPress.Name) || script.equalsIgnoreCase(BBPress.ShortName)) { return split(BBPress.LatestVersionRange, "-")[1]; } else if (script.equalsIgnoreCase(DLE.Name) || script.equalsIgnoreCase(DLE.ShortName)) { return split(DLE.LatestVersionRange, "-")[1]; } else if (script.equalsIgnoreCase(IPB.Name) || script.equalsIgnoreCase(IPB.ShortName)) { return split(IPB.LatestVersionRange, "-")[1]; } else if (script.equalsIgnoreCase(WordPress.Name) || script.equalsIgnoreCase(WordPress.ShortName)) { return split(WordPress.LatestVersionRange, "-")[1]; } return null; } public static String[] split(String string, String delimiter) { String[] split = string.split(delimiter); return split; } static void fillChatField(Player player, String text) { for (int i = 0; i < 20; i++) { player.sendMessage(""); } player.sendMessage(text); } static void spamText(final Player player, final String text, final int delay, final int show) { //if (Config.login_delay > 0 && !AuthDB.AuthDB_SpamMessage.containsKey(player.getName())) { if (Config.login_delay > 0) { schedule = AuthDB.server.getScheduler().scheduleSyncDelayedTask(AuthDB.plugin, new Runnable() { @Override public void run() { /* if (AuthDB.isAuthorized(player) && AuthDB.AuthDB_SpamMessage.containsKey(player.getName())) { AuthDB.server.getScheduler().cancelTask(AuthDB.AuthDB_SpamMessage.get(player.getName())); AuthDB.AuthDB_SpamMessage.remove(player.getName()); AuthDB.AuthDB_SpamMessageTime.remove(player.getName()); } else { if (!AuthDB.AuthDB_SpamMessage.containsKey(player.getName())) { AuthDB.AuthDB_SpamMessage.put(player.getName(), schedule); } if (!AuthDB.AuthDB_SpamMessageTime.containsKey(player.getName())) { AuthDB.AuthDB_SpamMessageTime.put(player.getName(), timeStamp()); } if ((AuthDB.AuthDB_SpamMessageTime.get(player.getName()) + show) <= timeStamp()) { AuthDB.server.getScheduler().cancelTask(AuthDB.AuthDB_SpamMessage.get(player.getName())); AuthDB.AuthDB_SpamMessage.remove(player.getName()); AuthDB.AuthDB_SpamMessageTime.remove(player.getName()); } String message = replaceStrings(text, player, null); if (Config.link_rename && !checkOtherName(player.getName()).equals(player.getName())) { message = message.replaceAll(player.getName(), player.getDisplayName()); player.sendMessage(message); } else { player.sendMessage(message); } fillChatField(player, message); } */ String message = replaceStrings(text, player, null); if (Config.link_rename && !checkOtherName(player.getName()).equals(player.getName())) { message = message.replaceAll(player.getName(), player.getDisplayName()); player.sendMessage(message); } else { player.sendMessage(message); } } }, delay); } } public static long timeStamp() { return System.currentTimeMillis()/1000; } public static long timeMS() { return System.currentTimeMillis(); } boolean checkingBan(String usertable, String useridfield, String usernamefield, String username, String bantable, String banipfield, String bannamefield, String ipAddress) throws SQLException { String check = "fail"; if (ipAddress == null) { String userid = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + useridfield + "`", "" + usernamefield + "", username); check = MySQL.getfromtable(Config.script_tableprefix + "" + bantable + "", "`" + banipfield + "`", "" + bannamefield + "", userid); } else { check = MySQL.getfromtable(Config.script_tableprefix + "" + bantable + "", "`" + banipfield + "`", "" + bannamefield + "", ipAddress); } if (check != "fail") { return true; } else { return false; } } public static String forumCache(String cache, String player, int userid, String nummember, String activemembers, String newusername, String newuserid, String extrausername) { StringTokenizer st = new StringTokenizer(cache, ":"); int i = 0; List<String> array = new ArrayList<String>(); while (st.hasMoreTokens()) { array.add(st.nextToken() + ":"); } StringBuffer newcache = new StringBuffer(); while (array.size() > i) { if (array.get(i).equals("\"" + nummember + "\";s:") && nummember != null) { String temp = array.get(i + 2); temp = removeChar(temp, '"'); temp = removeChar(temp, ':'); temp = removeChar(temp, 's'); temp = removeChar(temp, ';'); temp = temp.trim(); int tempnum = Integer.parseInt(temp) + 1; String templength = "" + tempnum; temp = "\"" + tempnum + "\"" + ";s"; array.set(i + 1, templength.length() + ":"); array.set(i + 2, temp + ":"); } else if (array.get(i).equals("\"" + newusername + "\";s:") && newusername != null) { array.set(i + 1, player.length() + ":"); array.set(i + 2, "\"" + player + "\"" + ";s" + ":"); } else if (array.get(i).equals("\"" + extrausername + "\";s:") && extrausername != null) { array.set(i + 1, player.length() + ":"); array.set(i + 2, "\"" + player + "\"" + ";s" + ":"); } else if (array.get(i).equals("\"" + activemembers + "\";s:") && activemembers != null) { String temp = array.get(i + 2); temp = removeChar(temp, '"'); temp = removeChar(temp, ':'); temp = removeChar(temp, 's'); temp = removeChar(temp, ';'); temp = temp.trim(); int tempnum = Integer.parseInt(temp) + 1; String templength = "" + tempnum; temp = "\"" + tempnum + "\"" + ";s"; array.set(i + 1, templength.length() + ":"); array.set(i + 2, temp + ":"); } else if (array.get(i).equals("\"" + newuserid + "\";s:") && newuserid != null) { String dupe = "" + userid; array.set(i + 1, dupe.length() + ":"); array.set(i + 2, "\"" + userid + "\"" + ";" + "}"); } newcache.append(array.get(i)); i++; } return newcache.toString(); } public static String forumCacheValue(String cache, String value) { StringTokenizer st = new StringTokenizer(cache, ":"); int i = 0; List<String> array = new ArrayList<String>(); while (st.hasMoreTokens()) { array.add(st.nextToken() + ":"); } while (array.size() > i) { if (array.get(i).equals("\"" + value + "\";s:") && value != null) { String temp = array.get(i + 2); temp = removeChar(temp, '"'); temp = removeChar(temp, ':'); temp = removeChar(temp, 's'); temp = removeChar(temp, ';'); temp = temp.trim(); return temp; } i++; } return "no"; } public static boolean checkVersionInRange(String versionrange) { String version = Config.script_version; String[] versions = version.split("\\."); String[] versionss = versionrange.split("\\-"); String[] versionrange1= versionss[0].split("\\."); String[] versionrange2= versionss[1].split("\\."); if (versionrange1.length == versions.length) { int a = Integer.parseInt(versionrange1[0]); int b = Integer.parseInt(versionrange2[0]); int c = Integer.parseInt(versions[0]); if (a <= c && b >= c) { int d = b - c; if (d > 0) { return true; } else if (d == 0) { int a2 = Integer.parseInt(versionrange1[1]); int b2 = Integer.parseInt(versionrange2[1]); int c2 = Integer.parseInt(versions[1]); if (a2 <= c2 && b2 >= c2) { if (versionrange1.length == 2) { return true; } else if (versionrange1.length > 2) { int d2 = b2 - c2; if (d2 > 0) { return true; } else if (d2 == 0) { int a3 = Integer.parseInt(versionrange1[2]); int b3 = Integer.parseInt(versionrange2[2]); int c3 = Integer.parseInt(versions[2]); if (a3 <= c3 && b3 >= c3) { if (versionrange1.length != 4) { return true; } else if (versionrange1.length == 4) { int d3 = b3 - c3; if (d3 > 0) { return true; } else if (d3 == 0) { int a4 = Integer.parseInt(versionrange1[3]); int b4 = Integer.parseInt(versionrange2[3]); int c4 = Integer.parseInt(versions[3]); if (a4 <= c4 && b4 >= c4) { return true; } } } } } } } } } } return false; } public static int toTicks(String time, String length) { logging.Debug("Launching function: toTicks(String time, String length) - " + time + ":" + length); time = time.toLowerCase(); int lengthint = Integer.parseInt(length); if (time.equalsIgnoreCase("days") || time.equalsIgnoreCase("day") || time.equalsIgnoreCase("d")) { return lengthint * 1728000; } else if (time.equalsIgnoreCase("hours") || time.equalsIgnoreCase("hour") || time.equalsIgnoreCase("hr") || time.equalsIgnoreCase("hrs") || time.equalsIgnoreCase("h")) { return lengthint * 72000; } else if (time.equalsIgnoreCase("minute") || time.equalsIgnoreCase("minutes") || time.equalsIgnoreCase("min") || time.equalsIgnoreCase("mins") || time.equalsIgnoreCase("m")) { return lengthint * 1200; } else if (time.equalsIgnoreCase("seconds") || time.equalsIgnoreCase("seconds") || time.equalsIgnoreCase("sec") || time.equalsIgnoreCase("s")) { return lengthint * 20; } return 0; } public static int toSeconds(String time, String length) { logging.Debug("Launching function: toSeconds(String time, String length) - " + time + ":" + length); time = time.toLowerCase(); int lengthint = Integer.parseInt(length); if (time.equalsIgnoreCase("days") || time.equalsIgnoreCase("day") || time.equalsIgnoreCase("d")) return lengthint * 86400; else if (time.equalsIgnoreCase("hours") || time.equalsIgnoreCase("hour") || time.equalsIgnoreCase("hr") || time.equalsIgnoreCase("hrs") || time.equalsIgnoreCase("h")) return lengthint * 3600; else if (time.equalsIgnoreCase("minute") || time.equalsIgnoreCase("minutes") || time.equalsIgnoreCase("min") || time.equalsIgnoreCase("mins") || time.equalsIgnoreCase("m")) return lengthint * 60; else if (time.equalsIgnoreCase("seconds") || time.equalsIgnoreCase("seconds") || time.equalsIgnoreCase("sec") || time.equalsIgnoreCase("s")) return lengthint; return 0; } public static int stringToTicks(String string) { String[] split = string.split(" "); String length = split[0]; String time = split[1].toLowerCase(); int lengthint = Integer.parseInt(length); logging.Debug("Launching function: FullStringToSeconds(String time, String length) - " + time + ":" + length); if (time.equalsIgnoreCase("days") || time.equalsIgnoreCase("day") || time.equalsIgnoreCase("d")) return lengthint * 1728000; else if (time.equalsIgnoreCase("hours") || time.equalsIgnoreCase("hour") || time.equalsIgnoreCase("hr") || time.equalsIgnoreCase("hrs") || time.equalsIgnoreCase("h")) return lengthint * 72000; else if (time.equalsIgnoreCase("minute") || time.equalsIgnoreCase("minutes") || time.equalsIgnoreCase("min") || time.equalsIgnoreCase("mins") || time.equalsIgnoreCase("m")) return lengthint * 1200; else if (time.equalsIgnoreCase("seconds") || time.equalsIgnoreCase("seconds") || time.equalsIgnoreCase("sec") || time.equalsIgnoreCase("s")) return lengthint * 20; return 0; } public static int stringToSeconds(String string) { String[] split = string.split(" "); String length = split[0]; String time = split[1].toLowerCase(); int lengthint = Integer.parseInt(length); logging.Debug("Launching function: StringToSeconds(String time, String length) - " + time + ":" + length); if (time.equalsIgnoreCase("days") || time.equalsIgnoreCase("day") || time.equalsIgnoreCase("d")) { return lengthint * 86400; } else if (time.equalsIgnoreCase("hours") || time.equalsIgnoreCase("hour") || time.equalsIgnoreCase("hr") || time.equalsIgnoreCase("hrs") || time.equalsIgnoreCase("h")) { return lengthint * 3600; } else if (time.equalsIgnoreCase("minute") || time.equalsIgnoreCase("minutes") || time.equalsIgnoreCase("min") || time.equalsIgnoreCase("mins") || time.equalsIgnoreCase("m")) { return lengthint * 60; } else if (time.equalsIgnoreCase("second") || time.equalsIgnoreCase("seconds") || time.equalsIgnoreCase("sec") || time.equalsIgnoreCase("s")) { return lengthint; } return 0; } public static String toLoginMethod(String method) { method = method.toLowerCase(); if (method.equalsIgnoreCase("prompt")) return method; else return "normal"; } public static boolean checkWhitelist(String whitelist, Player player) { String username = player.getName().toLowerCase(); logging.Debug("Launching function: checkWhitelist(String whitelist, String username) - " + username); StringTokenizer st = null; if (whitelist.equalsIgnoreCase("username")) { st = new StringTokenizer(Config.filter_whitelist, ", "); } while (st != null && st.hasMoreTokens()) { String whitelistname = st.nextToken().toLowerCase(); logging.Debug("Whitelist: " + whitelistname); if (whitelistname.equals(username)) { logging.Debug("Found user in whitelist: " + whitelistname); if (whitelist.equalsIgnoreCase("username")) { Messages.sendMessage(Message.filter_whitelist, player, null); } return true; } } return false; } public static void checkIdle(Player player) { logging.Debug("Launching function: CheckIdle(Player player)"); if (!AuthDB.isAuthorized(player)) { Messages.sendMessage(Message.kickPlayerIdleLoginMessage, player, null); } } public static long ip2Long(String ip) { logging.Debug("Launching function: IP2Long(String IP)"); long f1, f2, f3, f4; String tokens[] = ip.split("\\."); if (tokens.length != 4) { return -1; } try { f1 = Long.parseLong(tokens[0]) << 24; f2 = Long.parseLong(tokens[1]) << 16; f3 = Long.parseLong(tokens[2]) << 8; f4 = Long.parseLong(tokens[3]); return f1 + f2 + f3 + f4; } catch (Exception e) { return -1; } } public static boolean checkFilter(String what, String string) { if (what.equalsIgnoreCase("username")) { logging.Debug("Launching function: checkFilter(String what, String string) - " + Config.filter_username); int lengtha = string.length(); int lengthb = Config.filter_username.length(); int i = 0; char thechar1, thechar2; while (i < lengtha) { thechar1 = string.charAt(i); int a = 0; while (a < lengthb) { thechar2 = Config.filter_username.charAt(a); //logging.Debug(i + "-" + thechar1 + ":" + a + "-" + thechar2); if (thechar1 == thechar2 || thechar1 == '\'' || thechar1 == '\"') { logging.Debug("FOUND BAD CHARACTER!!: " + thechar2); Config.has_badcharacters = true; return false; } a++; } i++; } Config.has_badcharacters = false; return true; } else if (what.equalsIgnoreCase("password")) { logging.Debug("Launching function: checkFilter(String what, String string) - " + Config.filter_password); int lengtha = string.length(); int lengthb = Config.filter_password.length(); int i = 0; char thechar1, thechar2; while (i < lengtha) { thechar1 = string.charAt(i); int a = 0; while (a < lengthb) { thechar2 = Config.filter_password.charAt(a); //logging.Debug(i + "-" + thechar1 + ":" + a + "-" + thechar2); if (thechar1 == thechar2 || thechar1 == '\'' || thechar1 == '\"') { logging.Debug("FOUND BAD CHARACTER!!: " + thechar2); return false; } a++; } i++; } return true; } return true; } public static String fixCharacters(String string) { int lengtha = string.length(); int lengthb = "`~!@#$%^&*()-= + {[]}|\\:;\"<, >.?/".length(); int i = 0; char thechar1, thechar2; StringBuffer tempstring = new StringBuffer(); while (i < lengtha) { thechar1 = string.charAt(i); int a = 0; while (a < lengthb) { thechar2 = "`~!@#$%^&*()-= + {[]}|\\:;\"<, >.?/".charAt(a); if (thechar1 == thechar2 || thechar1 == '\'' || thechar1 == '\"') { thechar1 = thechar2; } a++; } tempstring.append(thechar1); i++; } return tempstring.toString(); } public static String replaceStrings(String string, Player player, String additional) { long start = Util.timeMS(); logging.Debug(("Launching function: replaceStrings(String string, Player player, String additional)")); String extra = ""; if(additional != null) { extra = additional; } if (!Config.has_badcharacters && Config.database_ison && player != null && player.getName().length() > Integer.parseInt(Config.username_minimum) && player.getName().length() < Integer.parseInt(Config.username_maximum) && extra.equalsIgnoreCase("login") == false) { string = string.replaceAll("\\{IP\\}", craftFirePlayer.getIP(player)); string = string.replaceAll("\\{PLAYER\\}", player.getName()); string = string.replaceAll("\\{NEWPLAYER\\}", ""); string = string.replaceAll("\\{PLAYERNEW\\}", ""); string = string.replaceAll("&", "§"); if (!Util.checkOtherName(player.getName()).equals(player.getName())) { string = string.replaceAll("\\{DISPLAYNAME\\}", checkOtherName(player.getName())); } } else { string = string.replaceAll("&", Matcher.quoteReplacement("�")); } String email = ""; if(Config.custom_emailrequired) { email = "email"; } string = string.replaceAll("\\{USERMIN\\}", Config.username_minimum); string = string.replaceAll("\\{USERMAX\\}", Config.username_maximum); string = string.replaceAll("\\{PASSMIN\\}", Config.password_minimum); string = string.replaceAll("\\{PASSMAX\\}", Config.password_maximum); string = string.replaceAll("\\{PLUGIN\\}", AuthDB.pluginName); string = string.replaceAll("\\{VERSION\\}", AuthDB.pluginVersion); string = string.replaceAll("\\{LOGINTIMEOUT\\}", Config.login_timeout_length + " " + replaceTime(Config.login_timeout_length, Config.login_timeout_time)); string = string.replaceAll("\\{REGISTERTIMEOUT\\}", "" + Config.register_timeout_length + " " + replaceTime(Config.register_timeout_length, Config.register_timeout_time)); string = string.replaceAll("\\{USERBADCHARACTERS\\}", Matcher.quoteReplacement(Config.filter_username)); string = string.replaceAll("\\{PASSBADCHARACTERS\\}", Matcher.quoteReplacement(Config.filter_password)); string = string.replaceAll("\\{EMAILREQUIRED\\}", email); string = string.replaceAll("\\{NEWLINE\\}", "\n"); string = string.replaceAll("\\{newline\\}", "\n"); string = string.replaceAll("\\{N\\}", "\n"); string = string.replaceAll("\\{n\\}", "\n"); //COMMANDS string = string.replaceAll("\\{REGISTERCMD\\}", Config.commands_user_register + " (" + Config.aliases_user_register + ")"); string = string.replaceAll("\\{LINKCMD\\}", Config.commands_user_link + " (" + Config.aliases_user_link + ")"); string = string.replaceAll("\\{UNLINKCMD\\}", Config.commands_user_unlink + " (" + Config.aliases_user_unlink + ")"); string = string.replaceAll("\\{LOGINCMD\\}", Config.commands_user_login + " (" + Config.aliases_user_login + ")"); ///COLORS string = string.replaceAll("\\{BLACK\\}", "§0"); string = string.replaceAll("\\{DARKBLUE\\}", "§1"); string = string.replaceAll("\\{DARKGREEN\\}", "§2"); string = string.replaceAll("\\{DARKTEAL\\}", "§3"); string = string.replaceAll("\\{DARKRED\\}", "§4"); string = string.replaceAll("\\{PURPLE\\}", "§5"); string = string.replaceAll("\\{GOLD\\}", "§6"); string = string.replaceAll("\\{GRAY\\}", "§7"); string = string.replaceAll("\\{DARKGRAY\\}", "§8"); string = string.replaceAll("\\{BLUE\\}", "§9"); string = string.replaceAll("\\{BRIGHTGREEN\\}", "§a"); string = string.replaceAll("\\{TEAL\\}", "§b"); string = string.replaceAll("\\{RED\\}", "§c"); string = string.replaceAll("\\{PINK\\}", "§d"); string = string.replaceAll("\\{YELLOW\\}", "§e"); string = string.replaceAll("\\{WHITE\\}", "§f"); string = string.replaceAll("\\{BLACK\\}", "§0"); string = string.replaceAll("\\{NAVY\\}", "§1"); string = string.replaceAll("\\{GREEN\\}", "§2"); string = string.replaceAll("\\{BLUE\\}", "§3"); string = string.replaceAll("\\{RED\\}", "§4"); string = string.replaceAll("\\{PURPLE\\}", "§5"); string = string.replaceAll("\\{GOLD\\}", "§6"); string = string.replaceAll("\\{LIGHTGRAY\\}", "§7"); string = string.replaceAll("\\{GRAY\\}", "§8"); string = string.replaceAll("\\{DARKPURPLE\\}", "§9"); string = string.replaceAll("\\{LIGHTGREEN\\}", "§a"); string = string.replaceAll("\\{LIGHTBLUE\\}", "§b"); string = string.replaceAll("\\{ROSE\\}", "§c"); string = string.replaceAll("\\{LIGHTPURPLE\\}", "§d"); string = string.replaceAll("\\{YELLOW\\}", "§e"); string = string.replaceAll("\\{WHITE\\}", "§f"); ///colors string = string.replaceAll("\\{black\\}", "§0"); string = string.replaceAll("\\{darkblue\\}", "§1"); string = string.replaceAll("\\{darkgreen\\}", "§2"); string = string.replaceAll("\\{darkteal\\}", "§3"); string = string.replaceAll("\\{darkred\\}", "§4"); string = string.replaceAll("\\{purple\\}", "§5"); string = string.replaceAll("\\{gold\\}", "§6"); string = string.replaceAll("\\{gray\\}", "§7"); string = string.replaceAll("\\{darkgray\\}", "§8"); string = string.replaceAll("\\{blue\\}", "§9"); string = string.replaceAll("\\{brightgreen\\}", "§a"); string = string.replaceAll("\\{teal\\}", "§b"); string = string.replaceAll("\\{red\\}", "§c"); string = string.replaceAll("\\{pink\\}", "§d"); string = string.replaceAll("\\{yellow\\}", "§e"); string = string.replaceAll("\\{white\\}", "§f"); string = string.replaceAll("\\{black\\}", "§0"); string = string.replaceAll("\\{navy\\}", "§1"); string = string.replaceAll("\\{green\\}", "§2"); string = string.replaceAll("\\{blue\\}", "§3"); string = string.replaceAll("\\{red\\}", "§4"); string = string.replaceAll("\\{purple\\}", "§5"); string = string.replaceAll("\\{gold\\}", "§6"); string = string.replaceAll("\\{lightgray\\}", "§7"); string = string.replaceAll("\\{gray\\}", "§8"); string = string.replaceAll("\\{darkpurple\\}", "§9"); string = string.replaceAll("\\{lightgreen\\}", "§a"); string = string.replaceAll("\\{lightblue\\}", "§b"); string = string.replaceAll("\\{rose\\}", "§c"); string = string.replaceAll("\\{lightpurple\\}", "§d"); string = string.replaceAll("\\{yellow\\}", "§e"); string = string.replaceAll("\\{white\\}", "§f"); long stop = Util.timeMS(); Util.logging.Debug("Took " + ((stop - start) / 1000) + " seconds (" + (stop - start) + "ms) to replace tags."); return string; } public static String replaceTime(String length, String time) { int lengthint = Integer.parseInt(length); if (time.equalsIgnoreCase("days") || time.equalsIgnoreCase("day") || time.equalsIgnoreCase("d")) { if(lengthint > 1) { return Messages.time_days; } else { return Messages.time_day; } } else if (time.equalsIgnoreCase("hours") || time.equalsIgnoreCase("hour") || time.equalsIgnoreCase("hr") || time.equalsIgnoreCase("hrs") || time.equalsIgnoreCase("h")) { if(lengthint > 1) { return Messages.time_hours; } else { return Messages.time_hour; } } else if (time.equalsIgnoreCase("minute") || time.equalsIgnoreCase("minutes") || time.equalsIgnoreCase("min") || time.equalsIgnoreCase("mins") || time.equalsIgnoreCase("m")) { if(lengthint > 1) { return Messages.time_minutes; } else { return Messages.time_minute; } } else if (time.equalsIgnoreCase("seconds") || time.equalsIgnoreCase("seconds") || time.equalsIgnoreCase("sec") || time.equalsIgnoreCase("s")) { if(lengthint > 1) { return Messages.time_seconds; } else { return Messages.time_second; } } else if (time.equalsIgnoreCase("milliseconds") || time.equalsIgnoreCase("millisecond") || time.equalsIgnoreCase("milli") || time.equalsIgnoreCase("ms")) { if(lengthint > 1) { return Messages.time_milliseconds; } else { return Messages.time_millisecond; } } return time; } public static String removeColors(String toremove) { long start = Util.timeMS(); logging.Debug("Launching function: removeColors"); toremove = toremove.replace("?0", ""); toremove = toremove.replace("?2", ""); toremove = toremove.replace("?3", ""); toremove = toremove.replace("?4", ""); toremove = toremove.replace("?5", ""); toremove = toremove.replace("?6", ""); toremove = toremove.replace("?7", ""); toremove = toremove.replace("?8", ""); toremove = toremove.replace("?9", ""); toremove = toremove.replace("?a", ""); toremove = toremove.replace("?b", ""); toremove = toremove.replace("?c", ""); toremove = toremove.replace("?d", ""); toremove = toremove.replace("?e", ""); toremove = toremove.replace("?f", ""); long stop = Util.timeMS(); Util.logging.Debug("Took " + ((stop - start) / 1000) + " seconds (" + (stop - start) + "ms) to replace colors."); return toremove; } public static String removeChar(String s, char c) { logging.Debug("Launching function: removeChar(String s, char c)"); StringBuffer r = new StringBuffer(s.length()); r.setLength(s.length()); int current = 0; for (int i = 0; i < s.length(); i ++) { char cur = s.charAt(i); if (cur != c) r.setCharAt(current++, cur); } return r.toString(); } public static String getRandomString(int length) { String charset = "0123456789abcdefghijklmnopqrstuvwxyz"; Random rand = new Random(System.currentTimeMillis()); StringBuffer sb = new StringBuffer(); for (int i = 0; i < length; i++) { int pos = rand.nextInt(charset.length()); sb.append(charset.charAt(pos)); } return sb.toString(); } public static String getRandomString2(int length, String charset) { Random rand = new Random(System.currentTimeMillis()); StringBuffer sb = new StringBuffer(); for (int i = 0; i < length; i++) { int pos = rand.nextInt(charset.length()); sb.append(charset.charAt(pos)); } return sb.toString(); } public static int randomNumber(int min, int max) { return (int) (Math.random() * (max - min + 1)) + min; } public static Location landLocation(Location location) { while (location.getBlock().getType().getId() == 0) { location.setY(location.getY() - 1); } location.setY(location.getY() + 2); return location; } public static String checkOtherName(String player) { if (AuthDB.AuthDB_LinkedNames.containsKey(player)) { return AuthDB.AuthDB_LinkedNames.get(player); } else if (!AuthDB.AuthDB_LinkedNameCheck.containsKey(player)) { AuthDB.AuthDB_LinkedNameCheck.put(player, "yes"); EBean eBeanClass = EBean.checkPlayer(player, true); String linkedName = eBeanClass.getLinkedname(); if (linkedName != null && linkedName.equals("") == false) { AuthDB.AuthDB_LinkedNames.put(player, linkedName); return linkedName; } } return player; } public static boolean checkIfLoggedIn(Player player) { for (Player p : player.getServer().getOnlinePlayers()) { if (p.getName().equals(player.getName()) && AuthDB.isAuthorized(p)) { return true; } } return false; } public static String getAction(String action) { if (action.toLowerCase().equalsIgnoreCase("kick")) { return "kick"; } else if (action.toLowerCase().equalsIgnoreCase("ban")) { return "ban"; } else if (action.toLowerCase().equalsIgnoreCase("rename")) { return "rename"; } return "kick"; } public static int hexToInt(char ch) { if (ch >= '0' && ch <= '9') { return ch - '0'; } ch = Character.toUpperCase(ch); if (ch >= 'A' && ch <= 'F') { return ch - 'A' + 0xA; } throw new IllegalArgumentException("Not a hex character: " + ch); } public static String hexToString(String str) { char[] chars = str.toCharArray(); StringBuffer hex = new StringBuffer(); for (int i = 0; i < chars.length; i++) { hex.append(Integer.toHexString((int) chars[i])); } return hex.toString(); } public static String checkSessionStart (String string) { if (string.equalsIgnoreCase("login")) { return "login"; } else if (string.equalsIgnoreCase("logoff")) { return "logoff"; } else { return "login"; } } public static String convertToHex(byte[] data) { StringBuffer buf = new StringBuffer(); for (int i = 0; i < data.length; i++) { int halfbyte = (data[i] >>> 4) & 0x0F; int twoHalfs = 0; do { if ((0 <= halfbyte) && (halfbyte <= 9)) { buf.append((char) ('0' + halfbyte)); } else { buf.append((char) ('a' + (halfbyte - 10))); } halfbyte = data[i] & 0x0F; } while (twoHalfs++< 1); } return buf.toString(); } public static String bytes2hex(byte[] bytes) { StringBuffer r = new StringBuffer(); for (int i = 0; i < bytes.length; i++) { String x = Integer.toHexString(bytes[i] & 0xff); if (x.length() < 2) { r.append("0"); } r.append(x); } return r.toString(); } }
true
true
public static boolean checkScript(String type, String script, String player, String password, String email, String ipAddress) throws SQLException { if(player != null) { player = player.toLowerCase(); } if (Util.databaseManager.getDatabaseType().equalsIgnoreCase("ebean")) { EBean eBeanClass = EBean.checkPlayer(player, true); if (type.equalsIgnoreCase("checkuser")) { if(eBeanClass.getRegistered().equalsIgnoreCase("true")) { return true; } return false; } else if (type.equalsIgnoreCase("checkpassword")) { String storedPassword = eBeanClass.getPassword(); if (Encryption.SHA512(password).equals(storedPassword)) { return true; } return false; } else if (type.equalsIgnoreCase("adduser")) { Custom.adduser(player, email, password, ipAddress); eBeanClass.setEmail(email); eBeanClass.setPassword(Encryption.SHA512(password)); eBeanClass.setRegistered("true"); eBeanClass.setIp(ipAddress); } else if (type.equalsIgnoreCase("numusers")) { int amount = EBean.getUsers(); logging.Info(amount + " user registrations in database"); } } else if (Config.database_ison) { String usertable = null, usernamefield = null, passwordfield = null, saltfield = ""; boolean bans = false; PreparedStatement ps = null; int number = 0; if (Config.custom_enabled) { if (type.equalsIgnoreCase("checkuser")) { String check = MySQL.getfromtable(Config.custom_table, "*", Config.custom_userfield, player); if (check != "fail") { Config.hasForumBoard = true; return true; } return false; } else if (type.equalsIgnoreCase("checkpassword")) { EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); if (Custom.check_hash(password, storedPassword)) { return true; } String hash = MySQL.getfromtable(Config.custom_table, "`" + Config.custom_passfield + "`", "" + Config.custom_userfield + "", player); EBean.checkPassword(player, hash); if (Custom.check_hash(password, hash)) { return true; } return false; } else if (type.equalsIgnoreCase("syncpassword")) { String hash = MySQL.getfromtable(Config.custom_table, "`" + Config.custom_passfield + "`", "" + Config.custom_userfield + "", player); EBean.checkPassword(player, hash); return true; } else if (type.equalsIgnoreCase("adduser")) { Custom.adduser(player, email, password, ipAddress); EBean.sync(player); return true; } else if (type.equalsIgnoreCase("numusers")) { ps = (PreparedStatement) MySQL.mysql.prepareStatement("SELECT COUNT(*) as `countit` FROM `" + Config.custom_table + "`"); ResultSet rs = ps.executeQuery(); if (rs.next()) { logging.Info(rs.getInt("countit") + " user registrations in database"); } } } else if (script.equalsIgnoreCase(PhpBB.Name) || script.equalsIgnoreCase(PhpBB.ShortName)) { usertable = "users"; //bantable = "banlist"; if (checkVersionInRange(PhpBB.VersionRange)) { usernamefield = "username_clean"; passwordfield = "user_password"; /*useridfield = "user_id"; banipfield = "ban_ip"; bannamefield = "ban_userid"; banreasonfield = "";*/ Config.hasForumBoard = true; number = 1; if (type.equalsIgnoreCase("checkpassword")) { EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); if (storedPassword != null && PhpBB.check_hash(password, storedPassword)) { return true; } String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player); EBean.checkPassword(player, hash); if (PhpBB.check_hash(password, hash)) { return true; } } /*else if (type.equalsIgnoreCase("checkban")) { String check = "fail"; if (ipAddress != null) { String userid = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + useridfield + "`", "" + usernamefield + "", player); check = MySQL.getfromtable(Config.script_tableprefix + "" + bantable + "", "`" + banipfield + "`", "" + bannamefield + "", userid); } else { check = MySQL.getfromtable(Config.script_tableprefix + "" + bantable + "", "`" + banipfield + "`", "" + banipfield + "", ipAddress); } if (check != "fail") { return true; } else { return false; } } */ } else if (checkVersionInRange(PhpBB.VersionRange2)) { usernamefield = "username_clean"; // TODO: use equalsIgnoreCase to allow for all variations? passwordfield = "user_password"; Config.hasForumBoard = true; bans = true; number = 2; if (type.equalsIgnoreCase("checkpassword")) { EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); if (storedPassword != null && PhpBB.check_hash(password, storedPassword)) { return true; } String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player); EBean.checkPassword(player, hash); if (PhpBB.check_hash(password, hash)) { return true; } } } if (type.equalsIgnoreCase("adduser")) { PhpBB.adduser(number, player, email, password, ipAddress); EBean.sync(player); return true; } } else if (script.equalsIgnoreCase(SMF.Name) || script.equalsIgnoreCase(SMF.ShortName)) { usertable = "members"; if (checkVersionInRange(SMF.VersionRange)) { usernamefield = "memberName"; passwordfield = "passwd"; saltfield = "passwordSalt"; Config.hasForumBoard = true; bans = true; number = 1; if (type.equalsIgnoreCase("checkpassword")) { EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); if (storedPassword != null && SMF.check_hash(SMF.hash(1, player, password), storedPassword)) { return true; } String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player); EBean.checkPassword(player, hash); if (SMF.check_hash(SMF.hash(1, player, password), hash)) { return true; } } } else if (checkVersionInRange(SMF.VersionRange2) || checkVersionInRange("2.0-2.0") || checkVersionInRange("2.0.0-2.0.0")) { usernamefield = "member_name"; passwordfield = "passwd"; Config.hasForumBoard = true; bans = true; number = 2; if (type.equalsIgnoreCase("checkpassword")) { EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); if (storedPassword != null && SMF.check_hash(SMF.hash(2, player, password), storedPassword)) { return true; } String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player); EBean.checkPassword(player, hash); if (SMF.check_hash(SMF.hash(2, player, password), hash)) { return true; } } } if (type.equalsIgnoreCase("adduser")) { SMF.adduser(number, player, email, password, ipAddress); EBean.sync(player); return true; } } else if (script.equalsIgnoreCase(MyBB.Name) || script.equalsIgnoreCase(MyBB.ShortName)) { usertable = "users"; if (checkVersionInRange(MyBB.VersionRange)) { saltfield = "salt"; usernamefield = "username"; passwordfield = "password"; Config.hasForumBoard = true; bans = true; number = 1; if (type.equalsIgnoreCase("checkpassword")) { EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); if (storedPassword != null && MyBB.check_hash(MyBB.hash("find", player, password, ""), storedPassword)) { return true; } String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player); EBean.checkPassword(player, hash); if (MyBB.check_hash(MyBB.hash("find", player, password, ""), hash)) { return true; } } } if (type.equalsIgnoreCase("adduser")) { MyBB.adduser(number, player, email, password, ipAddress); EBean.sync(player); return true; } } else if (script.equalsIgnoreCase(VBulletin.Name) || script.equalsIgnoreCase(VBulletin.ShortName)) { usertable = "user"; if (checkVersionInRange(VBulletin.VersionRange)) { saltfield = "salt"; usernamefield = "username"; passwordfield = "password"; Config.hasForumBoard = true; bans = true; number = 1; if (type.equalsIgnoreCase("checkpassword")) { EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); if (storedPassword != null && VBulletin.check_hash(VBulletin.hash("find", player, password, ""), storedPassword)) { return true; } String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player); EBean.checkPassword(player, hash); if (VBulletin.check_hash(VBulletin.hash("find", player, password, ""), hash)) { return true; } } } else if (checkVersionInRange(VBulletin.VersionRange2)) { usernamefield = "username"; passwordfield = "password"; Config.hasForumBoard = true; bans = true; number = 2; if (type.equalsIgnoreCase("checkpassword")) { EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); if (storedPassword != null && VBulletin.check_hash(VBulletin.hash("find", player, password, ""), storedPassword)) { return true; } String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player); EBean.checkPassword(player, hash); if (VBulletin.check_hash(VBulletin.hash("find", player, password, ""), hash)) { return true; } } } if (type.equalsIgnoreCase("adduser")) { VBulletin.adduser(number, player, email, password, ipAddress); EBean.sync(player); return true; } } else if (script.equalsIgnoreCase(Drupal.Name) || script.equalsIgnoreCase(Drupal.ShortName)) { usertable = "users"; if (checkVersionInRange(Drupal.VersionRange)) { usernamefield = "name"; passwordfield = "pass"; Config.hasForumBoard = true; number = 1; if (type.equalsIgnoreCase("checkpassword")) { EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); if (storedPassword != null && Encryption.md5(password).equals(storedPassword)) { return true; } String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player); EBean.checkPassword(player, hash); if (Encryption.md5(password).equals(hash)) { return true; } } } else if (checkVersionInRange(Drupal.VersionRange2)) { usernamefield = "name"; passwordfield = "pass"; Config.hasForumBoard = true; number = 2; if (type.equalsIgnoreCase("checkpassword")) { EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); if (storedPassword != null && storedPassword.equals(Drupal.user_check_password(password, storedPassword))) { return true; } String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player); EBean.checkPassword(player, hash); if (hash.equals(Drupal.user_check_password(password, hash))) { return true; } } } if (type.equalsIgnoreCase("adduser")) { Drupal.adduser(number, player, email, password, ipAddress); EBean.sync(player); return true; } } else if (script.equalsIgnoreCase(Joomla.Name) || script.equalsIgnoreCase(Joomla.ShortName)) { usertable = "users"; if (checkVersionInRange(Joomla.VersionRange)) { usernamefield = "username"; passwordfield = "password"; Config.hasForumBoard = true; number = 1; if (type.equalsIgnoreCase("checkpassword")) { EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); if (storedPassword != null && Joomla.check_hash(password, storedPassword)) { return true; } String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player); EBean.checkPassword(player, hash); if (Joomla.check_hash(password, hash)) { return true; } } } else if (checkVersionInRange(Joomla.VersionRange2)) { usernamefield = "username"; passwordfield = "password"; Config.hasForumBoard = true; number = 2; if (type.equalsIgnoreCase("checkpassword")) { EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); if (storedPassword != null && Joomla.check_hash(password, storedPassword)) { return true; } String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player); EBean.checkPassword(player, hash); if (Joomla.check_hash(password, hash)) { return true; } } } if (type.equalsIgnoreCase("adduser")) { Joomla.adduser(number, player, email, password, ipAddress); EBean.sync(player); return true; } } else if (script.equalsIgnoreCase(Vanilla.Name) || script.equalsIgnoreCase(Vanilla.ShortName)) { if (checkVersionInRange(Vanilla.VersionRange)) { usertable = "User"; usernamefield = "Name"; passwordfield = "Password"; if(Vanilla.check() == 2) { usertable = usertable.toLowerCase(); } Config.hasForumBoard = true; number = Vanilla.check(); if (type.equalsIgnoreCase("checkpassword")) { EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); if (storedPassword != null && Vanilla.check_hash(password, storedPassword)) { return true; } String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player); EBean.checkPassword(player, hash); if (Vanilla.check_hash(password, hash)) { return true; } } } if (type.equalsIgnoreCase("adduser")) { String emailcheck = MySQL.getfromtable(Config.script_tableprefix + usertable, "`Email`", "Email", email); if (emailcheck.equalsIgnoreCase("fail")) { Vanilla.adduser(number, player, email, password, ipAddress); EBean.sync(player); return true; } return false; } } else if (script.equalsIgnoreCase(PunBB.Name) || script.equalsIgnoreCase(PunBB.ShortName)) { usertable = "users"; //bantable = "bans"; if (checkVersionInRange(PunBB.VersionRange)) { // bannamefield = "username"; saltfield = "salt"; usernamefield = "username"; passwordfield = "password"; Config.hasForumBoard = true; number = 1; if (type.equalsIgnoreCase("checkpassword")) { EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); if (storedPassword != null && PunBB.check_hash(PunBB.hash("find", player, password, ""), storedPassword)) { return true; } String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player); EBean.checkPassword(player, hash); if (PunBB.check_hash(PunBB.hash("find", player, password, ""), hash)) { return true; } } } if (type.equalsIgnoreCase("adduser")) { PunBB.adduser(number, player, email, password, ipAddress); EBean.sync(player); return true; } } else if (script.equalsIgnoreCase(XenForo.Name) || script.equalsIgnoreCase(XenForo.ShortName)) { usertable = "user"; if (checkVersionInRange(XenForo.VersionRange)) { String userid = MySQL.getfromtable(Config.script_tableprefix + usertable, "`user_id`", "username", player); usernamefield = "username"; passwordfield = "password"; Config.hasForumBoard = true; number = 1; if (type.equalsIgnoreCase("checkpassword")) { Blob hash = MySQL.getfromtableBlob(Config.script_tableprefix + "user_authenticate", "`data`", "user_id", userid); if (hash != null) { int offset = -1; int chunkSize = 1024; long blobLength = hash.length(); if (chunkSize > blobLength) { chunkSize = (int) blobLength; } char buffer[] = new char[chunkSize]; StringBuilder stringBuffer = new StringBuilder(); Reader reader = new InputStreamReader(hash.getBinaryStream()); try { while ((offset = reader.read(buffer)) != -1) { stringBuffer.append(buffer, 0, offset); } } catch (IOException e) { // TODO Auto-generated catch block logging.StackTrace(e.getStackTrace(), Thread.currentThread().getStackTrace()[1].getMethodName(), Thread.currentThread().getStackTrace()[1].getLineNumber(), Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getFileName()); } String cache = stringBuffer.toString(); String thehash = forumCacheValue(cache, "hash"); String thesalt = forumCacheValue(cache, "salt"); EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); String storedSalt = eBeanClass.getSalt(); if (storedPassword != null && storedSalt != null && XenForo.check_hash(XenForo.hash(1, storedSalt, password), storedPassword)) { return true; } EBean.checkSalt(player, thesalt); EBean.checkPassword(player, thehash); if (XenForo.check_hash(XenForo.hash(1, thesalt, password), thehash)) { return true; } } else { return false; } } } if (type.equalsIgnoreCase("adduser")) { XenForo.adduser(number, player, email, password, ipAddress); EBean.sync(player); return true; } else if (Config.hasForumBoard && type.equalsIgnoreCase("syncpassword") && !Config.custom_enabled) { String userid = MySQL.getfromtable(Config.script_tableprefix + usertable, "`user_id`", "username", player); Blob hash = MySQL.getfromtableBlob(Config.script_tableprefix + "user_authenticate", "`data`", "user_id", userid); int offset = -1; int chunkSize = 1024; long blobLength = hash.length(); if (chunkSize > blobLength) { chunkSize = (int) blobLength; } char buffer[] = new char[chunkSize]; StringBuilder stringBuffer = new StringBuilder(); Reader reader = new InputStreamReader(hash.getBinaryStream()); try { while ((offset = reader.read(buffer)) != -1) { stringBuffer.append(buffer, 0, offset); } } catch (IOException e) { logging.StackTrace(e.getStackTrace(), Thread.currentThread().getStackTrace()[1].getMethodName(), Thread.currentThread().getStackTrace()[1].getLineNumber(), Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getFileName()); } String cache = stringBuffer.toString(); String thehash = forumCacheValue(cache, "hash"); EBean.checkPassword(player, thehash); return true; } else if (Config.hasForumBoard && type.equalsIgnoreCase("syncsalt") && !Config.custom_enabled && saltfield != null && saltfield != "") { String userid = MySQL.getfromtable(Config.script_tableprefix + usertable, "`user_id`", "username", player); Blob hash = MySQL.getfromtableBlob(Config.script_tableprefix + "user_authenticate", "`data`", "user_id", userid); int offset = -1; int chunkSize = 1024; long blobLength = hash.length(); if (chunkSize > blobLength) { chunkSize = (int) blobLength; } char buffer[] = new char[chunkSize]; StringBuilder stringBuffer = new StringBuilder(); Reader reader = new InputStreamReader(hash.getBinaryStream()); try { while ((offset = reader.read(buffer)) != -1) { stringBuffer.append(buffer, 0, offset); } } catch (IOException e) { // TODO Auto-generated catch block logging.StackTrace(e.getStackTrace(), Thread.currentThread().getStackTrace()[1].getMethodName(), Thread.currentThread().getStackTrace()[1].getLineNumber(), Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getFileName()); } String cache = stringBuffer.toString(); String thesalt = forumCacheValue(cache, "salt"); EBean.checkSalt(player, thesalt); return true; } } else if (script.equalsIgnoreCase(BBPress.Name) || script.equalsIgnoreCase(BBPress.ShortName)) { usertable = "users"; if (checkVersionInRange(BBPress.VersionRange)) { usernamefield = "user_login"; passwordfield = "user_pass"; Config.hasForumBoard = true; number = 1; if (type.equalsIgnoreCase("checkpassword")) { EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); if (storedPassword != null && BBPress.check_hash(password, storedPassword)) { return true; } String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player); EBean.checkPassword(player, hash); if (BBPress.check_hash(password, hash)) { return true; } } } if (type.equalsIgnoreCase("adduser")) { BBPress.adduser(number, player, email, password, ipAddress); EBean.sync(player); return true; } } else if (script.equalsIgnoreCase(DLE.Name) || script.equalsIgnoreCase(DLE.ShortName)) { usertable = "users"; if (checkVersionInRange(DLE.VersionRange)) { usernamefield = "name"; passwordfield = "password"; Config.hasForumBoard = true; number = 1; if (type.equalsIgnoreCase("checkpassword")) { EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); if (storedPassword != null && DLE.check_hash(DLE.hash(password), storedPassword)) { return true; } String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player); EBean.checkPassword(player, hash); if (DLE.check_hash(DLE.hash(password), hash)) { return true; } } } if (type.equalsIgnoreCase("adduser")) { DLE.adduser(number, player, email, password, ipAddress); EBean.sync(player); return true; } } else if (script.equalsIgnoreCase(IPB.Name) || script.equalsIgnoreCase(IPB.ShortName)) { usertable = "members"; if (checkVersionInRange(IPB.VersionRange)) { saltfield = "members_pass_salt"; usernamefield = "members_l_username"; passwordfield = "members_pass_hash"; Config.hasForumBoard = true; number = 1; if (type.equalsIgnoreCase("checkpassword")) { player = player.toLowerCase(); EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); if (storedPassword != null && IPB.check_hash(IPB.hash("find", player, password, null), storedPassword)) { return true; } String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", passwordfield + "`", "" + usernamefield + "", player); EBean.checkPassword(player, hash); if (IPB.check_hash(IPB.hash("find", player, password, null), hash)) { return true; } } } else if (checkVersionInRange(IPB.VersionRange2)) { saltfield = "members_pass_salt"; usernamefield = "members_l_username"; passwordfield = "members_pass_hash"; Config.hasForumBoard = true; number = 2; if (type.equalsIgnoreCase("checkpassword")) { player = player.toLowerCase(); EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); if (storedPassword != null && IPB.check_hash(IPB.hash("find", player, password, null), storedPassword)) { return true; } String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", passwordfield + "`", "" + usernamefield + "", player); EBean.checkPassword(player, hash); if (IPB.check_hash(IPB.hash("find", player, password, null), hash)) { return true; } } } if (type.equalsIgnoreCase("adduser")) { player = player.toLowerCase(); IPB.adduser(number, player, email, password, ipAddress); EBean.sync(player); return true; } } else if (script.equalsIgnoreCase(WordPress.Name) || script.equalsIgnoreCase(WordPress.ShortName)) { usertable = "users"; if (checkVersionInRange(WordPress.VersionRange)) { usernamefield = "user_login"; passwordfield = "user_pass"; Config.hasForumBoard = true; number = 1; if (type.equalsIgnoreCase("checkpassword")) { EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); if (storedPassword != null && WordPress.check_hash(password, storedPassword)) { return true; } String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player); EBean.checkPassword(player, hash); Util.logging.Info("HASH = "+hash); if (WordPress.check_hash(password, hash)) { return true; } } } if (type.equalsIgnoreCase("adduser")) { WordPress.adduser(number, player, email, password, ipAddress); EBean.sync(player); return true; } } /* else if (script.equalsIgnoreCase(Config.Script11_name) || script.equalsIgnoreCase(Config.Script11_shortname)) { usertable = "users"; if (checkVersionInRange(Config.Script11_versionrange)) { usernamefield = "username"; passwordfield = "password"; Config.hasForumBoard = true; number = 1; if (type.equalsIgnoreCase("checkpassword")) { String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player); if (XE.check_hash(password, hash)) { return true; } } } if (type.equalsIgnoreCase("adduser")) { XE.adduser(number, player, email, password, ipAddress); return true; } } */
public static boolean checkScript(String type, String script, String player, String password, String email, String ipAddress) throws SQLException { if(player != null) { player = player.toLowerCase(); } if (Util.databaseManager.getDatabaseType().equalsIgnoreCase("ebean")) { EBean eBeanClass = EBean.checkPlayer(player, true); if (type.equalsIgnoreCase("checkuser")) { if(eBeanClass.getRegistered().equalsIgnoreCase("true")) { return true; } return false; } else if (type.equalsIgnoreCase("checkpassword")) { String storedPassword = eBeanClass.getPassword(); if (Encryption.SHA512(password).equals(storedPassword)) { return true; } return false; } else if (type.equalsIgnoreCase("adduser")) { Custom.adduser(player, email, password, ipAddress); eBeanClass.setEmail(email); eBeanClass.setPassword(Encryption.SHA512(password)); eBeanClass.setRegistered("true"); eBeanClass.setIp(ipAddress); } else if (type.equalsIgnoreCase("numusers")) { int amount = EBean.getUsers(); logging.Info(amount + " user registrations in database"); } } else if (Config.database_ison) { String usertable = null, usernamefield = null, passwordfield = null, saltfield = ""; boolean bans = false; PreparedStatement ps = null; int number = 0; if (Config.custom_enabled) { if (type.equalsIgnoreCase("checkuser")) { String check = MySQL.getfromtable(Config.custom_table, "*", Config.custom_userfield, player); if (check != "fail") { Config.hasForumBoard = true; return true; } return false; } else if (type.equalsIgnoreCase("checkpassword")) { EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); if (Custom.check_hash(password, storedPassword)) { return true; } String hash = MySQL.getfromtable(Config.custom_table, "`" + Config.custom_passfield + "`", "" + Config.custom_userfield + "", player); EBean.checkPassword(player, hash); if (Custom.check_hash(password, hash)) { return true; } return false; } else if (type.equalsIgnoreCase("syncpassword")) { String hash = MySQL.getfromtable(Config.custom_table, "`" + Config.custom_passfield + "`", "" + Config.custom_userfield + "", player); EBean.checkPassword(player, hash); return true; } else if (type.equalsIgnoreCase("adduser")) { Custom.adduser(player, email, password, ipAddress); EBean.sync(player); return true; } else if (type.equalsIgnoreCase("numusers")) { ps = (PreparedStatement) MySQL.mysql.prepareStatement("SELECT COUNT(*) as `countit` FROM `" + Config.custom_table + "`"); ResultSet rs = ps.executeQuery(); if (rs.next()) { logging.Info(rs.getInt("countit") + " user registrations in database"); } } } else if (script.equalsIgnoreCase(PhpBB.Name) || script.equalsIgnoreCase(PhpBB.ShortName)) { usertable = "users"; //bantable = "banlist"; if (checkVersionInRange(PhpBB.VersionRange)) { usernamefield = "username_clean"; passwordfield = "user_password"; /*useridfield = "user_id"; banipfield = "ban_ip"; bannamefield = "ban_userid"; banreasonfield = "";*/ Config.hasForumBoard = true; number = 1; if (type.equalsIgnoreCase("checkpassword")) { EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); if (storedPassword != null && PhpBB.check_hash(password, storedPassword)) { return true; } String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player); EBean.checkPassword(player, hash); if (PhpBB.check_hash(password, hash)) { return true; } } /*else if (type.equalsIgnoreCase("checkban")) { String check = "fail"; if (ipAddress != null) { String userid = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + useridfield + "`", "" + usernamefield + "", player); check = MySQL.getfromtable(Config.script_tableprefix + "" + bantable + "", "`" + banipfield + "`", "" + bannamefield + "", userid); } else { check = MySQL.getfromtable(Config.script_tableprefix + "" + bantable + "", "`" + banipfield + "`", "" + banipfield + "", ipAddress); } if (check != "fail") { return true; } else { return false; } } */ } else if (checkVersionInRange(PhpBB.VersionRange2)) { usernamefield = "username_clean"; // TODO: use equalsIgnoreCase to allow for all variations? passwordfield = "user_password"; Config.hasForumBoard = true; bans = true; number = 2; if (type.equalsIgnoreCase("checkpassword")) { EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); if (storedPassword != null && PhpBB.check_hash(password, storedPassword)) { return true; } String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player); EBean.checkPassword(player, hash); if (PhpBB.check_hash(password, hash)) { return true; } } } if (type.equalsIgnoreCase("adduser")) { PhpBB.adduser(number, player, email, password, ipAddress); EBean.sync(player); return true; } } else if (script.equalsIgnoreCase(SMF.Name) || script.equalsIgnoreCase(SMF.ShortName)) { usertable = "members"; if (checkVersionInRange(SMF.VersionRange)) { usernamefield = "memberName"; passwordfield = "passwd"; saltfield = "passwordSalt"; Config.hasForumBoard = true; bans = true; number = 1; if (type.equalsIgnoreCase("checkpassword")) { EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); if (storedPassword != null && SMF.check_hash(SMF.hash(1, player, password), storedPassword)) { return true; } String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player); EBean.checkPassword(player, hash); if (SMF.check_hash(SMF.hash(1, player, password), hash)) { return true; } } } else if (checkVersionInRange(SMF.VersionRange2) || checkVersionInRange("2.0-2.0") || checkVersionInRange("2.0.0-2.0.0")) { usernamefield = "member_name"; passwordfield = "passwd"; Config.hasForumBoard = true; bans = true; number = 2; if (type.equalsIgnoreCase("checkpassword")) { EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); if (storedPassword != null && SMF.check_hash(SMF.hash(2, player, password), storedPassword)) { return true; } String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player); EBean.checkPassword(player, hash); if (SMF.check_hash(SMF.hash(2, player, password), hash)) { return true; } } } if (type.equalsIgnoreCase("adduser")) { SMF.adduser(number, player, email, password, ipAddress); EBean.sync(player); return true; } } else if (script.equalsIgnoreCase(MyBB.Name) || script.equalsIgnoreCase(MyBB.ShortName)) { usertable = "users"; if (checkVersionInRange(MyBB.VersionRange)) { saltfield = "salt"; usernamefield = "username"; passwordfield = "password"; Config.hasForumBoard = true; bans = true; number = 1; if (type.equalsIgnoreCase("checkpassword")) { EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); if (storedPassword != null && MyBB.check_hash(MyBB.hash("find", player, password, ""), storedPassword)) { return true; } String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player); EBean.checkPassword(player, hash); if (MyBB.check_hash(MyBB.hash("find", player, password, ""), hash)) { return true; } } } if (type.equalsIgnoreCase("adduser")) { MyBB.adduser(number, player, email, password, ipAddress); EBean.sync(player); return true; } } else if (script.equalsIgnoreCase(VBulletin.Name) || script.equalsIgnoreCase(VBulletin.ShortName)) { usertable = "user"; if (checkVersionInRange(VBulletin.VersionRange)) { saltfield = "salt"; usernamefield = "username"; passwordfield = "password"; Config.hasForumBoard = true; bans = true; number = 1; if (type.equalsIgnoreCase("checkpassword")) { EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); if (storedPassword != null && VBulletin.check_hash(VBulletin.hash("find", player, password, ""), storedPassword)) { return true; } String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player); EBean.checkPassword(player, hash); if (VBulletin.check_hash(VBulletin.hash("find", player, password, ""), hash)) { return true; } } } else if (checkVersionInRange(VBulletin.VersionRange2)) { usernamefield = "username"; passwordfield = "password"; Config.hasForumBoard = true; bans = true; number = 2; if (type.equalsIgnoreCase("checkpassword")) { EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); if (storedPassword != null && VBulletin.check_hash(VBulletin.hash("find", player, password, ""), storedPassword)) { return true; } String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player); EBean.checkPassword(player, hash); if (VBulletin.check_hash(VBulletin.hash("find", player, password, ""), hash)) { return true; } } } if (type.equalsIgnoreCase("adduser")) { VBulletin.adduser(number, player, email, password, ipAddress); EBean.sync(player); return true; } } else if (script.equalsIgnoreCase(Drupal.Name) || script.equalsIgnoreCase(Drupal.ShortName)) { usertable = "users"; if (checkVersionInRange(Drupal.VersionRange)) { usernamefield = "name"; passwordfield = "pass"; Config.hasForumBoard = true; number = 1; if (type.equalsIgnoreCase("checkpassword")) { EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); if (storedPassword != null && Encryption.md5(password).equals(storedPassword)) { return true; } String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player); EBean.checkPassword(player, hash); if (Encryption.md5(password).equals(hash)) { return true; } } } else if (checkVersionInRange(Drupal.VersionRange2)) { usernamefield = "name"; passwordfield = "pass"; Config.hasForumBoard = true; number = 2; if (type.equalsIgnoreCase("checkpassword")) { EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); if (storedPassword != null && storedPassword.equals(Drupal.user_check_password(password, storedPassword))) { return true; } String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player); EBean.checkPassword(player, hash); if (hash.equals(Drupal.user_check_password(password, hash))) { return true; } } } if (type.equalsIgnoreCase("adduser")) { Drupal.adduser(number, player, email, password, ipAddress); EBean.sync(player); return true; } } else if (script.equalsIgnoreCase(Joomla.Name) || script.equalsIgnoreCase(Joomla.ShortName)) { usertable = "users"; if (checkVersionInRange(Joomla.VersionRange)) { usernamefield = "username"; passwordfield = "password"; Config.hasForumBoard = true; number = 1; if (type.equalsIgnoreCase("checkpassword")) { EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); if (storedPassword != null && Joomla.check_hash(password, storedPassword)) { return true; } String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player); EBean.checkPassword(player, hash); if (Joomla.check_hash(password, hash)) { return true; } } } else if (checkVersionInRange(Joomla.VersionRange2)) { usernamefield = "username"; passwordfield = "password"; Config.hasForumBoard = true; number = 2; if (type.equalsIgnoreCase("checkpassword")) { EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); if (storedPassword != null && Joomla.check_hash(password, storedPassword)) { return true; } String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player); EBean.checkPassword(player, hash); if (Joomla.check_hash(password, hash)) { return true; } } } if (type.equalsIgnoreCase("adduser")) { Joomla.adduser(number, player, email, password, ipAddress); EBean.sync(player); return true; } } else if (script.equalsIgnoreCase(Vanilla.Name) || script.equalsIgnoreCase(Vanilla.ShortName)) { if (checkVersionInRange(Vanilla.VersionRange)) { usertable = "User"; usernamefield = "Name"; passwordfield = "Password"; if(Vanilla.check() == 2) { usertable = usertable.toLowerCase(); } Config.hasForumBoard = true; number = Vanilla.check(); if (type.equalsIgnoreCase("checkpassword")) { EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); if (storedPassword != null && Vanilla.check_hash(password, storedPassword)) { return true; } String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player); EBean.checkPassword(player, hash); if (Vanilla.check_hash(password, hash)) { return true; } } } if (type.equalsIgnoreCase("adduser")) { String emailcheck = MySQL.getfromtable(Config.script_tableprefix + usertable, "`Email`", "Email", email); if (emailcheck.equalsIgnoreCase("fail")) { Vanilla.adduser(number, player, email, password, ipAddress); EBean.sync(player); return true; } return false; } } else if (script.equalsIgnoreCase(PunBB.Name) || script.equalsIgnoreCase(PunBB.ShortName)) { usertable = "users"; //bantable = "bans"; if (checkVersionInRange(PunBB.VersionRange)) { // bannamefield = "username"; saltfield = "salt"; usernamefield = "username"; passwordfield = "password"; Config.hasForumBoard = true; number = 1; if (type.equalsIgnoreCase("checkpassword")) { EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); if (storedPassword != null && PunBB.check_hash(PunBB.hash("find", player, password, ""), storedPassword)) { return true; } String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player); EBean.checkPassword(player, hash); if (PunBB.check_hash(PunBB.hash("find", player, password, ""), hash)) { return true; } } } if (type.equalsIgnoreCase("adduser")) { PunBB.adduser(number, player, email, password, ipAddress); EBean.sync(player); return true; } } else if (script.equalsIgnoreCase(XenForo.Name) || script.equalsIgnoreCase(XenForo.ShortName)) { usertable = "user"; if (checkVersionInRange(XenForo.VersionRange)) { String userid = MySQL.getfromtable(Config.script_tableprefix + usertable, "`user_id`", "username", player); usernamefield = "username"; passwordfield = "password"; Config.hasForumBoard = true; number = 1; if (type.equalsIgnoreCase("checkpassword")) { Blob hash = MySQL.getfromtableBlob(Config.script_tableprefix + "user_authenticate", "`data`", "user_id", userid); if (hash != null) { int offset = -1; int chunkSize = 1024; long blobLength = hash.length(); if (chunkSize > blobLength) { chunkSize = (int) blobLength; } char buffer[] = new char[chunkSize]; StringBuilder stringBuffer = new StringBuilder(); Reader reader = new InputStreamReader(hash.getBinaryStream()); try { while ((offset = reader.read(buffer)) != -1) { stringBuffer.append(buffer, 0, offset); } } catch (IOException e) { // TODO Auto-generated catch block logging.StackTrace(e.getStackTrace(), Thread.currentThread().getStackTrace()[1].getMethodName(), Thread.currentThread().getStackTrace()[1].getLineNumber(), Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getFileName()); } String cache = stringBuffer.toString(); String thehash = forumCacheValue(cache, "hash"); String thesalt = forumCacheValue(cache, "salt"); EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); String storedSalt = eBeanClass.getSalt(); if (storedPassword != null && storedSalt != null && XenForo.check_hash(XenForo.hash(1, storedSalt, password), storedPassword)) { return true; } EBean.checkSalt(player, thesalt); EBean.checkPassword(player, thehash); if (XenForo.check_hash(XenForo.hash(1, thesalt, password), thehash)) { return true; } } else { return false; } } } if (type.equalsIgnoreCase("adduser")) { XenForo.adduser(number, player, email, password, ipAddress); EBean.sync(player); return true; } else if (Config.hasForumBoard && type.equalsIgnoreCase("syncpassword") && !Config.custom_enabled) { String userid = MySQL.getfromtable(Config.script_tableprefix + usertable, "`user_id`", "username", player); Blob hash = MySQL.getfromtableBlob(Config.script_tableprefix + "user_authenticate", "`data`", "user_id", userid); int offset = -1; int chunkSize = 1024; long blobLength = hash.length(); if (chunkSize > blobLength) { chunkSize = (int) blobLength; } char buffer[] = new char[chunkSize]; StringBuilder stringBuffer = new StringBuilder(); Reader reader = new InputStreamReader(hash.getBinaryStream()); try { while ((offset = reader.read(buffer)) != -1) { stringBuffer.append(buffer, 0, offset); } } catch (IOException e) { logging.StackTrace(e.getStackTrace(), Thread.currentThread().getStackTrace()[1].getMethodName(), Thread.currentThread().getStackTrace()[1].getLineNumber(), Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getFileName()); } String cache = stringBuffer.toString(); String thehash = forumCacheValue(cache, "hash"); EBean.checkPassword(player, thehash); return true; } else if (Config.hasForumBoard && type.equalsIgnoreCase("syncsalt") && !Config.custom_enabled && saltfield != null && saltfield != "") { String userid = MySQL.getfromtable(Config.script_tableprefix + usertable, "`user_id`", "username", player); Blob hash = MySQL.getfromtableBlob(Config.script_tableprefix + "user_authenticate", "`data`", "user_id", userid); int offset = -1; int chunkSize = 1024; long blobLength = hash.length(); if (chunkSize > blobLength) { chunkSize = (int) blobLength; } char buffer[] = new char[chunkSize]; StringBuilder stringBuffer = new StringBuilder(); Reader reader = new InputStreamReader(hash.getBinaryStream()); try { while ((offset = reader.read(buffer)) != -1) { stringBuffer.append(buffer, 0, offset); } } catch (IOException e) { // TODO Auto-generated catch block logging.StackTrace(e.getStackTrace(), Thread.currentThread().getStackTrace()[1].getMethodName(), Thread.currentThread().getStackTrace()[1].getLineNumber(), Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getFileName()); } String cache = stringBuffer.toString(); String thesalt = forumCacheValue(cache, "salt"); EBean.checkSalt(player, thesalt); return true; } } else if (script.equalsIgnoreCase(BBPress.Name) || script.equalsIgnoreCase(BBPress.ShortName)) { usertable = "users"; if (checkVersionInRange(BBPress.VersionRange)) { usernamefield = "user_login"; passwordfield = "user_pass"; Config.hasForumBoard = true; number = 1; if (type.equalsIgnoreCase("checkpassword")) { EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); if (storedPassword != null && BBPress.check_hash(password, storedPassword)) { return true; } String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player); EBean.checkPassword(player, hash); if (BBPress.check_hash(password, hash)) { return true; } } } if (type.equalsIgnoreCase("adduser")) { BBPress.adduser(number, player, email, password, ipAddress); EBean.sync(player); return true; } } else if (script.equalsIgnoreCase(DLE.Name) || script.equalsIgnoreCase(DLE.ShortName)) { usertable = "users"; if (checkVersionInRange(DLE.VersionRange)) { usernamefield = "name"; passwordfield = "password"; Config.hasForumBoard = true; number = 1; if (type.equalsIgnoreCase("checkpassword")) { EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); if (storedPassword != null && DLE.check_hash(DLE.hash(password), storedPassword)) { return true; } String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player); EBean.checkPassword(player, hash); if (DLE.check_hash(DLE.hash(password), hash)) { return true; } } } if (type.equalsIgnoreCase("adduser")) { DLE.adduser(number, player, email, password, ipAddress); EBean.sync(player); return true; } } else if (script.equalsIgnoreCase(IPB.Name) || script.equalsIgnoreCase(IPB.ShortName)) { usertable = "members"; if (checkVersionInRange(IPB.VersionRange)) { saltfield = "members_pass_salt"; usernamefield = "members_l_username"; passwordfield = "members_pass_hash"; Config.hasForumBoard = true; number = 1; if (type.equalsIgnoreCase("checkpassword")) { player = player.toLowerCase(); EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); if (storedPassword != null && IPB.check_hash(IPB.hash("find", player, password, null), storedPassword)) { return true; } String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player); EBean.checkPassword(player, hash); if (IPB.check_hash(IPB.hash("find", player, password, null), hash)) { return true; } } } else if (checkVersionInRange(IPB.VersionRange2)) { saltfield = "members_pass_salt"; usernamefield = "members_l_username"; passwordfield = "members_pass_hash"; Config.hasForumBoard = true; number = 2; if (type.equalsIgnoreCase("checkpassword")) { player = player.toLowerCase(); EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); if (storedPassword != null && IPB.check_hash(IPB.hash("find", player, password, null), storedPassword)) { return true; } String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", passwordfield + "`", "" + usernamefield + "", player); EBean.checkPassword(player, hash); if (IPB.check_hash(IPB.hash("find", player, password, null), hash)) { return true; } } } if (type.equalsIgnoreCase("adduser")) { player = player.toLowerCase(); IPB.adduser(number, player, email, password, ipAddress); EBean.sync(player); return true; } } else if (script.equalsIgnoreCase(WordPress.Name) || script.equalsIgnoreCase(WordPress.ShortName)) { usertable = "users"; if (checkVersionInRange(WordPress.VersionRange)) { usernamefield = "user_login"; passwordfield = "user_pass"; Config.hasForumBoard = true; number = 1; if (type.equalsIgnoreCase("checkpassword")) { EBean eBeanClass = EBean.find(player); String storedPassword = eBeanClass.getPassword(); if (storedPassword != null && WordPress.check_hash(password, storedPassword)) { return true; } String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player); EBean.checkPassword(player, hash); Util.logging.Info("HASH = "+hash); if (WordPress.check_hash(password, hash)) { return true; } } } if (type.equalsIgnoreCase("adduser")) { WordPress.adduser(number, player, email, password, ipAddress); EBean.sync(player); return true; } } /* else if (script.equalsIgnoreCase(Config.Script11_name) || script.equalsIgnoreCase(Config.Script11_shortname)) { usertable = "users"; if (checkVersionInRange(Config.Script11_versionrange)) { usernamefield = "username"; passwordfield = "password"; Config.hasForumBoard = true; number = 1; if (type.equalsIgnoreCase("checkpassword")) { String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player); if (XE.check_hash(password, hash)) { return true; } } } if (type.equalsIgnoreCase("adduser")) { XE.adduser(number, player, email, password, ipAddress); return true; } } */
diff --git a/src/de/raptor2101/GalDroid/WebGallery/Gallery3/Gallery3Imp.java b/src/de/raptor2101/GalDroid/WebGallery/Gallery3/Gallery3Imp.java index fddbc8a..e9e57eb 100644 --- a/src/de/raptor2101/GalDroid/WebGallery/Gallery3/Gallery3Imp.java +++ b/src/de/raptor2101/GalDroid/WebGallery/Gallery3/Gallery3Imp.java @@ -1,354 +1,356 @@ /* * GalDroid - a webgallery frontend for android * Copyright (C) 2011 Raptor 2101 [[email protected]] * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.raptor2101.GalDroid.WebGallery.Gallery3; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.StringBody; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.os.AsyncTask.Status; import android.util.FloatMath; import de.raptor2101.GalDroid.WebGallery.GalleryStream; import de.raptor2101.GalDroid.WebGallery.Gallery3.JSON.AlbumEntity; import de.raptor2101.GalDroid.WebGallery.Gallery3.JSON.CommentEntity; import de.raptor2101.GalDroid.WebGallery.Gallery3.JSON.CommentEntity.CommentState; import de.raptor2101.GalDroid.WebGallery.Gallery3.JSON.Entity; import de.raptor2101.GalDroid.WebGallery.Gallery3.JSON.EntityFactory; import de.raptor2101.GalDroid.WebGallery.Gallery3.Tasks.JSONArrayLoaderTask; import de.raptor2101.GalDroid.WebGallery.Interfaces.GalleryDownloadObject; import de.raptor2101.GalDroid.WebGallery.Interfaces.GalleryObject; import de.raptor2101.GalDroid.WebGallery.Interfaces.GalleryObjectComment; import de.raptor2101.GalDroid.WebGallery.Interfaces.GalleryProgressListener; import de.raptor2101.GalDroid.WebGallery.Interfaces.WebGallery; public class Gallery3Imp implements WebGallery { private HttpClient mHttpClient; private String mSecurityToken; private float mMaxImageDiag; private final String mRootLink; public final String LinkRest_LoadSecurityToken; public final String LinkRest_LoadItem; public final String LinkRest_LoadTag; public final String LinkRest_LoadBunchItems; public final String LinkRest_LoadBunchTags; public final String LinkRest_LoadPicture; public final String LinkRest_LoadComments; private static int MAX_REQUEST_SIZE = 4000; public Gallery3Imp(String rootLink) { mRootLink = rootLink; LinkRest_LoadSecurityToken = rootLink+"/index.php/rest"; LinkRest_LoadItem = rootLink+"/index.php/rest/item/%d"; LinkRest_LoadTag = rootLink+"/index.php/rest/tag/%s"; LinkRest_LoadBunchItems = rootLink +"/index.php/rest/items?urls=[%s]"; LinkRest_LoadBunchTags = rootLink +"/index.php/rest/tags?urls=[%s]"; LinkRest_LoadPicture = rootLink +"/index.php/rest/data/%s?size=%s"; LinkRest_LoadComments = rootLink + "/index.php/rest/item_comments/%d"; } public String getItemLink(int id){ return String.format(LinkRest_LoadItem, id); } private RestCall buildRestCall(String url, long suggestedLength){ HttpGet httpRequest = new HttpGet(url); httpRequest.addHeader("X-Gallery-Request-Method", "get"); httpRequest.addHeader("X-Gallery-Request-Key", mSecurityToken); return new RestCall(this, httpRequest, suggestedLength); } private Entity loadGalleryEntity(String url) throws ClientProtocolException, IOException, JSONException { RestCall restCall = buildRestCall(url, -1); return EntityFactory.parseJSON(restCall.loadJSONObject(), this); } private List<JSONObject> loadJSONObjectsParallel(String bunchUrl,List<String> urls, int taskCount, GalleryProgressListener listener) { int objectSize = urls.size(); ArrayList<JSONArrayLoaderTask> tasks = new ArrayList<JSONArrayLoaderTask>(taskCount); ArrayList<JSONObject> jsonObjects = new ArrayList<JSONObject>(objectSize); for(int i=0; i<objectSize; ) { StringBuilder requstUrl = new StringBuilder(MAX_REQUEST_SIZE); JSONArrayLoaderTask task = new JSONArrayLoaderTask(); tasks.add(task); /* * TODO Kommentar anpassen * Otherwise the max length of a GET-Request might be exceeded */ for( ; i<objectSize; i++) { String url = urls.get(i); if(url.length()+requstUrl.length() > MAX_REQUEST_SIZE) { break; } requstUrl.append("%22" + url + "%22,"); } requstUrl.deleteCharAt(requstUrl.length() - 1); String realUrl = String.format(bunchUrl, requstUrl); task.execute(buildRestCall(realUrl, -1)); } for(JSONArrayLoaderTask task:tasks) { if(task.getStatus() != Status.FINISHED) { try { JSONArray jsonArray = task.get(); for(int i=0; i<jsonArray.length(); i++) { try { jsonObjects.add(jsonArray.getJSONObject(i)); - listener.handleProgress(jsonObjects.size(), objectSize); + if(listener != null) { + listener.handleProgress(jsonObjects.size(), objectSize); + } } catch (JSONException e) { e.printStackTrace(); } } } catch (InterruptedException e) { } catch (ExecutionException e) { } } } return jsonObjects; } public GalleryObject getDisplayObject(String url) throws ClientProtocolException, IOException, JSONException { return loadGalleryEntity(url); } public List<GalleryObject> getDisplayObjects() { return getDisplayObjects(String.format(LinkRest_LoadItem, 1), null); } public List<GalleryObject> getDisplayObjects(String url) { return getDisplayObjects(url, null); } public List<GalleryObject> getDisplayObjects(GalleryProgressListener progressListener) { return getDisplayObjects(String.format(LinkRest_LoadItem, 1), progressListener); } public List<GalleryObject> getDisplayObjects(String url, GalleryProgressListener listener) { ArrayList<GalleryObject> displayObjects; try { GalleryObject galleryObject = loadGalleryEntity(url); if(galleryObject.hasChildren()) { AlbumEntity album = (AlbumEntity) galleryObject; List<String> members = album.getMembers(); displayObjects = new ArrayList<GalleryObject>(members.size()); List<JSONObject> jsonObjects = loadJSONObjectsParallel(LinkRest_LoadBunchItems,members,5,listener); for(JSONObject jsonObject:jsonObjects) { if(jsonObject != null) { displayObjects.add(EntityFactory.parseJSON(jsonObject, this)); } } } else displayObjects = new ArrayList<GalleryObject>(0); } catch (ClientProtocolException e) { displayObjects = new ArrayList<GalleryObject>(0); e.printStackTrace(); } catch (IOException e) { displayObjects = new ArrayList<GalleryObject>(0); e.printStackTrace(); } catch (JSONException e) { displayObjects = new ArrayList<GalleryObject>(0); e.printStackTrace(); } return displayObjects; } public List<GalleryObject> getDisplayObjects(GalleryObject galleryObject) { return getDisplayObjects(galleryObject, null); } public List<GalleryObject> getDisplayObjects(GalleryObject galleryObject, GalleryProgressListener progressListener) { try { Entity entity = (Entity) galleryObject; if(!entity.hasChildren()) { return null; } return getDisplayObjects(entity.getObjectLink(), progressListener); } catch (ClassCastException e) { return null; } } public List<String> getDisplayObjectTags(GalleryObject galleryObject, GalleryProgressListener listener) throws IOException { try { Entity entity = (Entity) galleryObject; List<String> tagLinks = entity.getTagLinks(); int linkCount = tagLinks.size(); ArrayList<String> tags = new ArrayList<String>(linkCount); ArrayList<JSONObject> jsonObjects = new ArrayList<JSONObject>(linkCount); if (linkCount>0) { for(int i=0; i<linkCount; i++ ) { try { RestCall restCall = buildRestCall(tagLinks.get(i),-1); JSONObject jsonObject = restCall.loadJSONObject(); tags.add(EntityFactory.parseTag(jsonObject)); } catch (JSONException e) { // Nothing to do here } catch (IOException e) { // Nothing to do here } } } return tags; } catch (ClassCastException e) { throw new IOException("GalleryObject doesn't contain to Gallery3Implementation", e); } } public List<GalleryObjectComment> getDisplayObjectComments(GalleryObject galleryObject, GalleryProgressListener listener) throws IOException, ClientProtocolException, JSONException { try { Entity entity = (Entity) galleryObject; String commentSource = String.format(LinkRest_LoadComments, entity.getId()); RestCall restCall = buildRestCall(commentSource, -1); JSONObject jsonObject = restCall.loadJSONObject(); JSONArray jsonItemComments = jsonObject.getJSONArray("members"); int commentCount = jsonItemComments.length(); ArrayList<JSONObject> jsonObjects = new ArrayList<JSONObject>(commentCount); ArrayList<GalleryObjectComment> comments = new ArrayList<GalleryObjectComment>(commentCount); ArrayList<String> authors = new ArrayList<String>(commentCount); for(int i=0; i<commentCount; i++ ) { restCall = buildRestCall(jsonItemComments.getString(i),-1); jsonObject = restCall.loadJSONObject(); CommentEntity comment = EntityFactory.parseComment(jsonObject); if(comment.getState() == CommentState.Published) { comments.add(comment); if(!comment.isAuthorInformationLoaded()) { authors.add(comment.getAuthorId()); } } } return comments; } catch (ClassCastException e) { throw new IOException("GalleryObject doesn't contain to Gallery3Implementation", e); } } private GalleryStream getFileStream(String sourceLink, long suggestedLength) throws ClientProtocolException, IOException{ RestCall restCall = buildRestCall(sourceLink, suggestedLength); return restCall.open(); } public GalleryStream getFileStream(GalleryDownloadObject galleryDownloadObject) throws ClientProtocolException, IOException { if(!(galleryDownloadObject instanceof DownloadObject)) { throw new IOException("downloadObject don't belong to the Gallery3 Implementation"); } DownloadObject downloadObject = (DownloadObject) galleryDownloadObject; if(!(downloadObject.getRootLink().equals(mRootLink))){ throw new IOException("downloadObject don't belong to the this Host"); } return getFileStream(downloadObject.getUniqueId(), downloadObject.getFileSize()); } public void setHttpClient(HttpClient httpClient) { mHttpClient = httpClient; } public String getSecurityToken(String user, String password) throws SecurityException { try { HttpPost httpRequest = new HttpPost(LinkRest_LoadSecurityToken); httpRequest.addHeader("X-Gallery-Request-Method", "post"); MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); mpEntity.addPart("user", new StringBody(user)); mpEntity.addPart("password", new StringBody(password)); httpRequest.setEntity(mpEntity); HttpResponse response; response = mHttpClient.execute(httpRequest); InputStream inputStream = response.getEntity().getContent(); InputStreamReader streamReader = new InputStreamReader(inputStream); BufferedReader reader = new BufferedReader(streamReader); String content = reader.readLine(); inputStream.close(); if(content.length()==0 || content.startsWith("[]")) { throw new SecurityException("Couldn't verify user-credentials"); } return content.trim().replace("\"", ""); } catch (Exception e) { throw new SecurityException("Couldn't verify user-credentials", e); } } public HttpClient getHttpClient() { return mHttpClient; } public void setSecurityToken(String securityToken) { mSecurityToken = securityToken; } public void setPreferedDimensions(int height, int width) { mMaxImageDiag = FloatMath.sqrt(height*height+width*width); } public String getRootLink() { return mRootLink; } public float getMaxImageDiag() { return mMaxImageDiag; } }
true
true
private List<JSONObject> loadJSONObjectsParallel(String bunchUrl,List<String> urls, int taskCount, GalleryProgressListener listener) { int objectSize = urls.size(); ArrayList<JSONArrayLoaderTask> tasks = new ArrayList<JSONArrayLoaderTask>(taskCount); ArrayList<JSONObject> jsonObjects = new ArrayList<JSONObject>(objectSize); for(int i=0; i<objectSize; ) { StringBuilder requstUrl = new StringBuilder(MAX_REQUEST_SIZE); JSONArrayLoaderTask task = new JSONArrayLoaderTask(); tasks.add(task); /* * TODO Kommentar anpassen * Otherwise the max length of a GET-Request might be exceeded */ for( ; i<objectSize; i++) { String url = urls.get(i); if(url.length()+requstUrl.length() > MAX_REQUEST_SIZE) { break; } requstUrl.append("%22" + url + "%22,"); } requstUrl.deleteCharAt(requstUrl.length() - 1); String realUrl = String.format(bunchUrl, requstUrl); task.execute(buildRestCall(realUrl, -1)); } for(JSONArrayLoaderTask task:tasks) { if(task.getStatus() != Status.FINISHED) { try { JSONArray jsonArray = task.get(); for(int i=0; i<jsonArray.length(); i++) { try { jsonObjects.add(jsonArray.getJSONObject(i)); listener.handleProgress(jsonObjects.size(), objectSize); } catch (JSONException e) { e.printStackTrace(); } } } catch (InterruptedException e) { } catch (ExecutionException e) { } } } return jsonObjects; }
private List<JSONObject> loadJSONObjectsParallel(String bunchUrl,List<String> urls, int taskCount, GalleryProgressListener listener) { int objectSize = urls.size(); ArrayList<JSONArrayLoaderTask> tasks = new ArrayList<JSONArrayLoaderTask>(taskCount); ArrayList<JSONObject> jsonObjects = new ArrayList<JSONObject>(objectSize); for(int i=0; i<objectSize; ) { StringBuilder requstUrl = new StringBuilder(MAX_REQUEST_SIZE); JSONArrayLoaderTask task = new JSONArrayLoaderTask(); tasks.add(task); /* * TODO Kommentar anpassen * Otherwise the max length of a GET-Request might be exceeded */ for( ; i<objectSize; i++) { String url = urls.get(i); if(url.length()+requstUrl.length() > MAX_REQUEST_SIZE) { break; } requstUrl.append("%22" + url + "%22,"); } requstUrl.deleteCharAt(requstUrl.length() - 1); String realUrl = String.format(bunchUrl, requstUrl); task.execute(buildRestCall(realUrl, -1)); } for(JSONArrayLoaderTask task:tasks) { if(task.getStatus() != Status.FINISHED) { try { JSONArray jsonArray = task.get(); for(int i=0; i<jsonArray.length(); i++) { try { jsonObjects.add(jsonArray.getJSONObject(i)); if(listener != null) { listener.handleProgress(jsonObjects.size(), objectSize); } } catch (JSONException e) { e.printStackTrace(); } } } catch (InterruptedException e) { } catch (ExecutionException e) { } } } return jsonObjects; }
diff --git a/src/klient/Klient.java b/src/klient/Klient.java index 9772637..82ca217 100644 --- a/src/klient/Klient.java +++ b/src/klient/Klient.java @@ -1,129 +1,129 @@ package klient; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import javax.swing.JFrame; import klient.Gui.KlientGUI; import klient.Nettverk.KlientNettInn; import klient.Nettverk.KlientNettUt; public class Klient extends JFrame implements KeyListener { /** * @param args */ public static void main(String[] args) { new Klient(); } KlientGUI gui; KlientNettInn nettInn; KlientNettUt nettUt; public Klient() { super("Klient"); setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); gui = new KlientGUI(); setContentPane(gui); setUndecorated(true); pack(); setVisible(true); nettInn = new KlientNettInn(); nettUt = new KlientNettUt(); Thread ni = new Thread(nettInn); Thread nu = new Thread(nettUt); ni.start(); nu.start(); this.addKeyListener(this); run(); } private void run() { String[] tags = {""}; String login = ""; while(true) { /*String[] nyetags = gui.LesTags(); if(erUlike(tags, nyetags)) nettUt.send(nyetags);*/ nettUt.poke(); // Denne erstattes med kommentert-ut kode ovenfor hvis klienten skal kunne sende tags selv. login = gui.sjekkLogin(); if(!login.equals("")) nettUt.sendLogin(login); for(int i = 0; i<10; i++) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } String[] inntags = nettInn.getTags(); if(erUlike(inntags, tags) /*&& !erUlike(inntags, nyetags)*/) { gui.GiBilder(nettInn.getURLs()); tags = inntags.clone(); break; } } if(nettInn.erLoginKorrekt()) - gui.login(); + gui.Login(); } } private boolean erUlike(String[] tags, String[] nyetags) { if(tags.length != nyetags.length) return false; boolean ret = true; for(int i = 0; i<tags.length; i++) { boolean funnet = false; for(int j = 0; j<tags.length; j++) { if(tags[i].toUpperCase().equals(nyetags[j].toUpperCase())) { funnet = true; break; } } if(!funnet) { ret=false; break; } } return !ret; } @Override public void keyPressed(KeyEvent arg0) { if(arg0.getKeyCode() == arg0.VK_ESCAPE) System.exit(0); } @Override public void keyReleased(KeyEvent arg0) { // TODO Auto-generated method stub } @Override public void keyTyped(KeyEvent arg0) { // TODO Auto-generated method stub } }
true
true
private void run() { String[] tags = {""}; String login = ""; while(true) { /*String[] nyetags = gui.LesTags(); if(erUlike(tags, nyetags)) nettUt.send(nyetags);*/ nettUt.poke(); // Denne erstattes med kommentert-ut kode ovenfor hvis klienten skal kunne sende tags selv. login = gui.sjekkLogin(); if(!login.equals("")) nettUt.sendLogin(login); for(int i = 0; i<10; i++) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } String[] inntags = nettInn.getTags(); if(erUlike(inntags, tags) /*&& !erUlike(inntags, nyetags)*/) { gui.GiBilder(nettInn.getURLs()); tags = inntags.clone(); break; } } if(nettInn.erLoginKorrekt()) gui.login(); } }
private void run() { String[] tags = {""}; String login = ""; while(true) { /*String[] nyetags = gui.LesTags(); if(erUlike(tags, nyetags)) nettUt.send(nyetags);*/ nettUt.poke(); // Denne erstattes med kommentert-ut kode ovenfor hvis klienten skal kunne sende tags selv. login = gui.sjekkLogin(); if(!login.equals("")) nettUt.sendLogin(login); for(int i = 0; i<10; i++) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } String[] inntags = nettInn.getTags(); if(erUlike(inntags, tags) /*&& !erUlike(inntags, nyetags)*/) { gui.GiBilder(nettInn.getURLs()); tags = inntags.clone(); break; } } if(nettInn.erLoginKorrekt()) gui.Login(); } }
diff --git a/src/com/ReviewGist/RewiewGist.java b/src/com/ReviewGist/RewiewGist.java index 4ba19b8..5dac6c0 100644 --- a/src/com/ReviewGist/RewiewGist.java +++ b/src/com/ReviewGist/RewiewGist.java @@ -1,37 +1,35 @@ /* 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 com.ReviewGist; import android.app.Activity; import android.os.Bundle; import org.apache.cordova.*; public class RewiewGist extends DroidGap { @Override public void onCreate(Bundle savedInstanceState) { - super.setIntegerProperty("loadUrlTimeoutValue", 70000); + super.setIntegerProperty("loadUrlTimeoutValue", 40000); super.onCreate(savedInstanceState); - super.clearCache(); - // super.setIntegerProperty("splashscreen",R.drawable.splash); - super.loadUrl("file:///android_asset/www/app.html#page1"); + super.loadUrl("file:///android_asset/www/app.html"); } }
false
true
public void onCreate(Bundle savedInstanceState) { super.setIntegerProperty("loadUrlTimeoutValue", 70000); super.onCreate(savedInstanceState); super.clearCache(); // super.setIntegerProperty("splashscreen",R.drawable.splash); super.loadUrl("file:///android_asset/www/app.html#page1"); }
public void onCreate(Bundle savedInstanceState) { super.setIntegerProperty("loadUrlTimeoutValue", 40000); super.onCreate(savedInstanceState); super.loadUrl("file:///android_asset/www/app.html"); }
diff --git a/libraries/javalib/gnu/java/nio/FileLockImpl.java b/libraries/javalib/gnu/java/nio/FileLockImpl.java index 31b2e826d..ca79f772d 100644 --- a/libraries/javalib/gnu/java/nio/FileLockImpl.java +++ b/libraries/javalib/gnu/java/nio/FileLockImpl.java @@ -1,94 +1,94 @@ /* FileLockImpl.java -- Copyright (C) 2002, 2004 Free Software Foundation, Inc. This file is part of GNU Classpath. GNU Classpath 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, or (at your option) any later version. GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ package gnu.java.nio; import java.io.FileDescriptor; import java.io.IOException; import java.nio.channels.FileChannel; import java.nio.channels.FileLock; import gnu.classpath.Configuration; /** * @author Michael Koch * @since 1.4 */ public class FileLockImpl extends FileLock { static { // load the shared library needed for native methods. if (Configuration.INIT_LOAD_LIBRARY) { System.loadLibrary ("nio"); } } private FileDescriptor fd; public FileLockImpl (FileDescriptor fd, FileChannel channel, long position, long size, boolean shared) { super (channel, position, size, shared); this.fd = fd; } - public void finalize() + protected void finalize() { try { release(); } catch (IOException e) { // Ignore this. } } public boolean isValid () { return !channel().isOpen(); } private native void releaseImpl () throws IOException; public synchronized void release () throws IOException { releaseImpl (); } }
true
true
public void finalize() { try { release(); } catch (IOException e) { // Ignore this. } }
protected void finalize() { try { release(); } catch (IOException e) { // Ignore this. } }
diff --git a/drools-compiler/src/main/java/org/drools/rule/builder/dialect/mvel/MVELDialect.java b/drools-compiler/src/main/java/org/drools/rule/builder/dialect/mvel/MVELDialect.java index afaa7e97a9..8da8375e07 100644 --- a/drools-compiler/src/main/java/org/drools/rule/builder/dialect/mvel/MVELDialect.java +++ b/drools-compiler/src/main/java/org/drools/rule/builder/dialect/mvel/MVELDialect.java @@ -1,735 +1,735 @@ package org.drools.rule.builder.dialect.mvel; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.io.Serializable; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.drools.base.EvaluatorWrapper; import org.drools.base.ModifyInterceptor; import org.drools.base.TypeResolver; import org.drools.base.ValueType; import org.drools.base.mvel.MVELCompilationUnit; import org.drools.base.mvel.MVELDebugHandler; import org.drools.commons.jci.readers.MemoryResourceReader; import org.drools.compiler.AnalysisResult; import org.drools.compiler.BoundIdentifiers; import org.drools.compiler.DescrBuildError; import org.drools.compiler.Dialect; import org.drools.compiler.ImportError; import org.drools.compiler.PackageBuilder; import org.drools.compiler.PackageRegistry; import org.drools.core.util.StringUtils; import org.drools.definition.rule.Rule; import org.drools.io.Resource; import org.drools.lang.descr.AccumulateDescr; import org.drools.lang.descr.AndDescr; import org.drools.lang.descr.BaseDescr; import org.drools.lang.descr.CollectDescr; import org.drools.lang.descr.EntryPointDescr; import org.drools.lang.descr.EvalDescr; import org.drools.lang.descr.ExistsDescr; import org.drools.lang.descr.ForallDescr; import org.drools.lang.descr.FromDescr; import org.drools.lang.descr.FunctionDescr; import org.drools.lang.descr.NotDescr; import org.drools.lang.descr.OrDescr; import org.drools.lang.descr.PatternDescr; import org.drools.lang.descr.ProcessDescr; import org.drools.lang.descr.QueryDescr; import org.drools.lang.descr.RuleDescr; import org.drools.rule.Declaration; import org.drools.rule.LineMappings; import org.drools.rule.MVELDialectRuntimeData; import org.drools.rule.Package; import org.drools.rule.builder.AccumulateBuilder; import org.drools.rule.builder.CollectBuilder; import org.drools.rule.builder.ConsequenceBuilder; import org.drools.rule.builder.EnabledBuilder; import org.drools.rule.builder.EngineElementBuilder; import org.drools.rule.builder.EntryPointBuilder; import org.drools.rule.builder.ForallBuilder; import org.drools.rule.builder.FromBuilder; import org.drools.rule.builder.GroupElementBuilder; import org.drools.rule.builder.PackageBuildContext; import org.drools.rule.builder.PatternBuilder; import org.drools.rule.builder.PredicateBuilder; import org.drools.rule.builder.QueryBuilder; import org.drools.rule.builder.ReturnValueBuilder; import org.drools.rule.builder.RuleBuildContext; import org.drools.rule.builder.RuleClassBuilder; import org.drools.rule.builder.RuleConditionBuilder; import org.drools.rule.builder.SalienceBuilder; import org.drools.rule.builder.dialect.java.JavaDialect; import org.drools.rule.builder.dialect.java.JavaFunctionBuilder; import org.drools.runtime.rule.RuleContext; import org.drools.spi.DeclarationScopeResolver; import org.drools.spi.Evaluator; import org.drools.spi.KnowledgeHelper; import org.mvel2.MVEL; import org.mvel2.ParserConfiguration; import org.mvel2.ParserContext; import org.mvel2.compiler.AbstractParser; import org.mvel2.compiler.ExpressionCompiler; public class MVELDialect implements Dialect, Externalizable { private String id = "mvel"; private final static String EXPRESSION_DIALECT_NAME = "MVEL"; protected static final PatternBuilder PATTERN_BUILDER = new PatternBuilder(); protected static final QueryBuilder QUERY_BUILDER = new QueryBuilder(); protected static final MVELAccumulateBuilder ACCUMULATE_BUILDER = new MVELAccumulateBuilder(); protected static final SalienceBuilder SALIENCE_BUILDER = new MVELSalienceBuilder(); protected static final EnabledBuilder ENABLED_BUILDER = new MVELEnabledBuilder(); protected static final MVELEvalBuilder EVAL_BUILDER = new MVELEvalBuilder(); protected static final MVELPredicateBuilder PREDICATE_BUILDER = new MVELPredicateBuilder(); protected static final MVELReturnValueBuilder RETURN_VALUE_BUILDER = new MVELReturnValueBuilder(); protected static final MVELConsequenceBuilder CONSEQUENCE_BUILDER = new MVELConsequenceBuilder(); // private final JavaRuleClassBuilder rule = new JavaRuleClassBuilder(); protected static final MVELFromBuilder FROM_BUILDER = new MVELFromBuilder(); protected static final JavaFunctionBuilder FUNCTION_BUILDER = new JavaFunctionBuilder(); protected static final CollectBuilder COLLECT_BUILDER = new CollectBuilder(); protected static final ForallBuilder FORALL_BUILDER = new ForallBuilder(); protected static final EntryPointBuilder ENTRY_POINT_BUILDER = new EntryPointBuilder(); protected static final GroupElementBuilder GE_BUILDER = new GroupElementBuilder(); // a map of registered builders private static Map<Class< ? >, EngineElementBuilder> builders; static { initBuilder(); } private static final MVELExprAnalyzer analyzer = new MVELExprAnalyzer(); private Map interceptors; protected List results; // private final JavaFunctionBuilder function = new JavaFunctionBuilder(); protected MemoryResourceReader src; protected Package pkg; private MVELDialectConfiguration configuration; private PackageBuilder pkgBuilder; private PackageRegistry packageRegistry; private Map<String, Object> imports; private Set<String> packageImports; private boolean strictMode; private int languageLevel; public MVELDialect(PackageBuilder builder, PackageRegistry pkgRegistry, Package pkg) { this( builder, pkgRegistry, pkg, "mvel" ); } public MVELDialect(PackageBuilder builder, PackageRegistry pkgRegistry, Package pkg, String id) { this.id = id; this.pkg = pkg; this.pkgBuilder = builder; this.packageRegistry = pkgRegistry; this.configuration = (MVELDialectConfiguration) builder.getPackageBuilderConfiguration().getDialectConfiguration( "mvel" ); setLanguageLevel( this.configuration.getLangLevel() ); this.strictMode = this.configuration.isStrict(); this.imports = new HashMap(); this.packageImports = new HashSet(); // setting MVEL option directly MVEL.COMPILER_OPT_ALLOW_NAKED_METH_CALL = true; this.interceptors = new HashMap( 1 ); this.interceptors.put( "Modify", new ModifyInterceptor() ); this.results = new ArrayList(); // this.data = new MVELDialectRuntimeData( // this.pkg.getDialectRuntimeRegistry() ); // // this.pkg.getDialectRuntimeRegistry().setDialectData( ID, // this.data ); MVELDialectRuntimeData data = null; // initialise the dialect runtime data if it doesn't already exist if ( pkg.getDialectRuntimeRegistry().getDialectData( getId() ) == null ) { data = new MVELDialectRuntimeData(); this.pkg.getDialectRuntimeRegistry().setDialectData( getId(), data ); data.onAdd( this.pkg.getDialectRuntimeRegistry(), this.pkgBuilder.getRootClassLoader() ); } this.results = new ArrayList(); this.src = new MemoryResourceReader(); if ( this.pkg != null ) { this.addImport( this.pkg.getName() + ".*" ); } this.addImport( "java.lang.*" ); } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { interceptors = (Map) in.readObject(); results = (List) in.readObject(); src = (MemoryResourceReader) in.readObject(); pkg = (Package) in.readObject(); packageRegistry = (PackageRegistry) in.readObject(); configuration = (MVELDialectConfiguration) in.readObject(); imports = (Map) in.readObject(); packageImports = (Set) in.readObject(); strictMode = in.readBoolean(); } public void writeExternal(ObjectOutput out) throws IOException { out.writeObject( interceptors ); out.writeObject( results ); out.writeObject( src ); out.writeObject( pkg ); out.writeObject( packageRegistry ); out.writeObject( configuration ); out.writeObject( imports ); out.writeObject( packageImports ); out.writeBoolean( strictMode ); } public void setLanguageLevel(int languageLevel) { this.languageLevel = languageLevel; } // public static void setLanguageLevel(int level) { // synchronized ( lang ) { // // this synchronisation is needed as setLanguageLevel is not thread safe // // and we do not want to be calling this while something else is being // parsed. // // the flag ensures it is just called once and no more. // if ( languageSet.booleanValue() == false ) { // languageSet = new Boolean( true ); // AbstractParser.setLanguageLevel( level ); // } // } // } public static void initBuilder() { if ( builders != null ) { return; } // statically adding all builders to the map // but in the future we can move that to a configuration // if we want to builders = new HashMap<Class< ? >, EngineElementBuilder>(); builders.put( AndDescr.class, GE_BUILDER ); builders.put( OrDescr.class, GE_BUILDER ); builders.put( NotDescr.class, GE_BUILDER ); builders.put( ExistsDescr.class, GE_BUILDER ); builders.put( PatternDescr.class, PATTERN_BUILDER ); builders.put( FromDescr.class, FROM_BUILDER ); builders.put( QueryDescr.class, QUERY_BUILDER ); builders.put( AccumulateDescr.class, ACCUMULATE_BUILDER ); builders.put( EvalDescr.class, EVAL_BUILDER ); builders.put( CollectDescr.class, COLLECT_BUILDER ); builders.put( ForallDescr.class, FORALL_BUILDER ); builders.put( FunctionDescr.class, FUNCTION_BUILDER ); builders.put( EntryPointDescr.class, ENTRY_POINT_BUILDER ); } public void init(RuleDescr ruleDescr) { // MVEL:test null to Fix failing test on // org.drools.rule.builder.dialect. // mvel.MVELConsequenceBuilderTest.testImperativeCodeError() // @todo: why is this here, MVEL doesn't compile anything? mdp String pkgName = this.pkg == null ? "" : this.pkg.getName(); final String ruleClassName = JavaDialect.getUniqueLegalName( pkgName, ruleDescr.getName(), "mvel", "Rule", this.src ); ruleDescr.setClassName( StringUtils.ucFirst( ruleClassName ) ); } public void init(final ProcessDescr processDescr) { final String processDescrClassName = JavaDialect.getUniqueLegalName( this.pkg.getName(), processDescr.getName(), "mvel", "Process", this.src ); processDescr.setClassName( StringUtils.ucFirst( processDescrClassName ) ); } public String getExpressionDialectName() { return EXPRESSION_DIALECT_NAME; } public void addRule(RuleBuildContext context) { // MVEL: Compiler change final RuleDescr ruleDescr = context.getRuleDescr(); // setup the line mappins for this rule final String name = this.pkg.getName() + "." + StringUtils.ucFirst( ruleDescr.getClassName() ); final LineMappings mapping = new LineMappings( name ); mapping.setStartLine( ruleDescr.getConsequenceLine() ); mapping.setOffset( ruleDescr.getConsequenceOffset() ); context.getPkg().getDialectRuntimeRegistry().getLineMappings().put( name, mapping ); } public void addFunction(FunctionDescr functionDescr, TypeResolver typeResolver, Resource resource) { // Serializable s1 = compile( (String) functionDescr.getText(), // null, // null, // null, // null, // null ); // // final ParserContext parserContext = getParserContext( analysis, // outerDeclarations, // otherInputVariables, // context ); // return MVELCompilationUnit.compile( text, pkgBuilder.getRootClassLoader(), parserContext, languageLevel ); // // Map<String, org.mvel2.ast.Function> map = org.mvel2.util.CompilerTools.extractAllDeclaredFunctions( (org.mvel2.compiler.CompiledExpression) s1 ); // MVELDialectRuntimeData data = (MVELDialectRuntimeData) this.packageRegistry.getDialectRuntimeRegistry().getDialectData( getId() ); // for ( org.mvel2.ast.Function function : map.values() ) { // data.addFunction( function ); // } } public void preCompileAddFunction(FunctionDescr functionDescr, TypeResolver typeResolver) { } public void postCompileAddFunction(FunctionDescr functionDescr, TypeResolver typeResolver) { } public void addImport(String importEntry) { if ( importEntry.endsWith( ".*" ) ) { importEntry = importEntry.substring( 0, importEntry.length() - 2 ); this.packageImports.add( importEntry ); } else { try { Class cls = this.packageRegistry.getTypeResolver().resolveType( importEntry ); this.imports.put( cls.getSimpleName(), cls ); } catch ( ClassNotFoundException e ) { this.results.add( new ImportError( importEntry, 1 ) ); } } } public Map<String, Object> getImports() { return this.imports; } public Set<String> getPackgeImports() { return this.packageImports; } public void addStaticImport(String staticImportEntry) { if ( staticImportEntry.endsWith( "*" ) ) { return; } int index = staticImportEntry.lastIndexOf( '.' ); String className = staticImportEntry.substring( 0, index ); String methodName = staticImportEntry.substring( index + 1 ); try { Class cls = this.pkgBuilder.getRootClassLoader().loadClass( className ); if ( cls != null ) { // First try and find a matching method for ( Method method : cls.getDeclaredMethods() ) { if ( method.getName().equals( methodName ) ) { this.imports.put( methodName, method ); return; } } //no matching method, so now try and find a matching public property for ( Field field : cls.getFields() ) { if ( field.isAccessible() && field.getName().equals( methodName ) ) { this.imports.put( methodName, field ); return; } } } } catch ( ClassNotFoundException e ) { } // we never managed to make the import, so log an error this.results.add( new ImportError( staticImportEntry, -1 ) ); } // private Map staticFieldImports = new HashMap(); // private Map staticMethodImports = new HashMap(); public boolean isStrictMode() { return strictMode; } public void setStrictMode(boolean strictMode) { this.strictMode = strictMode; } public void compileAll() { } public AnalysisResult analyzeExpression(final PackageBuildContext context, final BaseDescr descr, final Object content, final BoundIdentifiers availableIdentifiers) { return analyzeExpression( context, descr, content, availableIdentifiers, null ); } public AnalysisResult analyzeExpression(final PackageBuildContext context, final BaseDescr descr, final Object content, final BoundIdentifiers availableIdentifiers, final Map<String, Class<?>> localTypes) { AnalysisResult result = null; try { result = analyzer.analyzeExpression( context, (String) content, availableIdentifiers, localTypes, "drools", KnowledgeHelper.class ); } catch ( final Exception e ) { context.getErrors().add( new DescrBuildError( context.getParentDescr(), descr, null, "Unable to determine the used declarations.\n" + e.getMessage() ) ); } return result; } public AnalysisResult analyzeBlock(final PackageBuildContext context, final BaseDescr descr, final String text, final BoundIdentifiers availableIdentifiers) { return analyzeBlock( context, descr, null, text, availableIdentifiers, null, "drools", KnowledgeHelper.class); } public AnalysisResult analyzeBlock(final PackageBuildContext context, final BaseDescr descr, final Map interceptors, final String text, final BoundIdentifiers availableIdentifiers, final Map<String, Class<?>> localTypes, String contextIndeifier, Class kcontextClass) { AnalysisResult result = null; result = analyzer.analyzeExpression( context, text, availableIdentifiers, localTypes, contextIndeifier, kcontextClass); return result; } public MVELCompilationUnit getMVELCompilationUnit(final String expression, final AnalysisResult analysis, Declaration[] previousDeclarations, Declaration[] localDeclarations, final Map<String, Class<?>> otherInputVariables, final PackageBuildContext context, String contextIndeifier, Class kcontextClass) { String[] pkgImports = this.packageImports.toArray( new String[this.packageImports.size()] ); //String[] imports = new String[this.imports.size()]; List<String> importClasses = new ArrayList<String>(); List<String> importMethods = new ArrayList<String>(); List<String> importFields = new ArrayList<String>(); for ( Iterator it = this.imports.values().iterator(); it.hasNext(); ) { Object object = it.next(); if ( object instanceof Class ) { importClasses.add( ((Class) object).getName() ); } else if ( object instanceof Method ) { Method method = (Method) object; importMethods.add( method.getDeclaringClass().getName() + "." + method.getName() ); } else { Field field = (Field) object; importFields.add( field.getDeclaringClass().getName() + "." + field.getName() ); } } Map<String, Class> resolvedInputs = new LinkedHashMap<String, Class>(); List<String> ids = new ArrayList<String>(); if ( analysis.getBoundIdentifiers().getThisClass() != null || ( localDeclarations != null && localDeclarations.length > 0 ) ) { Class cls = analysis.getBoundIdentifiers().getThisClass(); ids.add( "this" ); resolvedInputs.put( "this", (cls != null) ? cls : Object.class ); // the only time cls is null is in accumumulate's acc/reverse } ids.add( contextIndeifier ); resolvedInputs.put( contextIndeifier, kcontextClass ); ids.add( "kcontext" ); resolvedInputs.put( "kcontext", kcontextClass ); ids.add( "rule" ); resolvedInputs.put( "rule", Rule.class ); List<String> strList = new ArrayList<String>(); for( Entry<String, Class<?>> e : analysis.getBoundIdentifiers().getGlobals().entrySet() ) { strList.add( e.getKey() ); ids.add( e.getKey() ); resolvedInputs.put( e.getKey(), e.getValue() ); } String[] globalIdentifiers = strList.toArray( new String[strList.size()] ); strList.clear(); for( String op : analysis.getBoundIdentifiers().getOperators().keySet() ) { strList.add( op ); ids.add( op ); resolvedInputs.put( op, EvaluatorWrapper.class ); } EvaluatorWrapper[] operators = new EvaluatorWrapper[strList.size()]; for( int i = 0; i < operators.length; i++ ) { operators[i] = analysis.getBoundIdentifiers().getOperators().get( strList.get( i ) ); } if ( previousDeclarations != null ) { for (Declaration decl : previousDeclarations ) { if ( analysis.getBoundIdentifiers().getDeclarations().containsKey( decl.getIdentifier() ) ) { ids.add( decl.getIdentifier() ); resolvedInputs.put( decl.getIdentifier(), decl.getExtractor().getExtractToClass() ); } } } if ( localDeclarations != null ) { for (Declaration decl : localDeclarations ) { if ( analysis.getBoundIdentifiers().getDeclarations().containsKey( decl.getIdentifier() ) ) { ids.add( decl.getIdentifier() ); resolvedInputs.put( decl.getIdentifier(), decl.getExtractor().getExtractToClass() ); } } } // "not bound" identifiers could be drools, kcontext and rule // but in the case of accumulate it could be vars from the "init" section. //String[] otherIdentifiers = otherInputVariables == null ? new String[]{} : new String[otherInputVariables.size()]; strList = new ArrayList<String>(); if ( otherInputVariables != null ) { int i = 0; for ( Iterator it = otherInputVariables.entrySet().iterator(); it.hasNext(); ) { Entry entry = (Entry) it.next(); if ( !analysis.getNotBoundedIdentifiers().contains( entry.getKey() ) || "rule".equals( entry.getKey() ) ) { // no point including them if they aren't used // and rule was already included continue; } ids.add( (String) entry.getKey() ); strList.add( (String) entry.getKey() ); resolvedInputs.put( (String) entry.getKey(), (Class) entry.getValue() ); } } String[] otherIdentifiers = strList.toArray( new String[strList.size()]); String[] inputIdentifiers = new String[resolvedInputs.size()]; String[] inputTypes = new String[resolvedInputs.size()]; int i = 0; for ( String id : ids ) { inputIdentifiers[i] = id; inputTypes[i++] = resolvedInputs.get( id ).getName(); } String name; - if ( context != null && context.getPkg() != null & context.getPkg().getName() != null ) { + if ( context != null && context.getPkg() != null && context.getPkg().getName() != null ) { if ( context instanceof RuleBuildContext ) { name = context.getPkg().getName() + "." + ((RuleBuildContext) context).getRuleDescr().getClassName(); } else { name = context.getPkg().getName() + ".Unknown"; } } else { name = "Unknown"; } MVELCompilationUnit compilationUnit = new MVELCompilationUnit( name, expression, pkgImports, importClasses.toArray( new String[importClasses.size()] ), importMethods.toArray( new String[importMethods.size()] ), importFields.toArray( new String[importFields.size()] ), globalIdentifiers, operators, previousDeclarations, localDeclarations, otherIdentifiers, inputIdentifiers, inputTypes, languageLevel, context.isTypesafe() ); return compilationUnit; } public EngineElementBuilder getBuilder(final Class clazz) { return this.builders.get( clazz ); } public Map<Class< ? >, EngineElementBuilder> getBuilders() { return this.builders; } public PatternBuilder getPatternBuilder() { return this.PATTERN_BUILDER; } public QueryBuilder getQueryBuilder() { return this.QUERY_BUILDER; } public AccumulateBuilder getAccumulateBuilder() { return this.ACCUMULATE_BUILDER; } public ConsequenceBuilder getConsequenceBuilder() { return this.CONSEQUENCE_BUILDER; } public RuleConditionBuilder getEvalBuilder() { return this.EVAL_BUILDER; } public FromBuilder getFromBuilder() { return this.FROM_BUILDER; } public EntryPointBuilder getEntryPointBuilder() { return this.ENTRY_POINT_BUILDER; } public PredicateBuilder getPredicateBuilder() { return this.PREDICATE_BUILDER; } public PredicateBuilder getExpressionPredicateBuilder() { return this.PREDICATE_BUILDER; } public SalienceBuilder getSalienceBuilder() { return this.SALIENCE_BUILDER; } public EnabledBuilder getEnabledBuilder() { return this.ENABLED_BUILDER; } public List getResults() { return results; } public ReturnValueBuilder getReturnValueBuilder() { return this.RETURN_VALUE_BUILDER; } public RuleClassBuilder getRuleClassBuilder() { throw new UnsupportedOperationException( "MVELDialect.getRuleClassBuilder is not supported" ); } public TypeResolver getTypeResolver() { return this.packageRegistry.getTypeResolver(); } public Map getInterceptors() { return this.interceptors; } public String getId() { return this.id; } }
true
true
public MVELCompilationUnit getMVELCompilationUnit(final String expression, final AnalysisResult analysis, Declaration[] previousDeclarations, Declaration[] localDeclarations, final Map<String, Class<?>> otherInputVariables, final PackageBuildContext context, String contextIndeifier, Class kcontextClass) { String[] pkgImports = this.packageImports.toArray( new String[this.packageImports.size()] ); //String[] imports = new String[this.imports.size()]; List<String> importClasses = new ArrayList<String>(); List<String> importMethods = new ArrayList<String>(); List<String> importFields = new ArrayList<String>(); for ( Iterator it = this.imports.values().iterator(); it.hasNext(); ) { Object object = it.next(); if ( object instanceof Class ) { importClasses.add( ((Class) object).getName() ); } else if ( object instanceof Method ) { Method method = (Method) object; importMethods.add( method.getDeclaringClass().getName() + "." + method.getName() ); } else { Field field = (Field) object; importFields.add( field.getDeclaringClass().getName() + "." + field.getName() ); } } Map<String, Class> resolvedInputs = new LinkedHashMap<String, Class>(); List<String> ids = new ArrayList<String>(); if ( analysis.getBoundIdentifiers().getThisClass() != null || ( localDeclarations != null && localDeclarations.length > 0 ) ) { Class cls = analysis.getBoundIdentifiers().getThisClass(); ids.add( "this" ); resolvedInputs.put( "this", (cls != null) ? cls : Object.class ); // the only time cls is null is in accumumulate's acc/reverse } ids.add( contextIndeifier ); resolvedInputs.put( contextIndeifier, kcontextClass ); ids.add( "kcontext" ); resolvedInputs.put( "kcontext", kcontextClass ); ids.add( "rule" ); resolvedInputs.put( "rule", Rule.class ); List<String> strList = new ArrayList<String>(); for( Entry<String, Class<?>> e : analysis.getBoundIdentifiers().getGlobals().entrySet() ) { strList.add( e.getKey() ); ids.add( e.getKey() ); resolvedInputs.put( e.getKey(), e.getValue() ); } String[] globalIdentifiers = strList.toArray( new String[strList.size()] ); strList.clear(); for( String op : analysis.getBoundIdentifiers().getOperators().keySet() ) { strList.add( op ); ids.add( op ); resolvedInputs.put( op, EvaluatorWrapper.class ); } EvaluatorWrapper[] operators = new EvaluatorWrapper[strList.size()]; for( int i = 0; i < operators.length; i++ ) { operators[i] = analysis.getBoundIdentifiers().getOperators().get( strList.get( i ) ); } if ( previousDeclarations != null ) { for (Declaration decl : previousDeclarations ) { if ( analysis.getBoundIdentifiers().getDeclarations().containsKey( decl.getIdentifier() ) ) { ids.add( decl.getIdentifier() ); resolvedInputs.put( decl.getIdentifier(), decl.getExtractor().getExtractToClass() ); } } } if ( localDeclarations != null ) { for (Declaration decl : localDeclarations ) { if ( analysis.getBoundIdentifiers().getDeclarations().containsKey( decl.getIdentifier() ) ) { ids.add( decl.getIdentifier() ); resolvedInputs.put( decl.getIdentifier(), decl.getExtractor().getExtractToClass() ); } } } // "not bound" identifiers could be drools, kcontext and rule // but in the case of accumulate it could be vars from the "init" section. //String[] otherIdentifiers = otherInputVariables == null ? new String[]{} : new String[otherInputVariables.size()]; strList = new ArrayList<String>(); if ( otherInputVariables != null ) { int i = 0; for ( Iterator it = otherInputVariables.entrySet().iterator(); it.hasNext(); ) { Entry entry = (Entry) it.next(); if ( !analysis.getNotBoundedIdentifiers().contains( entry.getKey() ) || "rule".equals( entry.getKey() ) ) { // no point including them if they aren't used // and rule was already included continue; } ids.add( (String) entry.getKey() ); strList.add( (String) entry.getKey() ); resolvedInputs.put( (String) entry.getKey(), (Class) entry.getValue() ); } } String[] otherIdentifiers = strList.toArray( new String[strList.size()]); String[] inputIdentifiers = new String[resolvedInputs.size()]; String[] inputTypes = new String[resolvedInputs.size()]; int i = 0; for ( String id : ids ) { inputIdentifiers[i] = id; inputTypes[i++] = resolvedInputs.get( id ).getName(); } String name; if ( context != null && context.getPkg() != null & context.getPkg().getName() != null ) { if ( context instanceof RuleBuildContext ) { name = context.getPkg().getName() + "." + ((RuleBuildContext) context).getRuleDescr().getClassName(); } else { name = context.getPkg().getName() + ".Unknown"; } } else { name = "Unknown"; } MVELCompilationUnit compilationUnit = new MVELCompilationUnit( name, expression, pkgImports, importClasses.toArray( new String[importClasses.size()] ), importMethods.toArray( new String[importMethods.size()] ), importFields.toArray( new String[importFields.size()] ), globalIdentifiers, operators, previousDeclarations, localDeclarations, otherIdentifiers, inputIdentifiers, inputTypes, languageLevel, context.isTypesafe() ); return compilationUnit; }
public MVELCompilationUnit getMVELCompilationUnit(final String expression, final AnalysisResult analysis, Declaration[] previousDeclarations, Declaration[] localDeclarations, final Map<String, Class<?>> otherInputVariables, final PackageBuildContext context, String contextIndeifier, Class kcontextClass) { String[] pkgImports = this.packageImports.toArray( new String[this.packageImports.size()] ); //String[] imports = new String[this.imports.size()]; List<String> importClasses = new ArrayList<String>(); List<String> importMethods = new ArrayList<String>(); List<String> importFields = new ArrayList<String>(); for ( Iterator it = this.imports.values().iterator(); it.hasNext(); ) { Object object = it.next(); if ( object instanceof Class ) { importClasses.add( ((Class) object).getName() ); } else if ( object instanceof Method ) { Method method = (Method) object; importMethods.add( method.getDeclaringClass().getName() + "." + method.getName() ); } else { Field field = (Field) object; importFields.add( field.getDeclaringClass().getName() + "." + field.getName() ); } } Map<String, Class> resolvedInputs = new LinkedHashMap<String, Class>(); List<String> ids = new ArrayList<String>(); if ( analysis.getBoundIdentifiers().getThisClass() != null || ( localDeclarations != null && localDeclarations.length > 0 ) ) { Class cls = analysis.getBoundIdentifiers().getThisClass(); ids.add( "this" ); resolvedInputs.put( "this", (cls != null) ? cls : Object.class ); // the only time cls is null is in accumumulate's acc/reverse } ids.add( contextIndeifier ); resolvedInputs.put( contextIndeifier, kcontextClass ); ids.add( "kcontext" ); resolvedInputs.put( "kcontext", kcontextClass ); ids.add( "rule" ); resolvedInputs.put( "rule", Rule.class ); List<String> strList = new ArrayList<String>(); for( Entry<String, Class<?>> e : analysis.getBoundIdentifiers().getGlobals().entrySet() ) { strList.add( e.getKey() ); ids.add( e.getKey() ); resolvedInputs.put( e.getKey(), e.getValue() ); } String[] globalIdentifiers = strList.toArray( new String[strList.size()] ); strList.clear(); for( String op : analysis.getBoundIdentifiers().getOperators().keySet() ) { strList.add( op ); ids.add( op ); resolvedInputs.put( op, EvaluatorWrapper.class ); } EvaluatorWrapper[] operators = new EvaluatorWrapper[strList.size()]; for( int i = 0; i < operators.length; i++ ) { operators[i] = analysis.getBoundIdentifiers().getOperators().get( strList.get( i ) ); } if ( previousDeclarations != null ) { for (Declaration decl : previousDeclarations ) { if ( analysis.getBoundIdentifiers().getDeclarations().containsKey( decl.getIdentifier() ) ) { ids.add( decl.getIdentifier() ); resolvedInputs.put( decl.getIdentifier(), decl.getExtractor().getExtractToClass() ); } } } if ( localDeclarations != null ) { for (Declaration decl : localDeclarations ) { if ( analysis.getBoundIdentifiers().getDeclarations().containsKey( decl.getIdentifier() ) ) { ids.add( decl.getIdentifier() ); resolvedInputs.put( decl.getIdentifier(), decl.getExtractor().getExtractToClass() ); } } } // "not bound" identifiers could be drools, kcontext and rule // but in the case of accumulate it could be vars from the "init" section. //String[] otherIdentifiers = otherInputVariables == null ? new String[]{} : new String[otherInputVariables.size()]; strList = new ArrayList<String>(); if ( otherInputVariables != null ) { int i = 0; for ( Iterator it = otherInputVariables.entrySet().iterator(); it.hasNext(); ) { Entry entry = (Entry) it.next(); if ( !analysis.getNotBoundedIdentifiers().contains( entry.getKey() ) || "rule".equals( entry.getKey() ) ) { // no point including them if they aren't used // and rule was already included continue; } ids.add( (String) entry.getKey() ); strList.add( (String) entry.getKey() ); resolvedInputs.put( (String) entry.getKey(), (Class) entry.getValue() ); } } String[] otherIdentifiers = strList.toArray( new String[strList.size()]); String[] inputIdentifiers = new String[resolvedInputs.size()]; String[] inputTypes = new String[resolvedInputs.size()]; int i = 0; for ( String id : ids ) { inputIdentifiers[i] = id; inputTypes[i++] = resolvedInputs.get( id ).getName(); } String name; if ( context != null && context.getPkg() != null && context.getPkg().getName() != null ) { if ( context instanceof RuleBuildContext ) { name = context.getPkg().getName() + "." + ((RuleBuildContext) context).getRuleDescr().getClassName(); } else { name = context.getPkg().getName() + ".Unknown"; } } else { name = "Unknown"; } MVELCompilationUnit compilationUnit = new MVELCompilationUnit( name, expression, pkgImports, importClasses.toArray( new String[importClasses.size()] ), importMethods.toArray( new String[importMethods.size()] ), importFields.toArray( new String[importFields.size()] ), globalIdentifiers, operators, previousDeclarations, localDeclarations, otherIdentifiers, inputIdentifiers, inputTypes, languageLevel, context.isTypesafe() ); return compilationUnit; }
diff --git a/Sweng2012QuizApp/src/epfl/sweng/entry/MainActivity.java b/Sweng2012QuizApp/src/epfl/sweng/entry/MainActivity.java index 216728d..ef06355 100644 --- a/Sweng2012QuizApp/src/epfl/sweng/entry/MainActivity.java +++ b/Sweng2012QuizApp/src/epfl/sweng/entry/MainActivity.java @@ -1,78 +1,78 @@ package epfl.sweng.entry; import epfl.sweng.R; import epfl.sweng.authentication.AuthenticationActivity; import epfl.sweng.editquestions.EditQuestionActivity; import epfl.sweng.globals.Globals; import epfl.sweng.showquestions.ShowQuestionsActivity; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.view.Menu; import android.view.View; /** * Main Activity of the Application * */ public class MainActivity extends Activity { /** * Method invoked at the creation of the Activity. * @param Bundle savedInstanceState the saved instance */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); SharedPreferences settings = getSharedPreferences(Globals.PREFS_NAME, 0); - if (settings.getString("SESSION_ID", "") == "") { + if (settings.getString("SESSION_ID", "").equals("")) { finish(); Intent authenticationActivityIntent = new Intent(this, AuthenticationActivity.class); startActivity(authenticationActivityIntent); } } /** * Method invoked at the creation of the Options Menu. * @param Menu menu the created menu */ @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } /** * Change view to the ShowQuestionsActivity * @param View view reference to the menu button */ public void goToDisplayActivity(View view) { Intent showQuestionsActivityIntent = new Intent(this, ShowQuestionsActivity.class); startActivity(showQuestionsActivityIntent); } /** * Change view to the EditQuestionActivity * @param View view reference to the menu button */ public void goToSubmitActivity(View view) { Intent editQuestionActivityIntent = new Intent(this, EditQuestionActivity.class); startActivity(editQuestionActivityIntent); } /** * Log out the user * @param View view reference to the menu button */ public void logout(View view) { SharedPreferences settings = getSharedPreferences(Globals.PREFS_NAME, 0); SharedPreferences.Editor editor = settings.edit(); editor.putString("SESSION_ID", ""); editor.commit(); Intent authenticationActivityIntent = new Intent(this, AuthenticationActivity.class); startActivity(authenticationActivityIntent); } }
true
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); SharedPreferences settings = getSharedPreferences(Globals.PREFS_NAME, 0); if (settings.getString("SESSION_ID", "") == "") { finish(); Intent authenticationActivityIntent = new Intent(this, AuthenticationActivity.class); startActivity(authenticationActivityIntent); } }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); SharedPreferences settings = getSharedPreferences(Globals.PREFS_NAME, 0); if (settings.getString("SESSION_ID", "").equals("")) { finish(); Intent authenticationActivityIntent = new Intent(this, AuthenticationActivity.class); startActivity(authenticationActivityIntent); } }
diff --git a/spf4j-core/src/main/java/org/spf4j/concurrent/FutureBean.java b/spf4j-core/src/main/java/org/spf4j/concurrent/FutureBean.java index 6619539104..b4f4bf20f8 100644 --- a/spf4j-core/src/main/java/org/spf4j/concurrent/FutureBean.java +++ b/spf4j-core/src/main/java/org/spf4j/concurrent/FutureBean.java @@ -1,101 +1,101 @@ /* * Copyright (c) 2001, Zoltan Farkas All Rights Reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package org.spf4j.concurrent; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import javax.annotation.concurrent.ThreadSafe; import org.spf4j.base.Pair; /** * bean like implementation of a future * @author zoly */ @ThreadSafe public class FutureBean<T> implements Future<T> { private Pair<Object, ? extends ExecutionException> resultStore; @Override public final boolean cancel(final boolean mayInterruptIfRunning) { throw new UnsupportedOperationException("Not supported yet."); } @Override public final boolean isCancelled() { throw new UnsupportedOperationException("Not supported yet."); } @Override public final synchronized boolean isDone() { return resultStore != null; } @Override // Findbugs complain here is rubbish, InterruptedException is thrown by wait @edu.umd.cs.findbugs.annotations.SuppressWarnings("BED_BOGUS_EXCEPTION_DECLARATION") public final synchronized T get() throws InterruptedException, ExecutionException { while (resultStore == null) { this.wait(); } return processResult(resultStore); } @Override public final synchronized T get(final long timeout, final TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { long timeoutMillis = unit.toMillis(timeout); long toWait = timeoutMillis; long startTime = System.currentTimeMillis(); - do { + while (toWait > 0 && resultStore == null) { this.wait(toWait); toWait = timeoutMillis - (System.currentTimeMillis() - startTime); - } while (toWait > 0); + } if (resultStore == null) { throw new TimeoutException(); } return processResult(resultStore); } private T processResult(final Pair<Object, ? extends ExecutionException> result) throws ExecutionException { ExecutionException e = result.getSecond(); if (e != null) { throw e; } else { return (T) result.getFirst(); } } public final synchronized void setResult(final Object result) { resultStore = Pair.of(result, (ExecutionException) null); done(); this.notifyAll(); } public final synchronized void setExceptionResult(final ExecutionException result) { resultStore = Pair.of(null, (ExecutionException) result); done(); this.notifyAll(); } public void done() { } }
false
true
public final synchronized T get(final long timeout, final TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { long timeoutMillis = unit.toMillis(timeout); long toWait = timeoutMillis; long startTime = System.currentTimeMillis(); do { this.wait(toWait); toWait = timeoutMillis - (System.currentTimeMillis() - startTime); } while (toWait > 0); if (resultStore == null) { throw new TimeoutException(); } return processResult(resultStore); }
public final synchronized T get(final long timeout, final TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { long timeoutMillis = unit.toMillis(timeout); long toWait = timeoutMillis; long startTime = System.currentTimeMillis(); while (toWait > 0 && resultStore == null) { this.wait(toWait); toWait = timeoutMillis - (System.currentTimeMillis() - startTime); } if (resultStore == null) { throw new TimeoutException(); } return processResult(resultStore); }
diff --git a/modules/common/org/dcache/commons/stats/RequestCounterImpl.java b/modules/common/org/dcache/commons/stats/RequestCounterImpl.java index 1668833f93..4416bed7e6 100644 --- a/modules/common/org/dcache/commons/stats/RequestCounterImpl.java +++ b/modules/common/org/dcache/commons/stats/RequestCounterImpl.java @@ -1,162 +1,163 @@ /* * Counter.java * * Created on April 4, 2009, 5:36 PM */ package org.dcache.commons.stats; import java.lang.management.ManagementFactory; import java.util.Formatter; import javax.management.InstanceAlreadyExistsException; import javax.management.InstanceNotFoundException; import javax.management.MBeanRegistrationException; import javax.management.MBeanServer; import javax.management.MalformedObjectNameException; import javax.management.NotCompliantMBeanException; import javax.management.ObjectName; /** * This class encapsulates two integer counters and provides utility methods * for increments and discovery of the count of request invocations and * failures * This class is thread safe. * @author timur */ public class RequestCounterImpl implements RequestCounterMXBean { private final String name; private int requests = 0; private int failed = 0; private ObjectName mxBeanName; /** Creates a new instance of Counter * @param name */ public RequestCounterImpl(String name) { this.name = name; MBeanServer server = ManagementFactory.getPlatformMBeanServer(); try { - String mxName = String.format("%s:type=RequestCounter,name=%s", this.getClass().getPackage(), this.name); + String mxName = String.format("%s:type=RequestCounter,name=%s", + this.getClass().getPackage().getName(), this.name); mxBeanName = new ObjectName(mxName); if (!server.isRegistered(mxBeanName)) { server.registerMBean(this, mxBeanName); } } catch (MalformedObjectNameException ex) { mxBeanName = null; } catch (InstanceAlreadyExistsException ex) { mxBeanName = null; } catch (MBeanRegistrationException ex) { mxBeanName = null; } catch (NotCompliantMBeanException ex) { mxBeanName = null; } } /** * * @return name of this counter */ public String getName() { return name; } @Override public synchronized String toString() { String aName = name; if(name.length() >34) { aName = aName.substring(0,34); } StringBuilder sb = new StringBuilder(); Formatter formatter = new Formatter(sb); formatter.format("%-34s %9d %9d", aName, requests, failed); formatter.flush(); formatter.close(); return sb.toString(); } /** * * @return number of request invocations known to this counter */ public synchronized int getTotalRequests() { return requests; } @Override public synchronized void reset() { requests = 0; failed = 0; } @Override public synchronized void shutdown() { if(mxBeanName != null) { try { MBeanServer server = ManagementFactory.getPlatformMBeanServer(); server.unregisterMBean( mxBeanName); }catch( InstanceNotFoundException e) { // ignored }catch(MBeanRegistrationException e) { // ignored } } } /** * increments the number of request invocations known to this counter * @param requests number by which to increment */ public synchronized void incrementRequests(int requests) { this.requests += requests; } /** * increments the number of request invocations known to this counter by 1 */ public synchronized void incrementRequests() { requests++; } /** * * @return number of faild request invocations known to this counter */ public synchronized int getFailed() { return failed; } /** * increments the number of failed request invocations known to this * counter * @param failed number by which to increment */ public synchronized void incrementFailed(int failed) { this.failed += failed; } /** * increments the number of failed request invocations known to this counter * by 1 */ public synchronized void incrementFailed() { failed++; } /** * * @return number of requests that succeed * This number is calculated as a difference between the * total number of requests executed and the failed requests. * The number of Successful requests is accurate only if both * number of requests executed and the failed requests are recorded * accurately */ public synchronized int getSuccessful() { return requests - failed; } }
true
true
public RequestCounterImpl(String name) { this.name = name; MBeanServer server = ManagementFactory.getPlatformMBeanServer(); try { String mxName = String.format("%s:type=RequestCounter,name=%s", this.getClass().getPackage(), this.name); mxBeanName = new ObjectName(mxName); if (!server.isRegistered(mxBeanName)) { server.registerMBean(this, mxBeanName); } } catch (MalformedObjectNameException ex) { mxBeanName = null; } catch (InstanceAlreadyExistsException ex) { mxBeanName = null; } catch (MBeanRegistrationException ex) { mxBeanName = null; } catch (NotCompliantMBeanException ex) { mxBeanName = null; } }
public RequestCounterImpl(String name) { this.name = name; MBeanServer server = ManagementFactory.getPlatformMBeanServer(); try { String mxName = String.format("%s:type=RequestCounter,name=%s", this.getClass().getPackage().getName(), this.name); mxBeanName = new ObjectName(mxName); if (!server.isRegistered(mxBeanName)) { server.registerMBean(this, mxBeanName); } } catch (MalformedObjectNameException ex) { mxBeanName = null; } catch (InstanceAlreadyExistsException ex) { mxBeanName = null; } catch (MBeanRegistrationException ex) { mxBeanName = null; } catch (NotCompliantMBeanException ex) { mxBeanName = null; } }
diff --git a/project-set/components/client-auth/src/main/java/com/rackspace/papi/components/clientauth/ClientAuthenticationHandlerFactory.java b/project-set/components/client-auth/src/main/java/com/rackspace/papi/components/clientauth/ClientAuthenticationHandlerFactory.java index cf9ccacf90..ba97935664 100644 --- a/project-set/components/client-auth/src/main/java/com/rackspace/papi/components/clientauth/ClientAuthenticationHandlerFactory.java +++ b/project-set/components/client-auth/src/main/java/com/rackspace/papi/components/clientauth/ClientAuthenticationHandlerFactory.java @@ -1,104 +1,105 @@ package com.rackspace.papi.components.clientauth; import com.rackspace.papi.auth.AuthModule; import com.rackspace.papi.commons.config.manager.UpdateListener; import com.rackspace.papi.commons.util.regex.KeyedRegexExtractor; import com.rackspace.papi.components.clientauth.config.ClientAuthConfig; import com.rackspace.papi.components.clientauth.config.URIPattern; import com.rackspace.papi.components.clientauth.config.WhiteList; import com.rackspace.papi.components.clientauth.openstack.config.ClientMapping; import com.rackspace.papi.components.clientauth.openstack.v1_0.OpenStackAuthenticationHandlerFactory; import com.rackspace.papi.components.clientauth.rackspace.config.AccountMapping; import com.rackspace.papi.components.clientauth.rackspace.v1_1.RackspaceAuthenticationHandlerFactory; import com.rackspace.papi.filter.logic.AbstractConfiguredFilterHandlerFactory; import com.rackspace.papi.service.datastore.Datastore; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import org.slf4j.Logger; /** * * @author jhopper * * The purpose of this class is to handle client authentication. Multiple * authentication schemes may be used depending on the configuration. For * example, a Rackspace specific or Basic Http authentication. * */ public class ClientAuthenticationHandlerFactory extends AbstractConfiguredFilterHandlerFactory<AuthModule> { private static final Logger LOG = org.slf4j.LoggerFactory.getLogger(ClientAuthenticationHandlerFactory.class); private AuthModule authenticationModule; private KeyedRegexExtractor<String> accountRegexExtractor = new KeyedRegexExtractor<String>(); private UriMatcher uriMatcher; private final Datastore datastore; public ClientAuthenticationHandlerFactory(Datastore datastore) { this.datastore = datastore; } @Override protected Map<Class, UpdateListener<?>> getListeners() { final Map<Class, UpdateListener<?>> listenerMap = new HashMap<Class, UpdateListener<?>>(); listenerMap.put(ClientAuthConfig.class, new ClientAuthConfigurationListener()); return listenerMap; } private class ClientAuthConfigurationListener implements UpdateListener<ClientAuthConfig> { @Override public void configurationUpdated(ClientAuthConfig modifiedConfig) { updateUriMatcher(modifiedConfig.getWhiteList()); + accountRegexExtractor.clear(); if (modifiedConfig.getRackspaceAuth() != null) { authenticationModule = getRackspaceAuthHandler(modifiedConfig); for (AccountMapping accountMapping : modifiedConfig.getRackspaceAuth().getAccountMapping()) { accountRegexExtractor.addPattern(accountMapping.getIdRegex(), accountMapping.getType().value()); } } else if (modifiedConfig.getOpenstackAuth() != null) { authenticationModule = getOpenStackAuthHandler(modifiedConfig); for (ClientMapping clientMapping : modifiedConfig.getOpenstackAuth().getClientMapping()) { accountRegexExtractor.addPattern(clientMapping.getIdRegex()); } } else if (modifiedConfig.getHttpBasicAuth() != null) { // TODO: Create handler for HttpBasic authenticationModule = null; } else { LOG.error("Authentication module is not understood or supported. Please check your configuration."); } } } private void updateUriMatcher(WhiteList whiteList) { final List<Pattern> whiteListRegexPatterns = new ArrayList<Pattern>(); if (whiteList != null) { for (URIPattern pattern : whiteList.getUriPattern()) { whiteListRegexPatterns.add(Pattern.compile(pattern.getUriRegex())); } } uriMatcher = new UriMatcher(whiteListRegexPatterns); } private AuthModule getRackspaceAuthHandler(ClientAuthConfig cfg) { return RackspaceAuthenticationHandlerFactory.newInstance(cfg, accountRegexExtractor, datastore, uriMatcher); } private AuthModule getOpenStackAuthHandler(ClientAuthConfig config) { return OpenStackAuthenticationHandlerFactory.newInstance(config, accountRegexExtractor, datastore, uriMatcher); } @Override protected AuthModule buildHandler() { return authenticationModule; } }
true
true
public void configurationUpdated(ClientAuthConfig modifiedConfig) { updateUriMatcher(modifiedConfig.getWhiteList()); if (modifiedConfig.getRackspaceAuth() != null) { authenticationModule = getRackspaceAuthHandler(modifiedConfig); for (AccountMapping accountMapping : modifiedConfig.getRackspaceAuth().getAccountMapping()) { accountRegexExtractor.addPattern(accountMapping.getIdRegex(), accountMapping.getType().value()); } } else if (modifiedConfig.getOpenstackAuth() != null) { authenticationModule = getOpenStackAuthHandler(modifiedConfig); for (ClientMapping clientMapping : modifiedConfig.getOpenstackAuth().getClientMapping()) { accountRegexExtractor.addPattern(clientMapping.getIdRegex()); } } else if (modifiedConfig.getHttpBasicAuth() != null) { // TODO: Create handler for HttpBasic authenticationModule = null; } else { LOG.error("Authentication module is not understood or supported. Please check your configuration."); } }
public void configurationUpdated(ClientAuthConfig modifiedConfig) { updateUriMatcher(modifiedConfig.getWhiteList()); accountRegexExtractor.clear(); if (modifiedConfig.getRackspaceAuth() != null) { authenticationModule = getRackspaceAuthHandler(modifiedConfig); for (AccountMapping accountMapping : modifiedConfig.getRackspaceAuth().getAccountMapping()) { accountRegexExtractor.addPattern(accountMapping.getIdRegex(), accountMapping.getType().value()); } } else if (modifiedConfig.getOpenstackAuth() != null) { authenticationModule = getOpenStackAuthHandler(modifiedConfig); for (ClientMapping clientMapping : modifiedConfig.getOpenstackAuth().getClientMapping()) { accountRegexExtractor.addPattern(clientMapping.getIdRegex()); } } else if (modifiedConfig.getHttpBasicAuth() != null) { // TODO: Create handler for HttpBasic authenticationModule = null; } else { LOG.error("Authentication module is not understood or supported. Please check your configuration."); } }
diff --git a/modules/foundation/xremwin/src/classes/org/jdesktop/wonderland/modules/xremwin/server/cell/AppCellMOXrw.java b/modules/foundation/xremwin/src/classes/org/jdesktop/wonderland/modules/xremwin/server/cell/AppCellMOXrw.java index dc548fb8f..edcbfabfe 100644 --- a/modules/foundation/xremwin/src/classes/org/jdesktop/wonderland/modules/xremwin/server/cell/AppCellMOXrw.java +++ b/modules/foundation/xremwin/src/classes/org/jdesktop/wonderland/modules/xremwin/server/cell/AppCellMOXrw.java @@ -1,73 +1,73 @@ /** * Project Wonderland * * Copyright (c) 2004-2008, Sun Microsystems, Inc., All Rights Reserved * * Redistributions in source code form must reproduce the above * copyright and this condition. * * The contents of this file are subject to the GNU General Public * License, Version 2 (the "License"); you may not use this file * except in compliance with the License. A copy of the License is * available at http://www.opensource.org/licenses/gpl-license.php. * * $Revision$ * $Date$ * $State$ */ package org.jdesktop.wonderland.modules.xremwin.server.cell; import java.util.logging.Logger; import org.jdesktop.wonderland.common.ExperimentalAPI; import org.jdesktop.wonderland.common.cell.ClientCapabilities; import org.jdesktop.wonderland.common.cell.state.CellServerState; import org.jdesktop.wonderland.modules.appbase.server.cell.AppConventionalCellMO; import org.jdesktop.wonderland.modules.xremwin.common.cell.AppCellXrwServerState; import org.jdesktop.wonderland.server.comms.WonderlandClientID; /** * The server-side cell for an Xremwin application. * * @author deronj */ @ExperimentalAPI public class AppCellMOXrw extends AppConventionalCellMO { private static final Logger logger = Logger.getLogger(AppCellMOXrw.class.getName()); /** The parameters from the WFS file. */ private AppCellXrwServerState serverState; /** Create an instance of AppCellMOXrw. */ public AppCellMOXrw() { super(); } /** * {@inheritDoc} */ @Override protected String getClientCellClassName(WonderlandClientID clientID, ClientCapabilities capabilities) { return "org.jdesktop.wonderland.modules.xremwin.client.cell.AppCellXrw"; } /** * {@inheritDoc} */ @Override public void setServerState(CellServerState state) { System.err.println("**************** Enter AppCellMOXrw.setServerState: state = " + state); super.setServerState(state); serverState = (AppCellXrwServerState) state; } /** * {@inheritDoc} */ @Override public CellServerState getServerState(CellServerState state) { if (state == null) { - return null; + state = new AppCellXrwServerState(); } return super.getServerState(state); } }
true
true
public CellServerState getServerState(CellServerState state) { if (state == null) { return null; } return super.getServerState(state); }
public CellServerState getServerState(CellServerState state) { if (state == null) { state = new AppCellXrwServerState(); } return super.getServerState(state); }
diff --git a/tests/src/com/android/providers/contacts/GlobalSearchSupportTest.java b/tests/src/com/android/providers/contacts/GlobalSearchSupportTest.java index 40ac1ba..066c47e 100644 --- a/tests/src/com/android/providers/contacts/GlobalSearchSupportTest.java +++ b/tests/src/com/android/providers/contacts/GlobalSearchSupportTest.java @@ -1,397 +1,397 @@ /* * 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.android.providers.contacts; import android.accounts.Account; import android.app.SearchManager; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import android.provider.ContactsContract; import android.provider.ContactsContract.CommonDataKinds.GroupMembership; import android.provider.ContactsContract.Contacts; import android.provider.ContactsContract.Data; import android.provider.ContactsContract.Intents; import android.provider.ContactsContract.StatusUpdates; import android.test.suitebuilder.annotation.LargeTest; /** * Unit tests for {@link GlobalSearchSupport}. * <p> * Run the test like this: * <p> * <code><pre> * adb shell am instrument -e class com.android.providers.contacts.GlobalSearchSupportTest -w \ * com.android.providers.contacts.tests/android.test.InstrumentationTestRunner * </pre></code> */ @LargeTest public class GlobalSearchSupportTest extends BaseContactsProvider2Test { public void testSearchSuggestionsNotInDefaultDirectory() throws Exception { Account account = new Account("actname", "acttype"); // Creating an AUTO_ADD group will exclude all ungrouped contacts from global search createGroup(account, "any", "any", 0 /* visible */, true /* auto-add */, false /* fav */); long rawContactId = createRawContact(account); insertStructuredName(rawContactId, "Deer", "Dough"); // Remove the new contact from all groups mResolver.delete(Data.CONTENT_URI, Data.RAW_CONTACT_ID + "=" + rawContactId + " AND " + Data.MIMETYPE + "='" + GroupMembership.CONTENT_ITEM_TYPE + "'", null); Uri searchUri = new Uri.Builder().scheme("content").authority(ContactsContract.AUTHORITY) .appendPath(SearchManager.SUGGEST_URI_PATH_QUERY).appendPath("D").build(); // If the contact is not in the "my contacts" group, nothing should be found Cursor c = mResolver.query(searchUri, null, null, null, null); assertEquals(0, c.getCount()); c.close(); } public void testSearchSuggestionsByNameWithPhoto() throws Exception { GoldenContact contact = new GoldenContactBuilder().name("Deer", "Dough").photo( loadTestPhoto()).build(); new SuggestionTesterBuilder(contact).query("D").expectIcon1Uri(true).expectedText1( "Deer Dough").build().test(); } public void testSearchSuggestionsByEmailWithPhoto() { GoldenContact contact = new GoldenContactBuilder().name("Deer", "Dough").photo( loadTestPhoto()).email("[email protected]").build(); new SuggestionTesterBuilder(contact).query("foo@ac").expectIcon1Uri(true).expectedIcon2( String.valueOf(StatusUpdates.getPresenceIconResourceId(StatusUpdates.OFFLINE))) .expectedText1("Deer Dough").expectedText2("[email protected]").build().test(); } public void testSearchSuggestionsByName() { GoldenContact contact = new GoldenContactBuilder().name("Deer", "Dough").company("Google") .build(); new SuggestionTesterBuilder(contact).query("D").expectedText1("Deer Dough").expectedText2( null).build().test(); } public void testSearchByNickname() { GoldenContact contact = new GoldenContactBuilder().name("Deer", "Dough").nickname( "Little Fawn").company("Google").build(); new SuggestionTesterBuilder(contact).query("L").expectedText1("Deer Dough").expectedText2( "Little Fawn").build().test(); } public void testSearchByCompany() { GoldenContact contact = new GoldenContactBuilder().name("Deer", "Dough").company("Google") .build(); new SuggestionTesterBuilder(contact).query("G").expectedText1("Deer Dough").expectedText2( "Google").build().test(); } public void testSearchByTitleWithCompany() { GoldenContact contact = new GoldenContactBuilder().name("Deer", "Dough").company("Google") .title("Software Engineer").build(); new SuggestionTesterBuilder(contact).query("S").expectIcon1Uri(false).expectedText1( "Deer Dough").expectedText2("Software Engineer, Google").build().test(); } public void testSearchSuggestionsByPhoneNumberOnNonPhone() throws Exception { getContactsProvider().setIsPhone(false); GoldenContact contact = new GoldenContactBuilder().name("Deer", "Dough").photo( loadTestPhoto()).phone("1-800-4664-411").build(); new SuggestionTesterBuilder(contact).query("1800").expectIcon1Uri(true).expectedText1( "Deer Dough").expectedText2("1-800-4664-411").build().test(); } public void testSearchSuggestionsByPhoneNumberOnPhone() throws Exception { getContactsProvider().setIsPhone(true); ContentValues values = new ContentValues(); Uri searchUri = new Uri.Builder().scheme("content").authority(ContactsContract.AUTHORITY) - .appendPath(SearchManager.SUGGEST_URI_PATH_QUERY).appendPath("12345").build(); + .appendPath(SearchManager.SUGGEST_URI_PATH_QUERY).appendPath("12345678").build(); Cursor c = mResolver.query(searchUri, null, null, null, null); assertEquals(2, c.getCount()); c.moveToFirst(); values.put(SearchManager.SUGGEST_COLUMN_TEXT_1, "Dial number"); - values.put(SearchManager.SUGGEST_COLUMN_TEXT_2, "using 12345"); + values.put(SearchManager.SUGGEST_COLUMN_TEXT_2, "using 12345678"); values.put(SearchManager.SUGGEST_COLUMN_ICON_1, String.valueOf(com.android.internal.R.drawable.call_contact)); values.put(SearchManager.SUGGEST_COLUMN_INTENT_ACTION, Intents.SEARCH_SUGGESTION_DIAL_NUMBER_CLICKED); - values.put(SearchManager.SUGGEST_COLUMN_INTENT_DATA, "tel:12345"); + values.put(SearchManager.SUGGEST_COLUMN_INTENT_DATA, "tel:12345678"); values.putNull(SearchManager.SUGGEST_COLUMN_SHORTCUT_ID); assertCursorValues(c, values); c.moveToNext(); values.clear(); values.put(SearchManager.SUGGEST_COLUMN_TEXT_1, "Create contact"); - values.put(SearchManager.SUGGEST_COLUMN_TEXT_2, "using 12345"); + values.put(SearchManager.SUGGEST_COLUMN_TEXT_2, "using 12345678"); values.put(SearchManager.SUGGEST_COLUMN_ICON_1, String.valueOf(com.android.internal.R.drawable.create_contact)); values.put(SearchManager.SUGGEST_COLUMN_INTENT_ACTION, Intents.SEARCH_SUGGESTION_CREATE_CONTACT_CLICKED); - values.put(SearchManager.SUGGEST_COLUMN_INTENT_DATA, "tel:12345"); + values.put(SearchManager.SUGGEST_COLUMN_INTENT_DATA, "tel:12345678"); values.put(SearchManager.SUGGEST_COLUMN_SHORTCUT_ID, SearchManager.SUGGEST_NEVER_MAKE_SHORTCUT); assertCursorValues(c, values); c.close(); } /** * Tests that the quick search suggestion returns the expected contact * information. */ private final class SuggestionTester { private final GoldenContact contact; private final String query; private final boolean expectIcon1Uri; private final String expectedIcon2; private final String expectedText1; private final String expectedText2; public SuggestionTester(SuggestionTesterBuilder builder) { contact = builder.contact; query = builder.query; expectIcon1Uri = builder.expectIcon1Uri; expectedIcon2 = builder.expectedIcon2; expectedText1 = builder.expectedText1; expectedText2 = builder.expectedText2; } /** * Tests suggest and refresh queries from quick search box, then deletes the contact from * the data base. */ public void test() { testQsbSuggest(); testContactIdQsbRefresh(); testLookupKeyQsbRefresh(); // Cleanup contact.delete(); } /** * Tests that the contacts provider return the appropriate information from the golden * contact in response to the suggestion query from the quick search box. */ private void testQsbSuggest() { Uri searchUri = new Uri.Builder().scheme("content").authority( ContactsContract.AUTHORITY).appendPath(SearchManager.SUGGEST_URI_PATH_QUERY) .appendPath(query).build(); Cursor c = mResolver.query(searchUri, null, null, null, null); assertEquals(1, c.getCount()); c.moveToFirst(); String icon1 = c.getString(c.getColumnIndex(SearchManager.SUGGEST_COLUMN_ICON_1)); if (expectIcon1Uri) { assertTrue(icon1.startsWith("content:")); } else { assertEquals(String.valueOf(com.android.internal.R.drawable.ic_contact_picture), icon1); } // SearchManager does not declare a constant for _id ContentValues values = getContactValues(); assertCursorValues(c, values); c.close(); } /** * Returns the expected Quick Search Box content values for the golden contact. */ private ContentValues getContactValues() { ContentValues values = new ContentValues(); values.put("_id", contact.getContactId()); values.put(SearchManager.SUGGEST_COLUMN_TEXT_1, expectedText1); values.put(SearchManager.SUGGEST_COLUMN_TEXT_2, expectedText2); values.put(SearchManager.SUGGEST_COLUMN_ICON_2, expectedIcon2); values.put(SearchManager.SUGGEST_COLUMN_INTENT_DATA, Contacts.getLookupUri(contact.getContactId(), contact.getLookupKey()) .toString()); values.put(SearchManager.SUGGEST_COLUMN_SHORTCUT_ID, contact.getLookupKey()); values.put(SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA, query); return values; } /** * Returns the expected Quick Search Box content values for the golden contact. */ private ContentValues getRefreshValues() { ContentValues values = new ContentValues(); values.put("_id", contact.getContactId()); values.put(SearchManager.SUGGEST_COLUMN_TEXT_1, expectedText1); values.put(SearchManager.SUGGEST_COLUMN_TEXT_2, expectedText2); values.put(SearchManager.SUGGEST_COLUMN_ICON_2, expectedIcon2); values.put(SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID, contact.getLookupKey()); values.put(SearchManager.SUGGEST_COLUMN_SHORTCUT_ID, contact.getLookupKey()); return values; } /** * Performs the refresh query and returns a cursor to the results. * * @param refreshId the final component path of the refresh query, which identifies which * contact to refresh. */ private Cursor refreshQuery(String refreshId) { // See if the same result is returned by a shortcut refresh Uri refershUri = ContactsContract.AUTHORITY_URI.buildUpon().appendPath( SearchManager.SUGGEST_URI_PATH_SHORTCUT) .appendPath(refreshId) .appendQueryParameter(SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA, query) .build(); String[] projection = new String[] { SearchManager.SUGGEST_COLUMN_ICON_1, SearchManager.SUGGEST_COLUMN_ICON_2, SearchManager.SUGGEST_COLUMN_TEXT_1, SearchManager.SUGGEST_COLUMN_TEXT_2, SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID, SearchManager.SUGGEST_COLUMN_SHORTCUT_ID, "_id", }; return mResolver.query(refershUri, projection, null, null, null); } /** * Tests that the contacts provider returns an empty result in response to a refresh query * from the quick search box that uses the contact id to identify the contact. The empty * result indicates that the shortcut is no longer valid, and the QSB will replace it with * a new-style shortcut the next time they click on the contact. * * @see #testLookupKeyQsbRefresh() */ private void testContactIdQsbRefresh() { Cursor c = refreshQuery(String.valueOf(contact.getContactId())); try { assertEquals("Record count", 0, c.getCount()); } finally { c.close(); } } /** * Tests that the contacts provider return the appropriate information from the golden * contact in response to the refresh query from the quick search box. The refresh query * uses the currently-supported mechanism of identifying the contact by the lookup key, * which is more stable than the previously used contact id. */ private void testLookupKeyQsbRefresh() { Cursor c = refreshQuery(contact.getLookupKey()); try { assertEquals("Record count", 1, c.getCount()); c.moveToFirst(); assertCursorValues(c, getRefreshValues()); } finally { c.close(); } } } /** * Builds {@link SuggestionTester} objects. Unspecified boolean objects default to * false. Unspecified String objects default to null. */ private final class SuggestionTesterBuilder { private final GoldenContact contact; private String query; private boolean expectIcon1Uri; private String expectedIcon2; private String expectedText1; private String expectedText2; public SuggestionTesterBuilder(GoldenContact contact) { this.contact = contact; } /** * Builds the {@link SuggestionTester} specified by this builder. */ public SuggestionTester build() { return new SuggestionTester(this); } /** * The text of the user's query to quick search (i.e., what they typed * in the search box). */ public SuggestionTesterBuilder query(String value) { query = value; return this; } /** * Whether to set Icon1, which in practice is the contact's photo. * <p> * TODO(tomo): Replace with actual expected value? This might be hard * because the values look non-deterministic, such as * "content://com.android.contacts/contacts/2015/photo" */ public SuggestionTesterBuilder expectIcon1Uri(boolean value) { expectIcon1Uri = value; return this; } /** * The value for Icon2, which in practice is the contact's Chat status * (available, busy, etc.) */ public SuggestionTesterBuilder expectedIcon2(String value) { expectedIcon2 = value; return this; } /** * First line of suggestion text expected to be returned (required). */ public SuggestionTesterBuilder expectedText1(String value) { expectedText1 = value; return this; } /** * Second line of suggestion text expected to return (optional). */ public SuggestionTesterBuilder expectedText2(String value) { expectedText2 = value; return this; } } }
false
true
public void testSearchSuggestionsByPhoneNumberOnPhone() throws Exception { getContactsProvider().setIsPhone(true); ContentValues values = new ContentValues(); Uri searchUri = new Uri.Builder().scheme("content").authority(ContactsContract.AUTHORITY) .appendPath(SearchManager.SUGGEST_URI_PATH_QUERY).appendPath("12345").build(); Cursor c = mResolver.query(searchUri, null, null, null, null); assertEquals(2, c.getCount()); c.moveToFirst(); values.put(SearchManager.SUGGEST_COLUMN_TEXT_1, "Dial number"); values.put(SearchManager.SUGGEST_COLUMN_TEXT_2, "using 12345"); values.put(SearchManager.SUGGEST_COLUMN_ICON_1, String.valueOf(com.android.internal.R.drawable.call_contact)); values.put(SearchManager.SUGGEST_COLUMN_INTENT_ACTION, Intents.SEARCH_SUGGESTION_DIAL_NUMBER_CLICKED); values.put(SearchManager.SUGGEST_COLUMN_INTENT_DATA, "tel:12345"); values.putNull(SearchManager.SUGGEST_COLUMN_SHORTCUT_ID); assertCursorValues(c, values); c.moveToNext(); values.clear(); values.put(SearchManager.SUGGEST_COLUMN_TEXT_1, "Create contact"); values.put(SearchManager.SUGGEST_COLUMN_TEXT_2, "using 12345"); values.put(SearchManager.SUGGEST_COLUMN_ICON_1, String.valueOf(com.android.internal.R.drawable.create_contact)); values.put(SearchManager.SUGGEST_COLUMN_INTENT_ACTION, Intents.SEARCH_SUGGESTION_CREATE_CONTACT_CLICKED); values.put(SearchManager.SUGGEST_COLUMN_INTENT_DATA, "tel:12345"); values.put(SearchManager.SUGGEST_COLUMN_SHORTCUT_ID, SearchManager.SUGGEST_NEVER_MAKE_SHORTCUT); assertCursorValues(c, values); c.close(); }
public void testSearchSuggestionsByPhoneNumberOnPhone() throws Exception { getContactsProvider().setIsPhone(true); ContentValues values = new ContentValues(); Uri searchUri = new Uri.Builder().scheme("content").authority(ContactsContract.AUTHORITY) .appendPath(SearchManager.SUGGEST_URI_PATH_QUERY).appendPath("12345678").build(); Cursor c = mResolver.query(searchUri, null, null, null, null); assertEquals(2, c.getCount()); c.moveToFirst(); values.put(SearchManager.SUGGEST_COLUMN_TEXT_1, "Dial number"); values.put(SearchManager.SUGGEST_COLUMN_TEXT_2, "using 12345678"); values.put(SearchManager.SUGGEST_COLUMN_ICON_1, String.valueOf(com.android.internal.R.drawable.call_contact)); values.put(SearchManager.SUGGEST_COLUMN_INTENT_ACTION, Intents.SEARCH_SUGGESTION_DIAL_NUMBER_CLICKED); values.put(SearchManager.SUGGEST_COLUMN_INTENT_DATA, "tel:12345678"); values.putNull(SearchManager.SUGGEST_COLUMN_SHORTCUT_ID); assertCursorValues(c, values); c.moveToNext(); values.clear(); values.put(SearchManager.SUGGEST_COLUMN_TEXT_1, "Create contact"); values.put(SearchManager.SUGGEST_COLUMN_TEXT_2, "using 12345678"); values.put(SearchManager.SUGGEST_COLUMN_ICON_1, String.valueOf(com.android.internal.R.drawable.create_contact)); values.put(SearchManager.SUGGEST_COLUMN_INTENT_ACTION, Intents.SEARCH_SUGGESTION_CREATE_CONTACT_CLICKED); values.put(SearchManager.SUGGEST_COLUMN_INTENT_DATA, "tel:12345678"); values.put(SearchManager.SUGGEST_COLUMN_SHORTCUT_ID, SearchManager.SUGGEST_NEVER_MAKE_SHORTCUT); assertCursorValues(c, values); c.close(); }
diff --git a/src/main/java/jenkins/plugins/publish_over_ssh/BapSshHostConfiguration.java b/src/main/java/jenkins/plugins/publish_over_ssh/BapSshHostConfiguration.java index 1e665cd..f40eb25 100644 --- a/src/main/java/jenkins/plugins/publish_over_ssh/BapSshHostConfiguration.java +++ b/src/main/java/jenkins/plugins/publish_over_ssh/BapSshHostConfiguration.java @@ -1,109 +1,109 @@ /* * The MIT License * * Copyright (C) 2010-2011 by Anthony Robinson * * 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 jenkins.plugins.publish_over_ssh; import hudson.Extension; import hudson.model.Describable; import hudson.model.Descriptor; import hudson.model.Hudson; import hudson.util.FormValidation; import jenkins.plugins.publish_over.BPValidators; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; public class BapSshHostConfiguration extends BapHostConfiguration implements Describable<BapSshHostConfiguration> { private static final long serialVersionUID = 1L; @DataBoundConstructor @SuppressWarnings("PMD.ExcessiveParameterList") public BapSshHostConfiguration(final String name, final String hostname, final String username, final String password, final String remoteRootDir, final int port, final int timeout, final boolean overrideKey, final String keyPath, final String key, final boolean disableExec) { super(name, hostname, username, password, remoteRootDir, port, timeout, overrideKey, keyPath, key, disableExec); } public DescriptorImpl getDescriptor() { return Hudson.getInstance().getDescriptorByType(DescriptorImpl.class); } public boolean equals(final Object that) { if (this == that) return true; if (that == null || getClass() != that.getClass()) return false; - final BapSshHostConfiguration thatSshCommonConfiguration = (BapSshHostConfiguration) that; + final BapSshHostConfiguration thatHostConfig = (BapSshHostConfiguration) that; - return createEqualsBuilder(thatSshCommonConfiguration).isEquals(); + return createEqualsBuilder(thatHostConfig).isEquals(); } public int hashCode() { return createHashCodeBuilder().toHashCode(); } public String toString() { return addToToString(new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)).toString(); } @Extension public static class DescriptorImpl extends Descriptor<BapSshHostConfiguration> { @Override public String getDisplayName() { return Messages.global_common_descriptor(); } public int getDefaultPort() { return BapHostConfiguration.DEFAULT_PORT; } public int getDefaultTimeout() { return BapHostConfiguration.DEFAULT_TIMEOUT; } public FormValidation doCheckName(@QueryParameter final String value) { return BPValidators.validateName(value); } public FormValidation doCheckHostname(@QueryParameter final String value) { return FormValidation.validateRequired(value); } public FormValidation doCheckUsername(@QueryParameter final String value) { return FormValidation.validateRequired(value); } public FormValidation doCheckPort(@QueryParameter final String value) { return FormValidation.validatePositiveInteger(value); } public FormValidation doCheckTimeout(@QueryParameter final String value) { return FormValidation.validateNonNegativeInteger(value); } public FormValidation doCheckKeyPath(@QueryParameter final String value) { return BPValidators.validateFileOnMaster(value); } public FormValidation doTestConnection(final StaplerRequest request, final StaplerResponse response) { final BapSshPublisherPlugin.Descriptor pluginDescriptor = Hudson.getInstance().getDescriptorByType( BapSshPublisherPlugin.Descriptor.class); return pluginDescriptor.doTestConnection(request, response); } } }
false
true
public boolean equals(final Object that) { if (this == that) return true; if (that == null || getClass() != that.getClass()) return false; final BapSshHostConfiguration thatSshCommonConfiguration = (BapSshHostConfiguration) that; return createEqualsBuilder(thatSshCommonConfiguration).isEquals(); }
public boolean equals(final Object that) { if (this == that) return true; if (that == null || getClass() != that.getClass()) return false; final BapSshHostConfiguration thatHostConfig = (BapSshHostConfiguration) that; return createEqualsBuilder(thatHostConfig).isEquals(); }
diff --git a/src/com/beanie/imagechooser/api/utils/ImageChooserBuilder.java b/src/com/beanie/imagechooser/api/utils/ImageChooserBuilder.java index 4d179cb..de5e903 100644 --- a/src/com/beanie/imagechooser/api/utils/ImageChooserBuilder.java +++ b/src/com/beanie/imagechooser/api/utils/ImageChooserBuilder.java @@ -1,46 +1,46 @@ package com.beanie.imagechooser.api.utils; import android.app.AlertDialog.Builder; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import com.beanie.imagechooser.R; import com.beanie.imagechooser.api.ChooserType; public class ImageChooserBuilder extends Builder { private OnClickListener listener; public ImageChooserBuilder(Context context, int theme, OnClickListener listener) { super(context, theme); this.listener = listener; init(); } public ImageChooserBuilder(Context context, OnClickListener listener) { super(context); this.listener = listener; init(); } private void init() { setTitle(R.string.lab_choose_option); CharSequence[] titles = { getContext().getString(R.string.lab_choose_from_gallery), getContext().getString(R.string.lab_take_picture) }; setItems(titles, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (which == 0) { listener.onClick(dialog, ChooserType.REQUEST_PICK_PICTURE); - } else if (which == 0) { + } else if (which == 1) { listener.onClick(dialog, ChooserType.REQUEST_CAPTURE_PICTURE); } } }); } }
true
true
private void init() { setTitle(R.string.lab_choose_option); CharSequence[] titles = { getContext().getString(R.string.lab_choose_from_gallery), getContext().getString(R.string.lab_take_picture) }; setItems(titles, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (which == 0) { listener.onClick(dialog, ChooserType.REQUEST_PICK_PICTURE); } else if (which == 0) { listener.onClick(dialog, ChooserType.REQUEST_CAPTURE_PICTURE); } } }); }
private void init() { setTitle(R.string.lab_choose_option); CharSequence[] titles = { getContext().getString(R.string.lab_choose_from_gallery), getContext().getString(R.string.lab_take_picture) }; setItems(titles, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (which == 0) { listener.onClick(dialog, ChooserType.REQUEST_PICK_PICTURE); } else if (which == 1) { listener.onClick(dialog, ChooserType.REQUEST_CAPTURE_PICTURE); } } }); }
diff --git a/impl/src/main/java/org/jboss/cdi/tck/tests/decorators/invocation/enterprise/BarBusinessDecorator.java b/impl/src/main/java/org/jboss/cdi/tck/tests/decorators/invocation/enterprise/BarBusinessDecorator.java index f7a5310b3..c50a24f01 100644 --- a/impl/src/main/java/org/jboss/cdi/tck/tests/decorators/invocation/enterprise/BarBusinessDecorator.java +++ b/impl/src/main/java/org/jboss/cdi/tck/tests/decorators/invocation/enterprise/BarBusinessDecorator.java @@ -1,41 +1,41 @@ /* * JBoss, Home of Professional Open Source * Copyright 2012, Red Hat, Inc., and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * 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.jboss.cdi.tck.tests.decorators.invocation.enterprise; import javax.decorator.Decorator; import javax.decorator.Delegate; import javax.inject.Inject; import org.jboss.cdi.tck.util.ActionSequence; /** * @author Martin Kouba */ @Decorator public abstract class BarBusinessDecorator implements Business { @Inject @Delegate private BarBusiness business; @Override public String businessOperation1() { - ActionSequence.addAction(BarBusinessDecorator.class.getSimpleName()); + ActionSequence.addAction(BarBusinessDecorator.class.getName()); return business.businessOperation1() + BarBusinessDecorator.class.getName(); } }
true
true
public String businessOperation1() { ActionSequence.addAction(BarBusinessDecorator.class.getSimpleName()); return business.businessOperation1() + BarBusinessDecorator.class.getName(); }
public String businessOperation1() { ActionSequence.addAction(BarBusinessDecorator.class.getName()); return business.businessOperation1() + BarBusinessDecorator.class.getName(); }
diff --git a/src/com/flaptor/util/cache/FileCache.java b/src/com/flaptor/util/cache/FileCache.java index 178ba30..2ddf2cd 100644 --- a/src/com/flaptor/util/cache/FileCache.java +++ b/src/com/flaptor/util/cache/FileCache.java @@ -1,766 +1,766 @@ /* Copyright 2008 Flaptor (flaptor.com) 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.flaptor.util.cache; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.EOFException; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.UnsupportedEncodingException; import java.lang.reflect.InvocationTargetException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Iterator; import java.util.Stack; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import org.apache.log4j.Logger; import com.flaptor.util.Execute; import com.flaptor.util.FileUtil; import com.flaptor.util.TranscodeUtil; /** * This class implements a disk-based hash table. * The cached data/object must implement Serializable * * This class is threadsafe, each thread should use its own iterator to iterate over the cache keys. * * @todo implement a entry-iterator so as to avoid duplicate file access when iterating over the keys and values * * actual VERSION: 2 - generic FileCache * supports reading VERSION 1 (byte[] FileCache) * * @author Flaptor Development Team */ public class FileCache<T> implements Iterable<String>, RmiCache<T>{ private static Logger logger = Logger.getLogger(Execute.whoAmI()); //private static byte VERSION = 1; //old byte[] fileCache private static byte VERSION = 2; private String cachedir = null; private final ADigester digester; private int subdirDepth = 2; private boolean writeToTempFiles = false; /** * Initializes the cache with a default subdirectory depth of 2 levels (subdir/subdir/file) * @param cachedir the directory of the cache. */ public FileCache (String cachedir) { this.digester = new SHADigester(); construct(cachedir); } private boolean useZipStream= true; /** * By default, the data in the cacho is stored ziped. * This contructor can be used to store it unzip. * Note: that you are the only responsible for calling the addItem and the * all the retrieve item method (getItem/iteration,hasItem...) with the same * kind of FileCache: If you added the item with a FileCache constructed * using zip=true, and then tries to read with a FileCache constructed * using zip=false, strange things can happen. * @param zip true iff the data is (to be) stored compressed * @param @param cachedir the directory of the cache. * note: the other constructors set zip=true. */ // This ctor is used in the BayesCalculator public FileCache (boolean zip, String cachedir) { this(cachedir); useZipStream= zip; } /** * This constructor behaves like {@link #FileCache(boolean, String)} and also * takes an additional writeToTempFiles parameter which causes the write operations * to occur in a temporary file that will replace the original once the write operation * has ended. This allows for another thread or process to read the item that's being * written without risking to get a partially written file. However this does not handle * the possibility of two threads or processes writting to the same file at the same time. * * @param cachedir * @param zip * @param writeToTempFiles */ public FileCache(String cachedir, boolean zip, boolean writeToTempFiles) { this(zip, cachedir); this.writeToTempFiles = writeToTempFiles; } /** * Initializes the cache with a specified subdirectory depth * @param cachedir the directory of the cache. * @param subdirDepth the subdirectory depth (2 means subdir/subdir/file). Should be strictly larger than 0 and lower than 20 */ public FileCache (String cachedir, int subdirDepth) { this.subdirDepth = subdirDepth; this.digester = new SHADigester(); construct(cachedir); } /** * Initializes a cache, using a digester that will always generate * colissions. This constructor should be only called for testing, * and behaves like this: * * If boolean parameter is false, logs ERROR and throws an * IllegalArgumentException. * * If boolean parameter is true, logs WARN and continues. * * THIS CONSTRUCTOR IS ONLY USEFUL FOR TESTING COLLISIONS * */ public FileCache (String cachedir, boolean generateCollisions) { if (false == generateCollisions) { logger.error("Using testing constructor, for a \"legitimate\" use."); throw new IllegalArgumentException("Using testing constructor"); } logger.warn("Using testing constructor"); construct(cachedir); this.digester = new ConstantDigester(); } //construction code private void construct(String cachedir) { this.cachedir = cachedir; File dir = new File(cachedir); if (!dir.exists()) { dir.mkdirs(); } } /** * Adds an item to the cache. * @param key an identification for the item. * @param data the contents of the item. */ public void addItem (String key, T value) { File file = getAssociatedFile(key); if (writeToTempFiles) { file = getTempFileForWritting(file); } ObjectOutputStream stream = null; try { if (useZipStream){ stream = new ObjectOutputStream(new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream(file)))); } else { stream = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(file))); } writeVersion(stream,VERSION); writeKey(stream, key); writeValue(stream, value); } catch (IOException e) { logger.error("Adding an item to the cache: " + e, e); } finally { try { if (null != stream) { stream.close(); } if (writeToTempFiles) { moveTempFile(file); } } catch (IOException e) { } } } private File getTempFileForWritting(File file) { return new File(file.getAbsolutePath() + ".writting"); } private void moveTempFile(File tempFile) { String path = tempFile.getAbsolutePath(); String original = path.substring(0, path.length() - ".writting".length()); if (!FileUtil.rename(path, original)) { logger.error("Unable to rename temporary cache file to actual cache file."); } } // Writes version number to a stream private void writeVersion (ObjectOutputStream stream, byte version) { try { stream.writeByte(version); } catch (IOException e) { logger.error("Writing a version to a cache item file", e); } } // Writes a block of data to a file. // Blocks contain a two-byte length field, followed by the block data. private void writeValue(ObjectOutputStream stream, T value) { try { stream.writeObject(value); } catch (IOException e) { logger.error("Writing the value to a cache item file", e); } } // Writes key private void writeKey(ObjectOutputStream stream, String key){ try { stream.writeObject(key); } catch (IOException e) { logger.error("Writing key to a cache item file", e); } } private ObjectInputStream open(File file) throws IOException { ObjectInputStream stream = null; if (useZipStream){ stream = new ObjectInputStream(new BufferedInputStream(new GZIPInputStream(new FileInputStream(file)))); } else { stream = new ObjectInputStream(new BufferedInputStream(new FileInputStream(file))); } return stream; } /** * @return the version number or -1 if the version is wrong */ private static int verifyVersion(ObjectInputStream stream) throws IOException { byte version = readVersion(stream); if (0 < version && version <= VERSION ) { return version; } else { logger.error("Wrong version: found " + version + " expected:" + VERSION); try {stream.close(); } catch (IOException e) {} return -1; } } private ObjectInputStream openAndVerifyVersion(File file) throws IOException { ObjectInputStream stream = open(file); int version = verifyVersion(stream); if (version <0) return null; else return stream; } // Reads a block of data from a file. // Blocks contain a two-byte length field, followed by the block data. @SuppressWarnings("unchecked") private T readValue (ObjectInputStream stream) { try { return (T)stream.readObject(); } catch (Throwable t) { logger.error("Reading value from a cache item file.", t); return null; } } /** Reads a block of data from a file. * Blocks contain a two-byte length field, followed by the block data. * for compatibility with old VERSION 1 */ private byte[] readByteArrayValue(ObjectInputStream stream) { try { int blocklen = stream.readInt(); byte[] block = new byte[blocklen]; stream.readFully(block); return block; } catch (IOException e) { logger.error("Reading a block to a cache item file: " + e, e); } return null; } // Reads version number from a stream. private static byte readVersion (ObjectInputStream stream) { try { return stream.readByte(); } catch (IOException e) { logger.error("Reading version number to a cache item file", e); } return 0; } // Reads key from a stream. private static String readKey (ObjectInputStream stream) { try { return (String)stream.readObject(); } catch (Exception e) { logger.error("Reading a key to a cache item file.", e); } return null; } /** * Returns true if the item is in the cache. * @param key an identification for the item. * @return true if the item is in the cache. */ public boolean hasItem (String key) { if (null == key ) return false; //else return getAssociatedFile(key).exists(); } /** * Retrieves an item from the cache. * @param key an identification for the item. * @return the contents of the cached item, or null if the item is not cached. */ @SuppressWarnings("unchecked") public T getItem (String key) { T value = null; if (null == key) { logger.error("Can't retrieve cache item with null key."); } else { try { File file = getAssociatedFile(key); if (!file.exists()) { logger.debug("There is no cache item for this key: " + key + " (" + digester.getDigest(key) + ")"); } else { boolean ok = false; ObjectInputStream stream = null; try { stream = open(file); int version = verifyVersion(stream); if (version < 0) return null; String storedKey = readKey(stream); if (null != storedKey) { if (!key.equals(storedKey)) { logger.error("Cache colission between the following keys: [" + key + "]; [" + storedKey + "]"); } else { if (version == VERSION) { value = readValue(stream); if (null != value) ok = true; } else if (version == 1) { //to support old cache, T must be byte[] value = (T) readByteArrayValue(stream); if (null != value) ok = true; } } } } catch (EOFException e) { logger.error("data incomplete for " + key + " - deleting", e); removeItem(key); } catch (IOException e) { logger.error("Getting " + key + " from the cache", e); } finally { try { if (null != stream) stream.close(); } catch (IOException e) {} } if (!ok) { logger.error("Corrupted cache file: unexpected end of file."); } } } catch (UnsupportedEncodingException e) { logger.error(e,e); } } return value; } /** * Deletes an item from the cache. * @param key an identification for the item. * @return true if the item was deleted (or didn't exist), false otherwise */ public boolean removeItem (String key) { File file = getAssociatedFile(key); if (file.exists()) { boolean deleted = file.delete(); File dir = file.getParentFile(); if (dir.list().length == 0) dir.delete(); return deleted; } // else return true; } //returns the subdirectory where a digest should be placed, // according to the subdirectory depth level private File getSubdir(String digest) { StringBuffer subdir = new StringBuffer(); for (int i = 0; i < subdirDepth; ++i) { subdir.append(digest.substring(i * 2, i * 2 + 2) + File.separator); } return new File(cachedir, subdir.toString()); } // Finds a File associated with a key. It solves collisions, and returns // as follows: // A file that exists, if the key was stored on the cache // A file that does not exist, if the key was not found. // // The file, no matter if it exists or not, will have collisions solved, // so if you wanted to know if a key was stored, check if the file exists. // If you want to write a key, you will get a file to write the key and // its content, and you can choose to overwrite if it existed or not. private File getAssociatedFile (String key) { try { String digest = digester.getDigest(key); File dir = getSubdir(digest); File file = new File(dir,digest); // If the dir did not exist, its obvious that the // file does not exist either. create dir and return new file. if (!dir.exists()) { dir.mkdirs(); return file; } File[] synonyms = dir.listFiles(new CollisionFilenameFilter(digest)); int max = -1; for (File syn: synonyms ) { ObjectInputStream stream = null; try { stream = openAndVerifyVersion(syn); } catch (IOException e) { logger.warn("could not open and verify version on " + syn.getAbsolutePath()); try {if (null != stream)stream.close();} catch (IOException ioe) {} continue; } if (null == stream) { logger.warn("could not open and verify version on " + syn.getAbsolutePath()); continue; } String storedKey = readKey(stream); try { stream.close(); } catch (IOException e) { // DO NOTHING } if (key.equals(storedKey)) { return syn; } // So, it was not what we expected. Find collision index. String[] parts = syn.getName().split("-"); int num = 0; if (2 == parts.length ) { num = Integer.parseInt(parts[1]); } max = Math.max(max,num); } // If we got out of the for loop, we did not find it. Just create // a new file with the specified name, and append max if not 0 if (max >= 0) { file = new File(dir,digest + "-" + (max+1)); } return file; } catch (UnsupportedEncodingException e) { logger.error(e,e); // IT MAKES NO SENSE TO CONTINUE IF THE HARDCODED ENCODING IS // NOT SUPPORTED BY PLATFORM. CACHE WILL BE USELESS AND CORRUPTED // WITH DUPLICATES, ETC. throw new RuntimeException(e); } } public Iterator<String> iterator() { return new CacheIterator(); } /** Implements the iterator of keys in the cache */ protected class CacheIterator implements Iterator<String>{ private Stack<File[]> enumFiles = null; private Stack<Integer> enumFileIndex = null; private File currentFile = null; private File nextFile = null; protected CacheIterator() { enumFiles = new Stack<File[]>(); enumFileIndex = new Stack<Integer>(); File root = new File(cachedir); if (root.list().length > 0) { enumFiles.push(new File[] {root}); // root level enumFileIndex.push(-1); currentFile = null; advanceNextFile(); } else { currentFile = null; nextFile = null; } } public boolean hasNext() { return null != nextFile; } public String next() { String key = null; if (hasNext()) { String storedKey = null; // Comented out because there is no other way to communicate that a cache entry is wrong except returning null. // while (null == storedKey && hasNext()) { currentFile = nextFile; advanceNextFile(); ObjectInputStream stream = null; try { stream = openAndVerifyVersion(currentFile); if (stream == null) return null; storedKey = readKey(stream); } catch (IOException e) { logger.error("Getting an enumeration key from the cache: " + e, e); } finally { try { if (null != stream) stream.close(); } catch (IOException e) {} } // } if (null != storedKey) key = storedKey; } return key; } public void remove() { currentFile.delete(); } // Advance the iterator to the next cache file. private synchronized void advanceNextFile() { do { nextFile = null; File[] files = enumFiles.peek(); int index = enumFileIndex.peek() + 1; while(index < files.length) { index = enumFileIndex.pop() + 1; enumFileIndex.push(index); File file = enumFiles.peek()[index]; if (!file.exists()) continue; //if the file doesnt exist (it was deleted) keep going if (file.isFile()) { //if the file exists, set it as currentFile and end nextFile = file; return; } if (file.isDirectory()) {//if it is a directory, get into the directory enumFiles.push(file.listFiles()); enumFileIndex.push(-1); advanceNextFile(); return; } } //we finished all files in the directory, so get out of it enumFiles.pop(); enumFileIndex.pop(); } while (enumFiles.size() > 0);//if we have nothing in enumFiles, we just popped the root directory and we are done } } private interface ADigester { public String getDigest(String param) throws UnsupportedEncodingException; } private class SHADigester implements ADigester { private MessageDigest md = null; public SHADigester() { try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { logger.error("Initializing the cache: " + e, e); throw new RuntimeException(e); } } public String getDigest (String key) throws UnsupportedEncodingException { return TranscodeUtil.binToHex(md.digest(key.getBytes("UTF-8"))); } } private static class ConstantDigester implements ADigester { public String getDigest (String param) throws UnsupportedEncodingException { return "constant"; } } private class CollisionFilenameFilter implements java.io.FilenameFilter { private String prefix; public CollisionFilenameFilter(String digest) { this.prefix = digest; } public boolean accept(File dir,String filename) { return filename.startsWith(prefix); } } public static void main (String[] args) { - String usage = "Cache get <dir> \nCache get <dir> <url>\\nCache getobj <dir> \\nCache getobj <dir> <url>\nCache getobjprop <dir> <method> \nCache getobjprop <dir> <method> <url>\nCache list <dir>\nCache translate <src dir> <dest dir> <src file depth>"; + String usage = "Cache get <dir> \nCache get <dir> <url>\nCache getobj <dir> \nCache getobj <dir> <url>\nCache getobjprop <dir> <method> \nCache getobjprop <dir> <method> <url>\nCache list <dir>\nCache translate <src dir> <dest dir> <src file depth>"; if (args.length != 2 && args.length != 3 && args.length != 4) { System.out.println(usage); System.exit(1); } if ("get".equals(args[0])) { FileCache<byte[]> cache = new FileCache<byte[]>(args[1]); if (args.length == 2) { Iterator<String> it = cache.iterator(); while (it.hasNext()) { String key = it.next(); byte[] data = cache.getItem(key); System.out.println("-------"); System.out.println(key); System.out.println(); System.out.println(new String(data)); System.out.println(); } System.out.println("-------"); } else { byte[] data = cache.getItem(args[2]); if (null == data) { System.out.println("Page not found in cache"); } else { System.out.println(); System.out.println(args[2]); System.out.println(); System.out.println(new String(data)); System.out.println(); } } } else if ("getobj".equals(args[0])) { FileCache<Object> cache = new FileCache<Object>(args[1]); if (args.length == 2) { Iterator<String> it = cache.iterator(); while (it.hasNext()) { String key = it.next(); Object data = cache.getItem(key); System.out.println("-------"); System.out.println(key); System.out.println(); System.out.println(String.valueOf(data)); System.out.println(); } System.out.println("-------"); } else { Object data = cache.getItem(args[2]); if (null == data) { System.out.println("Page not found in cache"); } else { System.out.println(); System.out.println(args[2]); System.out.println(); System.out.println(String.valueOf(data)); System.out.println(); } } } else if ("getobjprop".equals(args[0])) { FileCache<Object> cache = new FileCache<Object>(args[1]); if (args.length == 3) { Iterator<String> it = cache.iterator(); while (it.hasNext()) { String key = it.next(); Object data = getProperty(cache.getItem(key), args[2]); System.out.println("-------"); System.out.println(key); System.out.println(); System.out.println(String.valueOf(data)); System.out.println(); } System.out.println("-------"); } else { Object data = getProperty(cache.getItem(args[3]), args[2]); if (null == data) { System.out.println("Page not found in cache"); } else { System.out.println(); System.out.println(args[3]); System.out.println(); System.out.println(String.valueOf(data)); System.out.println(); } } } else if ("list".equals(args[0])) { FileCache<Object> cache = new FileCache<Object>(args[1]); Iterator<String> en = cache.iterator(); while (en.hasNext()) { System.out.println(en.next()); } } else if ("purge".equals(args[0])) { FileCache<Object> cache = new FileCache<Object>(args[1]); Iterator<String> en = cache.iterator(); while (en.hasNext()) { Object value = en.next(); if (null == value) { System.out.println("Removing faulty cache entry"); en.remove(); } } System.out.println("Done."); } else if ("translate".equals(args[0])) { FileCache<byte[]> cacheSrc = new FileCache<byte[]>(args[1], Integer.parseInt(args[3])); FileCache<byte[]> cacheDest = new FileCache<byte[]>(args[2]); for (String key: cacheSrc) { System.out.println("translating " + key); cacheDest.addItem(key, cacheSrc.getItem(key)); } System.out.println("Done."); } } private static Object getProperty(Object object, String property) { if (object == null) return null; try { return object.getClass().getMethod(property, new Class[0]).invoke(object, new Object[0]); } catch (SecurityException e) { System.out.println("Unable to obtain property " + property + " from class "+ object.getClass()); } catch (NoSuchMethodException e) { System.out.println("Unable to obtain property " + property + " from class "+ object.getClass()); } catch (IllegalArgumentException e) { System.out.println("Unable to obtain property " + property + " from class "+ object.getClass()); } catch (IllegalAccessException e) { System.out.println("Unable to obtain property " + property + " from class "+ object.getClass()); } catch (InvocationTargetException e) { System.out.println("Unable to obtain property " + property + " from class "+ object.getClass()); } return null; } }
true
true
public static void main (String[] args) { String usage = "Cache get <dir> \nCache get <dir> <url>\\nCache getobj <dir> \\nCache getobj <dir> <url>\nCache getobjprop <dir> <method> \nCache getobjprop <dir> <method> <url>\nCache list <dir>\nCache translate <src dir> <dest dir> <src file depth>"; if (args.length != 2 && args.length != 3 && args.length != 4) { System.out.println(usage); System.exit(1); } if ("get".equals(args[0])) { FileCache<byte[]> cache = new FileCache<byte[]>(args[1]); if (args.length == 2) { Iterator<String> it = cache.iterator(); while (it.hasNext()) { String key = it.next(); byte[] data = cache.getItem(key); System.out.println("-------"); System.out.println(key); System.out.println(); System.out.println(new String(data)); System.out.println(); } System.out.println("-------"); } else { byte[] data = cache.getItem(args[2]); if (null == data) { System.out.println("Page not found in cache"); } else { System.out.println(); System.out.println(args[2]); System.out.println(); System.out.println(new String(data)); System.out.println(); } } } else if ("getobj".equals(args[0])) { FileCache<Object> cache = new FileCache<Object>(args[1]); if (args.length == 2) { Iterator<String> it = cache.iterator(); while (it.hasNext()) { String key = it.next(); Object data = cache.getItem(key); System.out.println("-------"); System.out.println(key); System.out.println(); System.out.println(String.valueOf(data)); System.out.println(); } System.out.println("-------"); } else { Object data = cache.getItem(args[2]); if (null == data) { System.out.println("Page not found in cache"); } else { System.out.println(); System.out.println(args[2]); System.out.println(); System.out.println(String.valueOf(data)); System.out.println(); } } } else if ("getobjprop".equals(args[0])) { FileCache<Object> cache = new FileCache<Object>(args[1]); if (args.length == 3) { Iterator<String> it = cache.iterator(); while (it.hasNext()) { String key = it.next(); Object data = getProperty(cache.getItem(key), args[2]); System.out.println("-------"); System.out.println(key); System.out.println(); System.out.println(String.valueOf(data)); System.out.println(); } System.out.println("-------"); } else { Object data = getProperty(cache.getItem(args[3]), args[2]); if (null == data) { System.out.println("Page not found in cache"); } else { System.out.println(); System.out.println(args[3]); System.out.println(); System.out.println(String.valueOf(data)); System.out.println(); } } } else if ("list".equals(args[0])) { FileCache<Object> cache = new FileCache<Object>(args[1]); Iterator<String> en = cache.iterator(); while (en.hasNext()) { System.out.println(en.next()); } } else if ("purge".equals(args[0])) { FileCache<Object> cache = new FileCache<Object>(args[1]); Iterator<String> en = cache.iterator(); while (en.hasNext()) { Object value = en.next(); if (null == value) { System.out.println("Removing faulty cache entry"); en.remove(); } } System.out.println("Done."); } else if ("translate".equals(args[0])) { FileCache<byte[]> cacheSrc = new FileCache<byte[]>(args[1], Integer.parseInt(args[3])); FileCache<byte[]> cacheDest = new FileCache<byte[]>(args[2]); for (String key: cacheSrc) { System.out.println("translating " + key); cacheDest.addItem(key, cacheSrc.getItem(key)); } System.out.println("Done."); } }
public static void main (String[] args) { String usage = "Cache get <dir> \nCache get <dir> <url>\nCache getobj <dir> \nCache getobj <dir> <url>\nCache getobjprop <dir> <method> \nCache getobjprop <dir> <method> <url>\nCache list <dir>\nCache translate <src dir> <dest dir> <src file depth>"; if (args.length != 2 && args.length != 3 && args.length != 4) { System.out.println(usage); System.exit(1); } if ("get".equals(args[0])) { FileCache<byte[]> cache = new FileCache<byte[]>(args[1]); if (args.length == 2) { Iterator<String> it = cache.iterator(); while (it.hasNext()) { String key = it.next(); byte[] data = cache.getItem(key); System.out.println("-------"); System.out.println(key); System.out.println(); System.out.println(new String(data)); System.out.println(); } System.out.println("-------"); } else { byte[] data = cache.getItem(args[2]); if (null == data) { System.out.println("Page not found in cache"); } else { System.out.println(); System.out.println(args[2]); System.out.println(); System.out.println(new String(data)); System.out.println(); } } } else if ("getobj".equals(args[0])) { FileCache<Object> cache = new FileCache<Object>(args[1]); if (args.length == 2) { Iterator<String> it = cache.iterator(); while (it.hasNext()) { String key = it.next(); Object data = cache.getItem(key); System.out.println("-------"); System.out.println(key); System.out.println(); System.out.println(String.valueOf(data)); System.out.println(); } System.out.println("-------"); } else { Object data = cache.getItem(args[2]); if (null == data) { System.out.println("Page not found in cache"); } else { System.out.println(); System.out.println(args[2]); System.out.println(); System.out.println(String.valueOf(data)); System.out.println(); } } } else if ("getobjprop".equals(args[0])) { FileCache<Object> cache = new FileCache<Object>(args[1]); if (args.length == 3) { Iterator<String> it = cache.iterator(); while (it.hasNext()) { String key = it.next(); Object data = getProperty(cache.getItem(key), args[2]); System.out.println("-------"); System.out.println(key); System.out.println(); System.out.println(String.valueOf(data)); System.out.println(); } System.out.println("-------"); } else { Object data = getProperty(cache.getItem(args[3]), args[2]); if (null == data) { System.out.println("Page not found in cache"); } else { System.out.println(); System.out.println(args[3]); System.out.println(); System.out.println(String.valueOf(data)); System.out.println(); } } } else if ("list".equals(args[0])) { FileCache<Object> cache = new FileCache<Object>(args[1]); Iterator<String> en = cache.iterator(); while (en.hasNext()) { System.out.println(en.next()); } } else if ("purge".equals(args[0])) { FileCache<Object> cache = new FileCache<Object>(args[1]); Iterator<String> en = cache.iterator(); while (en.hasNext()) { Object value = en.next(); if (null == value) { System.out.println("Removing faulty cache entry"); en.remove(); } } System.out.println("Done."); } else if ("translate".equals(args[0])) { FileCache<byte[]> cacheSrc = new FileCache<byte[]>(args[1], Integer.parseInt(args[3])); FileCache<byte[]> cacheDest = new FileCache<byte[]>(args[2]); for (String key: cacheSrc) { System.out.println("translating " + key); cacheDest.addItem(key, cacheSrc.getItem(key)); } System.out.println("Done."); } }
diff --git a/src/java/org/infoglue/deliver/taglib/common/ImportTag.java b/src/java/org/infoglue/deliver/taglib/common/ImportTag.java index f77a63463..45ecc8417 100755 --- a/src/java/org/infoglue/deliver/taglib/common/ImportTag.java +++ b/src/java/org/infoglue/deliver/taglib/common/ImportTag.java @@ -1,108 +1,108 @@ /* =============================================================================== * * Part of the InfoGlue Content Management Platform (www.infoglue.org) * * =============================================================================== * * Copyright (C) * * 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. See the file LICENSE.html for more information. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY, including 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 org.infoglue.deliver.taglib.common; import java.util.HashMap; import java.util.Map; import javax.servlet.jsp.JspException; import org.apache.log4j.Logger; import org.infoglue.deliver.taglib.TemplateControllerTag; import org.infoglue.deliver.util.HttpHelper; public class ImportTag extends TemplateControllerTag { private static final long serialVersionUID = 4050206323348354355L; private final static Logger logger = Logger.getLogger(ImportTag.class.getName()); private String url; private String charEncoding; private Map requestParameters = new HashMap(); private Integer timeout = new Integer(30000); private HttpHelper helper = new HttpHelper(); public ImportTag() { super(); } /** * Initializes the parameters to make it accessible for the children tags (if any). * * @return indication of whether to evaluate the body or not. * @throws JspException if an error occurred while processing this tag. */ public int doStartTag() throws JspException { return EVAL_BODY_INCLUDE; } /** * Generates the url and either sets the result attribute or writes the url * to the output stream. * * @return indication of whether to continue evaluating the JSP page. * @throws JspException if an error occurred while processing this tag. */ public int doEndTag() throws JspException { try { - String result = helper.getUrlContent(url, requestParameters, charEncoding, timeout); + String result = helper.getUrlContent(url, requestParameters, charEncoding, timeout.intValue()); produceResult(result); } catch (Exception e) { logger.error("An error occurred when we tried during (" + timeout + " ms) to import the url:" + this.url + ":" + e.getMessage()); produceResult(""); } return EVAL_PAGE; } public void setUrl(String url) throws JspException { this.url = evaluateString("importTag", "url", url); } public void setCharEncoding(String charEncoding) throws JspException { this.charEncoding = evaluateString("importTag", "charEncoding", charEncoding); } public void setTimeout(String timeout) throws JspException { this.timeout = evaluateInteger("importTag", "timeout", timeout); } protected final void addParameter(final String name, final String value) { requestParameters.put(name, value); } }
true
true
public int doEndTag() throws JspException { try { String result = helper.getUrlContent(url, requestParameters, charEncoding, timeout); produceResult(result); } catch (Exception e) { logger.error("An error occurred when we tried during (" + timeout + " ms) to import the url:" + this.url + ":" + e.getMessage()); produceResult(""); } return EVAL_PAGE; }
public int doEndTag() throws JspException { try { String result = helper.getUrlContent(url, requestParameters, charEncoding, timeout.intValue()); produceResult(result); } catch (Exception e) { logger.error("An error occurred when we tried during (" + timeout + " ms) to import the url:" + this.url + ":" + e.getMessage()); produceResult(""); } return EVAL_PAGE; }
diff --git a/undertow/src/main/java/hello/DbSqlHandler.java b/undertow/src/main/java/hello/DbSqlHandler.java index 7aff347ee..3e3775969 100644 --- a/undertow/src/main/java/hello/DbSqlHandler.java +++ b/undertow/src/main/java/hello/DbSqlHandler.java @@ -1,63 +1,63 @@ package hello; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.net.MediaType; import io.undertow.server.HttpHandler; import io.undertow.server.HttpServerExchange; import io.undertow.util.Headers; import javax.sql.DataSource; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.Objects; import static hello.HelloWebServer.JSON_UTF8; /** * Handles the single- and multiple-query database tests using a SQL database. */ final class DbSqlHandler implements HttpHandler { private final ObjectMapper objectMapper; private final DataSource database; DbSqlHandler(ObjectMapper objectMapper, DataSource database) { this.objectMapper = Objects.requireNonNull(objectMapper); this.database = Objects.requireNonNull(database); } @Override public void handleRequest(HttpServerExchange exchange) throws Exception { if (exchange.isInIoThread()) { exchange.dispatch(this); return; } int queries = Helper.getQueries(exchange); World[] worlds = new World[queries]; try (Connection connection = database.getConnection(); PreparedStatement statement = connection.prepareStatement( "SELECT * FROM World WHERE id = ?", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)) { for (int i = 0; i < queries; i++) { statement.setInt(1, Helper.randomWorld()); try (ResultSet resultSet = statement.executeQuery()) { resultSet.next(); worlds[i] = new World( resultSet.getInt("id"), resultSet.getInt("randomNumber")); } } } exchange.getResponseHeaders().put( Headers.CONTENT_TYPE, JSON_UTF8); if (queries == 1) { - exchange.getResponseSender().send(objectMapper.writeValueAsString(world[0])); + exchange.getResponseSender().send(objectMapper.writeValueAsString(worlds[0])); } else { exchange.getResponseSender().send(objectMapper.writeValueAsString(worlds)); } } }
true
true
public void handleRequest(HttpServerExchange exchange) throws Exception { if (exchange.isInIoThread()) { exchange.dispatch(this); return; } int queries = Helper.getQueries(exchange); World[] worlds = new World[queries]; try (Connection connection = database.getConnection(); PreparedStatement statement = connection.prepareStatement( "SELECT * FROM World WHERE id = ?", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)) { for (int i = 0; i < queries; i++) { statement.setInt(1, Helper.randomWorld()); try (ResultSet resultSet = statement.executeQuery()) { resultSet.next(); worlds[i] = new World( resultSet.getInt("id"), resultSet.getInt("randomNumber")); } } } exchange.getResponseHeaders().put( Headers.CONTENT_TYPE, JSON_UTF8); if (queries == 1) { exchange.getResponseSender().send(objectMapper.writeValueAsString(world[0])); } else { exchange.getResponseSender().send(objectMapper.writeValueAsString(worlds)); } }
public void handleRequest(HttpServerExchange exchange) throws Exception { if (exchange.isInIoThread()) { exchange.dispatch(this); return; } int queries = Helper.getQueries(exchange); World[] worlds = new World[queries]; try (Connection connection = database.getConnection(); PreparedStatement statement = connection.prepareStatement( "SELECT * FROM World WHERE id = ?", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)) { for (int i = 0; i < queries; i++) { statement.setInt(1, Helper.randomWorld()); try (ResultSet resultSet = statement.executeQuery()) { resultSet.next(); worlds[i] = new World( resultSet.getInt("id"), resultSet.getInt("randomNumber")); } } } exchange.getResponseHeaders().put( Headers.CONTENT_TYPE, JSON_UTF8); if (queries == 1) { exchange.getResponseSender().send(objectMapper.writeValueAsString(worlds[0])); } else { exchange.getResponseSender().send(objectMapper.writeValueAsString(worlds)); } }
diff --git a/sim/src/main/java/devhood/im/sim/config/SimConfigurationBean.java b/sim/src/main/java/devhood/im/sim/config/SimConfigurationBean.java index a89caa9..598a8ac 100644 --- a/sim/src/main/java/devhood/im/sim/config/SimConfigurationBean.java +++ b/sim/src/main/java/devhood/im/sim/config/SimConfigurationBean.java @@ -1,51 +1,51 @@ package devhood.im.sim.config; import javax.inject.Inject; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import devhood.im.sim.dao.JtdsUserDao; import devhood.im.sim.dao.SingleFilePerUserDao; import devhood.im.sim.dao.SqliteUserDao; import devhood.im.sim.dao.interfaces.UserDao; /** * Spring Configuration Klasse. * * @author flo * */ @Configuration public class SimConfigurationBean { @Inject private SimConfiguration simConfiguration; @Inject private JtdsUserDao jtdsUserDao; @Inject private SingleFilePerUserDao singleFilePerUserDao; @Inject private SqliteUserDao sqliteUserDao; @Bean(name="userDao") public UserDao getUserDao() { UserDao userDao = jtdsUserDao; if ( simConfiguration.getUserDaoToUse() != null) { if ( "single".equals(simConfiguration.getUserDaoToUse()) ) { userDao = singleFilePerUserDao; - }else if ( "single".equals(simConfiguration.getUserDaoToUse()) ) { - userDao = singleFilePerUserDao; }else if ( "sqlite".equals(simConfiguration.getUserDaoToUse()) ) { userDao = sqliteUserDao; + }else if ( "jtds".equals(simConfiguration.getUserDaoToUse()) ) { + userDao = jtdsUserDao; } } return userDao; } }
false
true
public UserDao getUserDao() { UserDao userDao = jtdsUserDao; if ( simConfiguration.getUserDaoToUse() != null) { if ( "single".equals(simConfiguration.getUserDaoToUse()) ) { userDao = singleFilePerUserDao; }else if ( "single".equals(simConfiguration.getUserDaoToUse()) ) { userDao = singleFilePerUserDao; }else if ( "sqlite".equals(simConfiguration.getUserDaoToUse()) ) { userDao = sqliteUserDao; } } return userDao; }
public UserDao getUserDao() { UserDao userDao = jtdsUserDao; if ( simConfiguration.getUserDaoToUse() != null) { if ( "single".equals(simConfiguration.getUserDaoToUse()) ) { userDao = singleFilePerUserDao; }else if ( "sqlite".equals(simConfiguration.getUserDaoToUse()) ) { userDao = sqliteUserDao; }else if ( "jtds".equals(simConfiguration.getUserDaoToUse()) ) { userDao = jtdsUserDao; } } return userDao; }
diff --git a/src/gsingh/learnkirtan/Parser.java b/src/gsingh/learnkirtan/Parser.java index d00f8f1..7110041 100755 --- a/src/gsingh/learnkirtan/Parser.java +++ b/src/gsingh/learnkirtan/Parser.java @@ -1,314 +1,315 @@ package gsingh.learnkirtan; import gsingh.learnkirtan.keys.Key; import java.util.Scanner; import javax.swing.JOptionPane; public class Parser { /** * The default length each note is played */ private static final int gap = 500; private static final String PATTERN = "[A-Z.'\\-#]+"; private static boolean stop = false; private static boolean pause = false; private static boolean finished = false; private static boolean repeat = false; private static Key[] keys = Main.keys; private static int key = 0; private static int holdCount; private static String note; private static String nextNote; private static Scanner scanner = null; /** * Plays the shabad on the keyboard * * @param shabad * - The shabad to play * @param tempo * - The speed multiplier */ public static void parseAndPlay(String shabad, String start, String end, double tempo) { start = start.toUpperCase(); end = end.toUpperCase(); shabad = shabad.toUpperCase(); System.out.println(shabad); if (!validateShabad(shabad, start, end)) { JOptionPane .showMessageDialog( null, "Error: You specified that playback should start/stop at a label, " + "but that label could not be found. Make sure there is a " + "'#' before the label.", "Error", JOptionPane.ERROR_MESSAGE); return; } reset(shabad, start); while (!stop) { // Pause the thread if necessary if (isPaused()) pause(); // If the end label is found, finish. If another label is found, // skip it. if (note != null) { while (note.charAt(0) == '#') { if (!end.equals("")) { if (note.equals("#" + end)) finished = true; } note = nextNote; nextNote = getNextNote(); if (note == null) { finished = true; break; } } } else finished = true; // If we have reached the end of the shabad or specified lines, // check if we should repeat. Otherwise, break. if (finished) { if (repeat) { reset(shabad, start); finished = false; + continue; } else { break; } } // Check if we've reached the end of the shabad or specified lines if (nextNote == null) finished = true; // Determine the length of the prefix int count = 0; if (note.length() > 1) { for (int i = 0; i < 3; i++) { if (note.substring(i, i + 1).matches("[A-Z\\-]")) break; count++; } } // Break the input into a prefix, a suffix and a note String prefix = note.substring(0, count); String suffix = ""; note = note.substring(count); int index = note.indexOf("."); if (index == -1) index = note.indexOf("'"); if (index != -1) { suffix = note.substring(index); note = note.substring(0, index); } System.out.println(prefix + note + suffix); // Set the key number of the note to be played if (note.equals("SA")) { key = 10; } else if (note.equals("RE")) { key = 12; } else if (note.equals("GA")) { key = 14; } else if (note.equals("MA")) { key = 15; } else if (note.equals("PA")) { key = 17; } else if (note.equals("DHA")) { key = 19; } else if (note.equals("NI")) { key = 21; } else { System.out.println("Invalid note."); JOptionPane.showMessageDialog(null, "Error: Invalid note.", "Error", JOptionPane.ERROR_MESSAGE); break; } // Apply the modifiers in the prefix and suffix to calculate the // actual key number // TODO: Check if notes have valid modifiers if (prefix.contains("'")) { key--; } if (prefix.contains(".")) { key -= 12; } if (suffix.contains("'")) { key++; } if (suffix.contains(".")) { key += 12; } System.out.println(pause); if (key > 0 && key < 48) { keys[key].playOnce((int) (holdCount * gap / tempo)); note = nextNote; nextNote = getNextNote(); // If note is equal to a dash, we've reached the end of the file if (note != null) if (note.equals("-")) finished = true; } else { System.out.println("Invalid note."); JOptionPane.showMessageDialog(null, "Error: Invalid note.", "Error", JOptionPane.ERROR_MESSAGE); break; } } stop = false; finished = false; } /** * Gets the next note if one exists * * @param holdCount * - this is incremented each time a dash is found * @return the next note (after skipping any dashes) if it exists. If there * is no next note, return null */ private static String getNextNote() { String next = null; holdCount = 1; while (scanner.hasNext(PATTERN)) { next = scanner.next(PATTERN); if (next.equals("-")) holdCount++; else break; } return next; } /** * Sets the state of the scanner so we are starting from the beginning * * @param shabad * - the shabad to reset * @param start * - the point in the shabad to reset too. */ private static void reset(String shabad, String start) { scanner = new Scanner(shabad); note = getFirstNote(start); nextNote = getNextNote(); } /** * Gets the first note to parse and sets the scanner to that position. * * @param scanner * - the scanner reading the shabad * @return the first note of the shabad */ private static String getFirstNote(String start) { String note; if (!start.equals("")) { note = scanner.next(PATTERN); while (!note.equals("#" + start)) { System.out.println(note); note = scanner.next(PATTERN); } } note = scanner.next("[A-Z.'#]+"); return note; } /** * Checks whether the shabad input is valid. Checks whether labels are * present and in valid format * * @return true if input is valid. False otherwise. */ private static boolean validateShabad(String shabad, String start, String end) { if (!start.equals("")) { if (!shabad.contains("#" + start)) return false; } if (!end.equals("")) { if (!shabad.contains("#" + end)) return false; } return true; } /** * Sets pause to false and stop to true */ public static void stop() { stop = true; pause = false; } /** * Sets pause to true */ public static void setPause() { pause = true; } /** * If pause is true, the thread playing the shabad will sleep */ public static void pause() { while (pause) { try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } /** * Returns true if the playback is paused, false otherwise */ public static boolean isPaused() { return pause; } /** * Sets pause to false, so that playback resumes. This is note used to play * the shabad, only to unpause. */ public static void play() { pause = false; } /** * Sets the repeat flag * * @param bool * - {@code repeat} is set to this value */ public static void setRepeat(boolean bool) { repeat = bool; } }
true
true
public static void parseAndPlay(String shabad, String start, String end, double tempo) { start = start.toUpperCase(); end = end.toUpperCase(); shabad = shabad.toUpperCase(); System.out.println(shabad); if (!validateShabad(shabad, start, end)) { JOptionPane .showMessageDialog( null, "Error: You specified that playback should start/stop at a label, " + "but that label could not be found. Make sure there is a " + "'#' before the label.", "Error", JOptionPane.ERROR_MESSAGE); return; } reset(shabad, start); while (!stop) { // Pause the thread if necessary if (isPaused()) pause(); // If the end label is found, finish. If another label is found, // skip it. if (note != null) { while (note.charAt(0) == '#') { if (!end.equals("")) { if (note.equals("#" + end)) finished = true; } note = nextNote; nextNote = getNextNote(); if (note == null) { finished = true; break; } } } else finished = true; // If we have reached the end of the shabad or specified lines, // check if we should repeat. Otherwise, break. if (finished) { if (repeat) { reset(shabad, start); finished = false; } else { break; } } // Check if we've reached the end of the shabad or specified lines if (nextNote == null) finished = true; // Determine the length of the prefix int count = 0; if (note.length() > 1) { for (int i = 0; i < 3; i++) { if (note.substring(i, i + 1).matches("[A-Z\\-]")) break; count++; } } // Break the input into a prefix, a suffix and a note String prefix = note.substring(0, count); String suffix = ""; note = note.substring(count); int index = note.indexOf("."); if (index == -1) index = note.indexOf("'"); if (index != -1) { suffix = note.substring(index); note = note.substring(0, index); } System.out.println(prefix + note + suffix); // Set the key number of the note to be played if (note.equals("SA")) { key = 10; } else if (note.equals("RE")) { key = 12; } else if (note.equals("GA")) { key = 14; } else if (note.equals("MA")) { key = 15; } else if (note.equals("PA")) { key = 17; } else if (note.equals("DHA")) { key = 19; } else if (note.equals("NI")) { key = 21; } else { System.out.println("Invalid note."); JOptionPane.showMessageDialog(null, "Error: Invalid note.", "Error", JOptionPane.ERROR_MESSAGE); break; } // Apply the modifiers in the prefix and suffix to calculate the // actual key number // TODO: Check if notes have valid modifiers if (prefix.contains("'")) { key--; } if (prefix.contains(".")) { key -= 12; } if (suffix.contains("'")) { key++; } if (suffix.contains(".")) { key += 12; } System.out.println(pause); if (key > 0 && key < 48) { keys[key].playOnce((int) (holdCount * gap / tempo)); note = nextNote; nextNote = getNextNote(); // If note is equal to a dash, we've reached the end of the file if (note != null) if (note.equals("-")) finished = true; } else { System.out.println("Invalid note."); JOptionPane.showMessageDialog(null, "Error: Invalid note.", "Error", JOptionPane.ERROR_MESSAGE); break; } } stop = false; finished = false; }
public static void parseAndPlay(String shabad, String start, String end, double tempo) { start = start.toUpperCase(); end = end.toUpperCase(); shabad = shabad.toUpperCase(); System.out.println(shabad); if (!validateShabad(shabad, start, end)) { JOptionPane .showMessageDialog( null, "Error: You specified that playback should start/stop at a label, " + "but that label could not be found. Make sure there is a " + "'#' before the label.", "Error", JOptionPane.ERROR_MESSAGE); return; } reset(shabad, start); while (!stop) { // Pause the thread if necessary if (isPaused()) pause(); // If the end label is found, finish. If another label is found, // skip it. if (note != null) { while (note.charAt(0) == '#') { if (!end.equals("")) { if (note.equals("#" + end)) finished = true; } note = nextNote; nextNote = getNextNote(); if (note == null) { finished = true; break; } } } else finished = true; // If we have reached the end of the shabad or specified lines, // check if we should repeat. Otherwise, break. if (finished) { if (repeat) { reset(shabad, start); finished = false; continue; } else { break; } } // Check if we've reached the end of the shabad or specified lines if (nextNote == null) finished = true; // Determine the length of the prefix int count = 0; if (note.length() > 1) { for (int i = 0; i < 3; i++) { if (note.substring(i, i + 1).matches("[A-Z\\-]")) break; count++; } } // Break the input into a prefix, a suffix and a note String prefix = note.substring(0, count); String suffix = ""; note = note.substring(count); int index = note.indexOf("."); if (index == -1) index = note.indexOf("'"); if (index != -1) { suffix = note.substring(index); note = note.substring(0, index); } System.out.println(prefix + note + suffix); // Set the key number of the note to be played if (note.equals("SA")) { key = 10; } else if (note.equals("RE")) { key = 12; } else if (note.equals("GA")) { key = 14; } else if (note.equals("MA")) { key = 15; } else if (note.equals("PA")) { key = 17; } else if (note.equals("DHA")) { key = 19; } else if (note.equals("NI")) { key = 21; } else { System.out.println("Invalid note."); JOptionPane.showMessageDialog(null, "Error: Invalid note.", "Error", JOptionPane.ERROR_MESSAGE); break; } // Apply the modifiers in the prefix and suffix to calculate the // actual key number // TODO: Check if notes have valid modifiers if (prefix.contains("'")) { key--; } if (prefix.contains(".")) { key -= 12; } if (suffix.contains("'")) { key++; } if (suffix.contains(".")) { key += 12; } System.out.println(pause); if (key > 0 && key < 48) { keys[key].playOnce((int) (holdCount * gap / tempo)); note = nextNote; nextNote = getNextNote(); // If note is equal to a dash, we've reached the end of the file if (note != null) if (note.equals("-")) finished = true; } else { System.out.println("Invalid note."); JOptionPane.showMessageDialog(null, "Error: Invalid note.", "Error", JOptionPane.ERROR_MESSAGE); break; } } stop = false; finished = false; }
diff --git a/org/xbill/DNS/Tokenizer.java b/org/xbill/DNS/Tokenizer.java index e82d2f8..00a515b 100644 --- a/org/xbill/DNS/Tokenizer.java +++ b/org/xbill/DNS/Tokenizer.java @@ -1,505 +1,502 @@ // Copyright (c) 2003 Brian Wellington ([email protected]) // // Copyright (C) 2003 Nominum, Inc. // // Permission to use, copy, modify, and distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR ANY // SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT // OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. // package org.xbill.DNS; import java.io.*; import java.util.*; /** * Tokenizer is used to parse DNS records and zones from text format, * * @author Brian Wellington * @author Bob Halley */ public class Tokenizer { private static String delim = " \t\n;()\""; private static String quotes = "\""; /** End of file */ public static final int EOF = 0; /** End of line */ public static final int EOL = 1; /** Whitespace; only returned when wantWhitespace is set */ public static final int WHITESPACE = 2; /** An identifier (unquoted string) */ public static final int IDENTIFIER = 3; /** A quoted string */ public static final int QUOTED_STRING = 4; /** A comment; only returned when wantComment is set */ public static final int COMMENT = 5; private InputStream is; private int ungottenChar; private boolean ungottenToken; private int multiline; private boolean quoting; private String delimiters; private Token current; private StringBuffer sb; public static class Token { /** The type of token. */ public int type; /** The value of the token, or null for tokens without values. */ public String value; private Token() { type = -1; value = null; } private Token set(int type, StringBuffer value) { if (type < 0) throw new IllegalArgumentException(); this.type = type; this.value = value == null ? null : value.toString(); return this; } /** * Converts the token to a string containing a representation useful * for debugging. */ public String toString() { switch (type) { case EOF: return "<eof>"; case EOL: return "<eol>"; case WHITESPACE: return "<whitespace>"; case IDENTIFIER: return "<identifier: " + value + ">"; case QUOTED_STRING: return "<quoted_string: " + value + ">"; case COMMENT: return "<comment: " + value + ">"; default: return "<unknown>"; } } /** Indicates whether this token contains a string. */ public boolean isString() { return (type == IDENTIFIER || type == QUOTED_STRING); } /** Indicates whether this token contains an EOL or EOF. */ public boolean isEOL() { return (type == EOL || type == EOF); } } /** * Creates a Tokenizer from an arbitrary input stream. * @param is The InputStream to tokenize. */ public Tokenizer(InputStream is) { if (is instanceof BufferedInputStream) this.is = is; else this.is = new BufferedInputStream(is); ungottenChar = -1; ungottenToken = false; multiline = 0; quoting = false; delimiters = delim; current = new Token(); sb = new StringBuffer(); } /** * Creates a Tokenizer from a string. * @param s The String to tokenize. */ public Tokenizer(String s) { this(new ByteArrayInputStream(s.getBytes())); } /** * Creates a Tokenizer from a file. * @param f The File to tokenize. */ public Tokenizer(File f) throws FileNotFoundException { this(new FileInputStream(f)); } private int getChar() throws IOException { int c; if (ungottenChar != -1) { c = ungottenChar; ungottenChar = -1; } else { c = is.read(); if (c == '\r') c = '\n'; } return c; } private void ungetChar(int c) { if (ungottenChar != -1) throw new IllegalStateException ("Cannot unget multiple characters"); ungottenChar = c; } private int skipWhitespace() throws IOException { int skipped = 0; while (true) { int c = getChar(); if (c != ' ' && c != '\t') { if (!(c == '\n' && multiline > 0)) { ungetChar(c); return skipped; } } skipped++; } } private void fail(String s) throws TextParseException { throw new TextParseException(s); } private void checkUnbalancedParens() throws TextParseException { if (multiline > 0) fail("unbalanced parentheses"); } /** * Gets the next token from a tokenizer. * @param wantWhitespace If true, leading whitespace will be returned as a * token. * @param wantComment If true, comments are returned as tokens. * @return The next token in the stream. * @throws TextParseException The input was invalid. * @throws IOException An I/O error occurred. */ public Token get(boolean wantWhitespace, boolean wantComment) throws IOException { int type; int c; if (ungottenToken) { ungottenToken = false; if (current.type == WHITESPACE) { if (wantWhitespace) return current; } else if (current.type == COMMENT) { if (wantComment) return current; } else return current; } int skipped = skipWhitespace(); if (skipped > 0 && wantWhitespace) return current.set(WHITESPACE, null); type = IDENTIFIER; sb.setLength(0); while (true) { c = getChar(); if (c == -1 || delimiters.indexOf(c) != -1) { if (c == -1) { if (quoting) - throw new EOFException(); + fail("newline in quoted string"); else if (sb.length() == 0) return current.set(EOF, null); else return current.set(type, sb); } if (sb.length() == 0) { if (c == '(') { multiline++; skipWhitespace(); continue; } else if (c == ')') { if (multiline <= 0) fail("invalid close " + "parenthesis"); multiline--; skipWhitespace(); continue; } else if (c == '"') { if (!quoting) { quoting = true; delimiters = quotes; type = QUOTED_STRING; } else { quoting = false; delimiters = delim; skipWhitespace(); } continue; } else if (c == '\n') { return current.set(EOL, null); } else if (c == ';') { while (true) { c = getChar(); if (c == '\n' || c == -1) break; sb.append((char)c); } if (wantComment) { ungetChar(c); return current.set(COMMENT, sb); } else if (c == -1) { checkUnbalancedParens(); return current.set(EOF, null); } else if (multiline > 0) { skipWhitespace(); sb.setLength(0); continue; } else return current.set(EOL, null); } else throw new IllegalStateException(); } else ungetChar(c); break; - } else if (quoting) { - if (c == '\\') { - c = getChar(); - if (c == -1) - throw new EOFException(); - } else if (c == '\n') - fail("newline in quoted string"); + } else if (c == '\\') { + c = getChar(); + if (c == -1) + fail("unterminated escape sequence"); } sb.append((char)c); } if (sb.length() == 0) { checkUnbalancedParens(); return current.set(EOF, null); } return current.set(type, sb); } /** * Gets the next token from a tokenizer, ignoring whitespace and comments. * @return The next token in the stream. * @throws TextParseException The input was invalid. * @throws IOException An I/O error occurred. */ public Token get() throws IOException { return get(false, false); } /** * Returns a token to the stream, so that it will be returned by the next call * to get(). * @throws IllegalStateException There are already ungotten tokens. */ public void unget() { if (ungottenToken) throw new IllegalStateException ("Cannot unget multiple tokens"); ungottenToken = true; } /** * Gets the next token from a tokenizer and converts it to a string. * @return The next token in the stream, as a string. * @throws TextParseException The input was invalid or not a string. * @throws IOException An I/O error occurred. */ public String getString() throws IOException { Token next = get(); if (!next.isString()) { fail("expected a string"); } return next.value; } /** * Gets the next token from a tokenizer, ensures it is an unquoted string, * and converts it to a string. * @return The next token in the stream, as a string. * @throws TextParseException The input was invalid or not an unquoted string. * @throws IOException An I/O error occurred. */ public String getIdentifier() throws IOException { Token next = get(); if (next.type != IDENTIFIER) { fail("expected an identifier"); } return next.value; } /** * Gets the next token from a tokenizer and converts it to a long. * @return The next token in the stream, as a long. * @throws TextParseException The input was invalid or not a long. * @throws IOException An I/O error occurred. */ public long getLong() throws IOException { String next = getIdentifier(); if (!Character.isDigit(next.charAt(0))) fail("expecting an integer"); try { return Long.parseLong(next); } catch (NumberFormatException e) { fail("expecting an integer"); return 0; } } /** * Gets the next token from a tokenizer and converts it to an unsigned 32 bit * integer. * @return The next token in the stream, as an unsigned 32 bit integer. * @throws TextParseException The input was invalid or not an unsigned 32 * bit integer. * @throws IOException An I/O error occurred. */ public long getUInt32() throws IOException { long l = getLong(); if (l < 0 || l > 0xFFFFFFFFL) fail("expecting an 32 bit unsigned integer"); return l; } /** * Gets the next token from a tokenizer and converts it to an unsigned 16 bit * integer. * @return The next token in the stream, as an unsigned 16 bit integer. * @throws TextParseException The input was invalid or not an unsigned 16 * bit integer. * @throws IOException An I/O error occurred. */ public int getUInt16() throws IOException { long l = getLong(); if (l < 0 || l > 0xFFFFL) fail("expecting an 16 bit unsigned integer"); return (int) l; } /** * Gets the next token from a tokenizer and converts it to an unsigned 8 bit * integer. * @return The next token in the stream, as an unsigned 8 bit integer. * @throws TextParseException The input was invalid or not an unsigned 8 * bit integer. * @throws IOException An I/O error occurred. */ public int getUInt8() throws IOException { long l = getLong(); if (l < 0 || l > 0xFFL) fail("expecting an 8 bit unsigned integer"); return (int) l; } /** * Gets the next token from a tokenizer and converts it to a double. * @return The next token in the stream, as a double. * @throws TextParseException The input was invalid or not a double. * @throws IOException An I/O error occurred. */ public double getDouble() throws IOException { String next = getIdentifier(); if (!Character.isDigit(next.charAt(0))) fail("expecting an integer"); try { return Double.parseDouble(next); } catch (NumberFormatException e) { fail("expecting an floating point value"); return 0; } } /** * Gets the next token from a tokenizer and converts it to an integer * representing a TTL (which may be encoded in the BIND TTL format). * @return The next token in the stream, as a integer. * @throws TextParseException The input was invalid or not a valid TTL. * @throws IOException An I/O error occurred. * @see TTL */ public int getTTL() throws IOException { String next = getIdentifier(); try { return TTL.parseTTL(next); } catch (NumberFormatException e) { fail("invalid TTL: " + next); return 0; } } /** * Gets the next token from a tokenizer and converts it to a name. * @param origin The origin to append to relative names. * @return The next token in the stream, as a name. * @throws TextParseException The input was invalid or not a valid name. * @throws IOException An I/O error occurred. * @throws RelativeNameException The parsed name was relative, even with the * origin. * @see Name */ public Name getName(Name origin) throws IOException { Name name = Name.fromString(getIdentifier(), origin); if (!name.isAbsolute()) throw new RelativeNameException(name); return name; } /** * Gets the next token from a tokenizer, which must be an EOL or EOF. * @throws TextParseException The input was invalid or not an EOL or EOF token. * @throws IOException An I/O error occurred. */ public void getEOL() throws IOException { Token next = get(); if (next.type != EOL && next.type != EOF) { fail("expecting EOL or EOF"); } } }
false
true
public Token get(boolean wantWhitespace, boolean wantComment) throws IOException { int type; int c; if (ungottenToken) { ungottenToken = false; if (current.type == WHITESPACE) { if (wantWhitespace) return current; } else if (current.type == COMMENT) { if (wantComment) return current; } else return current; } int skipped = skipWhitespace(); if (skipped > 0 && wantWhitespace) return current.set(WHITESPACE, null); type = IDENTIFIER; sb.setLength(0); while (true) { c = getChar(); if (c == -1 || delimiters.indexOf(c) != -1) { if (c == -1) { if (quoting) throw new EOFException(); else if (sb.length() == 0) return current.set(EOF, null); else return current.set(type, sb); } if (sb.length() == 0) { if (c == '(') { multiline++; skipWhitespace(); continue; } else if (c == ')') { if (multiline <= 0) fail("invalid close " + "parenthesis"); multiline--; skipWhitespace(); continue; } else if (c == '"') { if (!quoting) { quoting = true; delimiters = quotes; type = QUOTED_STRING; } else { quoting = false; delimiters = delim; skipWhitespace(); } continue; } else if (c == '\n') { return current.set(EOL, null); } else if (c == ';') { while (true) { c = getChar(); if (c == '\n' || c == -1) break; sb.append((char)c); } if (wantComment) { ungetChar(c); return current.set(COMMENT, sb); } else if (c == -1) { checkUnbalancedParens(); return current.set(EOF, null); } else if (multiline > 0) { skipWhitespace(); sb.setLength(0); continue; } else return current.set(EOL, null); } else throw new IllegalStateException(); } else ungetChar(c); break; } else if (quoting) { if (c == '\\') { c = getChar(); if (c == -1) throw new EOFException(); } else if (c == '\n') fail("newline in quoted string"); } sb.append((char)c); } if (sb.length() == 0) { checkUnbalancedParens(); return current.set(EOF, null); } return current.set(type, sb); }
public Token get(boolean wantWhitespace, boolean wantComment) throws IOException { int type; int c; if (ungottenToken) { ungottenToken = false; if (current.type == WHITESPACE) { if (wantWhitespace) return current; } else if (current.type == COMMENT) { if (wantComment) return current; } else return current; } int skipped = skipWhitespace(); if (skipped > 0 && wantWhitespace) return current.set(WHITESPACE, null); type = IDENTIFIER; sb.setLength(0); while (true) { c = getChar(); if (c == -1 || delimiters.indexOf(c) != -1) { if (c == -1) { if (quoting) fail("newline in quoted string"); else if (sb.length() == 0) return current.set(EOF, null); else return current.set(type, sb); } if (sb.length() == 0) { if (c == '(') { multiline++; skipWhitespace(); continue; } else if (c == ')') { if (multiline <= 0) fail("invalid close " + "parenthesis"); multiline--; skipWhitespace(); continue; } else if (c == '"') { if (!quoting) { quoting = true; delimiters = quotes; type = QUOTED_STRING; } else { quoting = false; delimiters = delim; skipWhitespace(); } continue; } else if (c == '\n') { return current.set(EOL, null); } else if (c == ';') { while (true) { c = getChar(); if (c == '\n' || c == -1) break; sb.append((char)c); } if (wantComment) { ungetChar(c); return current.set(COMMENT, sb); } else if (c == -1) { checkUnbalancedParens(); return current.set(EOF, null); } else if (multiline > 0) { skipWhitespace(); sb.setLength(0); continue; } else return current.set(EOL, null); } else throw new IllegalStateException(); } else ungetChar(c); break; } else if (c == '\\') { c = getChar(); if (c == -1) fail("unterminated escape sequence"); } sb.append((char)c); } if (sb.length() == 0) { checkUnbalancedParens(); return current.set(EOF, null); } return current.set(type, sb); }
diff --git a/src/main/java/ai/ilikeplaces/logic/Listeners/widgets/people/PeopleThumb.java b/src/main/java/ai/ilikeplaces/logic/Listeners/widgets/people/PeopleThumb.java index 89d9cbc7..3daaa871 100644 --- a/src/main/java/ai/ilikeplaces/logic/Listeners/widgets/people/PeopleThumb.java +++ b/src/main/java/ai/ilikeplaces/logic/Listeners/widgets/people/PeopleThumb.java @@ -1,60 +1,58 @@ package ai.ilikeplaces.logic.Listeners.widgets.people; import ai.ilikeplaces.logic.Listeners.widgets.UserProperty; import ai.ilikeplaces.rbs.RBGet; import ai.ilikeplaces.servlets.Controller; import ai.ilikeplaces.util.AbstractWidgetListener; import ai.ilikeplaces.util.MarkupTag; import org.itsnat.core.ItsNatServletRequest; import org.itsnat.core.html.ItsNatHTMLDocument; import org.w3c.dom.Element; import org.w3c.dom.html.HTMLDocument; /** * Created by IntelliJ IDEA. * User: Ravindranath Akila * Date: 1/1/12 * Time: 12:22 PM */ public class PeopleThumb extends AbstractWidgetListener<PeopleThumbCriteria> { private static final String PROFILE_PHOTOS = "PROFILE_PHOTOS"; public static enum PeopleThumbIds implements WidgetIds { PeopleThumbImage } /** * @param request__ * @param appendToElement__ */ public PeopleThumb(final ItsNatServletRequest request__, final PeopleThumbCriteria peopleThumbCriteria, final Element appendToElement__) { super(request__, Controller.Page.PeopleThumb, peopleThumbCriteria, appendToElement__); } /** * @param peopleThumbCriteria */ @Override protected void init(final PeopleThumbCriteria peopleThumbCriteria) { final String profilePhotoURLPath = UserProperty.formatProfilePhotoUrl(peopleThumbCriteria.getProfilePhoto()); - final String imageURL = RBGet.globalConfig.getString(PROFILE_PHOTOS) + profilePhotoURLPath; - $$(PeopleThumbIds.PeopleThumbImage).setAttribute(MarkupTag.IMG.src(), imageURL); - $$(PeopleThumbIds.PeopleThumbImage).setAttribute(MarkupTag.IMG.alt(), profilePhotoURLPath); + $$(PeopleThumbIds.PeopleThumbImage).setAttribute(MarkupTag.IMG.title(), profilePhotoURLPath); } /** * Use ItsNatHTMLDocument variable stored in the AbstractListener class * Do not call this method anywhere, just implement it, as it will be * automatically called by the constructor * * @param itsNatHTMLDocument_ * @param hTMLDocument_ */ @Override protected void registerEventListeners(ItsNatHTMLDocument itsNatHTMLDocument_, HTMLDocument hTMLDocument_) { } }
true
true
protected void init(final PeopleThumbCriteria peopleThumbCriteria) { final String profilePhotoURLPath = UserProperty.formatProfilePhotoUrl(peopleThumbCriteria.getProfilePhoto()); final String imageURL = RBGet.globalConfig.getString(PROFILE_PHOTOS) + profilePhotoURLPath; $$(PeopleThumbIds.PeopleThumbImage).setAttribute(MarkupTag.IMG.src(), imageURL); $$(PeopleThumbIds.PeopleThumbImage).setAttribute(MarkupTag.IMG.alt(), profilePhotoURLPath); }
protected void init(final PeopleThumbCriteria peopleThumbCriteria) { final String profilePhotoURLPath = UserProperty.formatProfilePhotoUrl(peopleThumbCriteria.getProfilePhoto()); $$(PeopleThumbIds.PeopleThumbImage).setAttribute(MarkupTag.IMG.title(), profilePhotoURLPath); }
diff --git a/jbi/src/main/java/org/apache/ode/jbi/OdeService.java b/jbi/src/main/java/org/apache/ode/jbi/OdeService.java index 564be685..9f4c8e74 100755 --- a/jbi/src/main/java/org/apache/ode/jbi/OdeService.java +++ b/jbi/src/main/java/org/apache/ode/jbi/OdeService.java @@ -1,317 +1,317 @@ /* * 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.ode.jbi; import javax.jbi.JBIException; import javax.jbi.messaging.ExchangeStatus; import javax.jbi.messaging.Fault; import javax.jbi.messaging.InOnly; import javax.jbi.messaging.InOut; import javax.jbi.messaging.MessagingException; import javax.jbi.messaging.NormalizedMessage; import javax.jbi.servicedesc.ServiceEndpoint; import javax.xml.namespace.QName; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.ode.bpel.iapi.Endpoint; import org.apache.ode.bpel.iapi.InvocationStyle; import org.apache.ode.bpel.iapi.Message; import org.apache.ode.bpel.iapi.MyRoleMessageExchange; import org.apache.ode.bpel.iapi.MessageExchange.Status; import org.apache.ode.jbi.msgmap.Mapper; import org.apache.ode.jbi.msgmap.MessageTranslationException; import org.w3c.dom.Element; /** * Bridge JBI (consumer) to ODE (provider). */ public class OdeService extends ServiceBridge implements JbiMessageExchangeProcessor { private static final Log __log = LogFactory.getLog(OdeService.class); /** JBI-Generated Endpoint */ private ServiceEndpoint _internal; /** External endpoint. */ private ServiceEndpoint _external; private OdeContext _ode; private Element _serviceref; private Endpoint _endpoint; public OdeService(OdeContext odeContext, Endpoint endpoint) throws Exception { _ode = odeContext; _endpoint = endpoint; } /** * Do the JBI endpoint activation. * * @throws JBIException */ public void activate() throws JBIException { if (_serviceref == null) { ServiceEndpoint[] candidates = _ode.getContext().getExternalEndpointsForService(_endpoint.serviceName); if (candidates.length != 0) { _external = candidates[0]; } } _internal = _ode.getContext().activateEndpoint(_endpoint.serviceName, _endpoint.portName); if (__log.isDebugEnabled()) { __log.debug("Activated endpoint " + _endpoint); } // TODO: Is there a race situation here? } /** * Deactivate endpoints in JBI. */ public void deactivate() throws JBIException { _ode.getContext().deactivateEndpoint(_internal); __log.debug("Dectivated endpoint " + _endpoint); } public ServiceEndpoint getInternalServiceEndpoint() { return _internal; } public ServiceEndpoint getExternalServiceEndpoint() { return _external; } public void onJbiMessageExchange(javax.jbi.messaging.MessageExchange jbiMex) throws MessagingException { if (jbiMex.getRole() != javax.jbi.messaging.MessageExchange.Role.PROVIDER) { String errmsg = "Message exchange is not in PROVIDER role as expected: " + jbiMex.getExchangeId(); __log.fatal(errmsg); throw new IllegalArgumentException(errmsg); } if (jbiMex.getStatus() != ExchangeStatus.ACTIVE) { // We can forget about the exchange. return; } if (jbiMex.getOperation() == null) { throw new IllegalArgumentException("Null operation in JBI message exchange id=" + jbiMex.getExchangeId() + " endpoint=" + _endpoint); } if (jbiMex.getPattern().equals(org.apache.ode.jbi.MessageExchangePattern.IN_ONLY)) { boolean success = false; Exception err = null; try { invokeOde(jbiMex, ((InOnly) jbiMex).getInMessage()); success = true; } catch (Exception ex) { __log.error("Error invoking ODE.", ex); err = ex; } finally { if (!success) { jbiMex.setStatus(ExchangeStatus.ERROR); if (err != null && jbiMex.getError() != null) jbiMex.setError(err); } else { if (jbiMex.getStatus() == ExchangeStatus.ACTIVE) jbiMex.setStatus(ExchangeStatus.DONE); } _ode.getChannel().send(jbiMex); } } else if (jbiMex.getPattern().equals(org.apache.ode.jbi.MessageExchangePattern.IN_OUT)) { boolean success = false; Exception err = null; try { invokeOde(jbiMex, ((InOut) jbiMex).getInMessage()); success = true; } catch (Exception ex) { __log.error("Error invoking ODE.", ex); err = ex; } catch (Throwable t) { __log.error("Unexpected error invoking ODE.", t); err = new RuntimeException(t); } finally { // If we got an error that wasn't sent. if (jbiMex.getStatus() == ExchangeStatus.ACTIVE && !success) { - if (err != null && jbiMex.getError() != null) { + if (err != null && jbiMex.getError() == null) { jbiMex.setError(err); } jbiMex.setStatus(ExchangeStatus.ERROR); _ode.getChannel().send(jbiMex); } } } else { __log.error("JBI MessageExchange " + jbiMex.getExchangeId() + " is of an unsupported pattern " + jbiMex.getPattern()); jbiMex.setStatus(ExchangeStatus.ERROR); jbiMex.setError(new Exception("Unknown message exchange pattern: " + jbiMex.getPattern())); } } /** * Forward a JBI input message to ODE. * * @param jbiMex */ private void invokeOde(javax.jbi.messaging.MessageExchange jbiMex, NormalizedMessage request) throws Exception { MyRoleMessageExchange odeMex; if (__log.isDebugEnabled()) { __log.debug("invokeOde() JBI exchangeId=" + jbiMex.getExchangeId() + " endpoint=" + _endpoint + " operation=" + jbiMex.getOperation()); } odeMex = _ode._server.createMessageExchange(InvocationStyle.UNRELIABLE, _endpoint.serviceName, jbiMex.getOperation() .getLocalPart(), jbiMex.getExchangeId()); if (odeMex.getOperation() == null) { __log.error("ODE MEX " + odeMex + " was unroutable."); sendError(jbiMex, new IllegalArgumentException("Unroutable invocation.")); return; } copyMexProperties(odeMex, jbiMex); javax.wsdl.Message msgdef = odeMex.getOperation().getInput().getMessage(); Message odeRequest = odeMex.createMessage(odeMex.getOperation().getInput().getMessage().getQName()); Mapper mapper = _ode.findMapper(request, odeMex.getOperation()); if (mapper == null) { String errmsg = "Could not find a mapper for request message for JBI MEX " + jbiMex.getExchangeId() + "; ODE MEX " + odeMex.getMessageExchangeId() + " is failed. "; __log.error(errmsg); throw new MessageTranslationException(errmsg); } odeMex.setProperty(Mapper.class.getName(), mapper.getClass().getName()); mapper.toODE(odeRequest, request, msgdef); odeMex.setRequest(odeRequest); try { odeMex.invokeBlocking(); } catch (Exception ex) { __log.error("ODE MEX " + odeMex + " resulted in an error."); sendError(jbiMex, ex); return; } switch (odeMex.getAckType()) { case FAULT: outResponseFault(odeMex, jbiMex); break; case RESPONSE: outResponse(odeMex, jbiMex); break; case FAILURE: outFailure(odeMex, jbiMex); break; default: __log.fatal("Unexpected AckType:" + odeMex.getAckType()); sendError(jbiMex, new RuntimeException("Unexpected AckType:" + odeMex.getAckType())); } } private void outFailure(MyRoleMessageExchange odeMex, javax.jbi.messaging.MessageExchange jbiMex) { try { jbiMex.setError(new Exception("MEXFailure: " + odeMex.getFailureType())); jbiMex.setStatus(ExchangeStatus.ERROR); // TODO: get failure codes out of the message. _ode.getChannel().send(jbiMex); } catch (MessagingException ex) { __log.fatal("Error bridging ODE out response: ", ex); } } private void outResponse(MyRoleMessageExchange mex, javax.jbi.messaging.MessageExchange jbiMex) { InOut inout = (InOut) jbiMex; try { NormalizedMessage nmsg = inout.createMessage(); String mapperName = mex.getProperty(Mapper.class.getName()); Mapper mapper = _ode.getMapper(mapperName); if (mapper == null) { String errmsg = "Message-mapper " + mapperName + " used in ODE MEX " + mex.getMessageExchangeId() + " is no longer available."; __log.error(errmsg); throw new MessageTranslationException(errmsg); } mapper.toNMS(nmsg, mex.getResponse(), mex.getOperation().getOutput().getMessage(), null); inout.setOutMessage(nmsg); _ode.getChannel().send(inout); } catch (MessagingException ex) { __log.error("Error bridging ODE out response: ", ex); sendError(jbiMex, ex); } catch (MessageTranslationException e) { __log.error("Error translating ODE message " + mex.getResponse() + " to NMS format!", e); sendError(jbiMex, e); } } private void outResponseFault(MyRoleMessageExchange mex, javax.jbi.messaging.MessageExchange jbiMex) { InOut inout = (InOut) jbiMex; try { Fault flt = inout.createFault(); String mapperName = mex.getProperty(Mapper.class.getName()); Mapper mapper = _ode.getMapper(mapperName); if (mapper == null) { String errmsg = "Message-mapper " + mapperName + " used in ODE MEX " + mex.getMessageExchangeId() + " is no longer available."; __log.error(errmsg); throw new MessageTranslationException(errmsg); } QName fault = mex.getFault(); javax.wsdl.Fault wsdlFault = mex.getOperation().getFault(fault.getLocalPart()); if (wsdlFault == null) { sendError(jbiMex, new MessageTranslationException("Unmapped Fault : " + fault + ": " + mex.getFaultExplanation())); } else { mapper.toNMS(flt, mex.getFaultResponse(), wsdlFault.getMessage(), fault); inout.setFault(flt); _ode.getChannel().send(inout); } } catch (MessagingException e) { __log.error("Error bridging ODE fault response: ", e); sendError(jbiMex, e); } catch (MessageTranslationException mte) { __log.error("Error translating ODE fault message " + mex.getFaultResponse() + " to NMS format!", mte); sendError(jbiMex, mte); } } private void sendError(javax.jbi.messaging.MessageExchange jbiMex, Exception error) { try { jbiMex.setError(error); jbiMex.setStatus(ExchangeStatus.ERROR); _ode.getChannel().send(jbiMex); } catch (Exception e) { __log.error("Error sending ERROR status: ", e); } } public Endpoint getEndpoint() { return _endpoint; } }
true
true
public void onJbiMessageExchange(javax.jbi.messaging.MessageExchange jbiMex) throws MessagingException { if (jbiMex.getRole() != javax.jbi.messaging.MessageExchange.Role.PROVIDER) { String errmsg = "Message exchange is not in PROVIDER role as expected: " + jbiMex.getExchangeId(); __log.fatal(errmsg); throw new IllegalArgumentException(errmsg); } if (jbiMex.getStatus() != ExchangeStatus.ACTIVE) { // We can forget about the exchange. return; } if (jbiMex.getOperation() == null) { throw new IllegalArgumentException("Null operation in JBI message exchange id=" + jbiMex.getExchangeId() + " endpoint=" + _endpoint); } if (jbiMex.getPattern().equals(org.apache.ode.jbi.MessageExchangePattern.IN_ONLY)) { boolean success = false; Exception err = null; try { invokeOde(jbiMex, ((InOnly) jbiMex).getInMessage()); success = true; } catch (Exception ex) { __log.error("Error invoking ODE.", ex); err = ex; } finally { if (!success) { jbiMex.setStatus(ExchangeStatus.ERROR); if (err != null && jbiMex.getError() != null) jbiMex.setError(err); } else { if (jbiMex.getStatus() == ExchangeStatus.ACTIVE) jbiMex.setStatus(ExchangeStatus.DONE); } _ode.getChannel().send(jbiMex); } } else if (jbiMex.getPattern().equals(org.apache.ode.jbi.MessageExchangePattern.IN_OUT)) { boolean success = false; Exception err = null; try { invokeOde(jbiMex, ((InOut) jbiMex).getInMessage()); success = true; } catch (Exception ex) { __log.error("Error invoking ODE.", ex); err = ex; } catch (Throwable t) { __log.error("Unexpected error invoking ODE.", t); err = new RuntimeException(t); } finally { // If we got an error that wasn't sent. if (jbiMex.getStatus() == ExchangeStatus.ACTIVE && !success) { if (err != null && jbiMex.getError() != null) { jbiMex.setError(err); } jbiMex.setStatus(ExchangeStatus.ERROR); _ode.getChannel().send(jbiMex); } } } else { __log.error("JBI MessageExchange " + jbiMex.getExchangeId() + " is of an unsupported pattern " + jbiMex.getPattern()); jbiMex.setStatus(ExchangeStatus.ERROR); jbiMex.setError(new Exception("Unknown message exchange pattern: " + jbiMex.getPattern())); } }
public void onJbiMessageExchange(javax.jbi.messaging.MessageExchange jbiMex) throws MessagingException { if (jbiMex.getRole() != javax.jbi.messaging.MessageExchange.Role.PROVIDER) { String errmsg = "Message exchange is not in PROVIDER role as expected: " + jbiMex.getExchangeId(); __log.fatal(errmsg); throw new IllegalArgumentException(errmsg); } if (jbiMex.getStatus() != ExchangeStatus.ACTIVE) { // We can forget about the exchange. return; } if (jbiMex.getOperation() == null) { throw new IllegalArgumentException("Null operation in JBI message exchange id=" + jbiMex.getExchangeId() + " endpoint=" + _endpoint); } if (jbiMex.getPattern().equals(org.apache.ode.jbi.MessageExchangePattern.IN_ONLY)) { boolean success = false; Exception err = null; try { invokeOde(jbiMex, ((InOnly) jbiMex).getInMessage()); success = true; } catch (Exception ex) { __log.error("Error invoking ODE.", ex); err = ex; } finally { if (!success) { jbiMex.setStatus(ExchangeStatus.ERROR); if (err != null && jbiMex.getError() != null) jbiMex.setError(err); } else { if (jbiMex.getStatus() == ExchangeStatus.ACTIVE) jbiMex.setStatus(ExchangeStatus.DONE); } _ode.getChannel().send(jbiMex); } } else if (jbiMex.getPattern().equals(org.apache.ode.jbi.MessageExchangePattern.IN_OUT)) { boolean success = false; Exception err = null; try { invokeOde(jbiMex, ((InOut) jbiMex).getInMessage()); success = true; } catch (Exception ex) { __log.error("Error invoking ODE.", ex); err = ex; } catch (Throwable t) { __log.error("Unexpected error invoking ODE.", t); err = new RuntimeException(t); } finally { // If we got an error that wasn't sent. if (jbiMex.getStatus() == ExchangeStatus.ACTIVE && !success) { if (err != null && jbiMex.getError() == null) { jbiMex.setError(err); } jbiMex.setStatus(ExchangeStatus.ERROR); _ode.getChannel().send(jbiMex); } } } else { __log.error("JBI MessageExchange " + jbiMex.getExchangeId() + " is of an unsupported pattern " + jbiMex.getPattern()); jbiMex.setStatus(ExchangeStatus.ERROR); jbiMex.setError(new Exception("Unknown message exchange pattern: " + jbiMex.getPattern())); } }
diff --git a/src/hunternif/mc/dota2items/client/gui/GuiDotaStats.java b/src/hunternif/mc/dota2items/client/gui/GuiDotaStats.java index 5bd71c4..c1406c2 100644 --- a/src/hunternif/mc/dota2items/client/gui/GuiDotaStats.java +++ b/src/hunternif/mc/dota2items/client/gui/GuiDotaStats.java @@ -1,87 +1,91 @@ package hunternif.mc.dota2items.client.gui; import hunternif.mc.dota2items.Dota2Items; import hunternif.mc.dota2items.core.EntityStats; import hunternif.mc.dota2items.core.Mechanics; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.client.renderer.Tessellator; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.MathHelper; import org.lwjgl.opengl.GL11; public class GuiDotaStats { public static final int WIDTH = 113; public static final int HEIGHT = 60; private static final int COLOR_REGULAR = 0xffffff; private static final int COLOR_BONUS = 0x26B117; public void render() { Minecraft mc = Minecraft.getMinecraft(); // Show stats when the inventory is open: if (!(mc.currentScreen instanceof GuiContainer)) { return; } int left = 0; int top = mc.currentScreen.height - HEIGHT; GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); GL11.glDisable(GL11.GL_LIGHTING); mc.renderEngine.bindTexture("/mods/"+Dota2Items.ID+"/textures/gui/stats.png"); Tessellator tessellator = Tessellator.instance; tessellator.startDrawingQuads(); tessellator.addVertexWithUV(left+WIDTH, top+HEIGHT, 0, 1, 1); tessellator.addVertexWithUV(left+WIDTH, top, 0, 1, 0); tessellator.addVertexWithUV(left, top, 0, 0, 0); tessellator.addVertexWithUV(left, top+HEIGHT, 0, 0, 1); tessellator.draw(); EntityStats stats = Dota2Items.mechanics.getEntityStats(mc.thePlayer); float baseDmg = 1; - boolean isMelee = false; + boolean isMelee = true; ItemStack item = mc.thePlayer.getCurrentEquippedItem(); if (item != null) { // Calculating damage against himself, lol. baseDmg = item.getDamageVsEntity(mc.thePlayer); - isMelee = item.itemID == Item.bow.itemID; + if (item.itemID == Item.bow.itemID) { + isMelee = false; + // Assume the damage of an arrow at average charge: 6 + baseDmg = 6; + } } baseDmg *= Mechanics.DOTA_VS_MINECRAFT_DAMAGE; float improvedDmg = stats.getDamage(baseDmg, isMelee); int baseValue = MathHelper.floor_float(baseDmg); int improvedValue = MathHelper.floor_float(improvedDmg) - baseValue; String str = String.valueOf(baseValue) + (improvedValue > 0 ? (EnumChatFormatting.GREEN.toString() + "+" + improvedValue) : ""); int strlen = mc.fontRenderer.getStringWidth(str); mc.fontRenderer.drawString(str, left + 32 - strlen/2, top + 8, COLOR_REGULAR); baseValue = stats.baseArmor; improvedValue = stats.getArmor(baseValue); str = String.valueOf(baseValue) + (improvedValue > 0 ? (EnumChatFormatting.GREEN.toString() + "+" + improvedValue) : ""); strlen = mc.fontRenderer.getStringWidth(str); mc.fontRenderer.drawString(str, left + 18 - strlen/2, top + 44, COLOR_REGULAR); str = String.valueOf(stats.getDotaMovementSpeed()); strlen = mc.fontRenderer.getStringWidth(str); mc.fontRenderer.drawString(str, left + 45 - strlen/2, top + 44, COLOR_REGULAR); baseValue = stats.baseStrength; improvedValue = stats.getStrength(); str = String.valueOf(baseValue) + (improvedValue > 0 ? (EnumChatFormatting.GREEN.toString() + "+" + improvedValue) : ""); strlen = mc.fontRenderer.getStringWidth(str); mc.fontRenderer.drawString(str, left + 93 - strlen/2, top + 11, COLOR_REGULAR); baseValue = stats.baseAgility; improvedValue = stats.getAgility(); str = String.valueOf(baseValue) + (improvedValue > 0 ? (EnumChatFormatting.GREEN.toString() + "+" + improvedValue) : ""); strlen = mc.fontRenderer.getStringWidth(str); mc.fontRenderer.drawString(str, left + 93 - strlen/2, top + 27, COLOR_REGULAR); baseValue = stats.baseIntelligence; improvedValue = stats.getIntelligence(); str = String.valueOf(baseValue) + (improvedValue > 0 ? (EnumChatFormatting.GREEN.toString() + "+" + improvedValue) : ""); strlen = mc.fontRenderer.getStringWidth(str); mc.fontRenderer.drawString(str, left + 93 - strlen/2, top + 44, COLOR_REGULAR); } }
false
true
public void render() { Minecraft mc = Minecraft.getMinecraft(); // Show stats when the inventory is open: if (!(mc.currentScreen instanceof GuiContainer)) { return; } int left = 0; int top = mc.currentScreen.height - HEIGHT; GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); GL11.glDisable(GL11.GL_LIGHTING); mc.renderEngine.bindTexture("/mods/"+Dota2Items.ID+"/textures/gui/stats.png"); Tessellator tessellator = Tessellator.instance; tessellator.startDrawingQuads(); tessellator.addVertexWithUV(left+WIDTH, top+HEIGHT, 0, 1, 1); tessellator.addVertexWithUV(left+WIDTH, top, 0, 1, 0); tessellator.addVertexWithUV(left, top, 0, 0, 0); tessellator.addVertexWithUV(left, top+HEIGHT, 0, 0, 1); tessellator.draw(); EntityStats stats = Dota2Items.mechanics.getEntityStats(mc.thePlayer); float baseDmg = 1; boolean isMelee = false; ItemStack item = mc.thePlayer.getCurrentEquippedItem(); if (item != null) { // Calculating damage against himself, lol. baseDmg = item.getDamageVsEntity(mc.thePlayer); isMelee = item.itemID == Item.bow.itemID; } baseDmg *= Mechanics.DOTA_VS_MINECRAFT_DAMAGE; float improvedDmg = stats.getDamage(baseDmg, isMelee); int baseValue = MathHelper.floor_float(baseDmg); int improvedValue = MathHelper.floor_float(improvedDmg) - baseValue; String str = String.valueOf(baseValue) + (improvedValue > 0 ? (EnumChatFormatting.GREEN.toString() + "+" + improvedValue) : ""); int strlen = mc.fontRenderer.getStringWidth(str); mc.fontRenderer.drawString(str, left + 32 - strlen/2, top + 8, COLOR_REGULAR); baseValue = stats.baseArmor; improvedValue = stats.getArmor(baseValue); str = String.valueOf(baseValue) + (improvedValue > 0 ? (EnumChatFormatting.GREEN.toString() + "+" + improvedValue) : ""); strlen = mc.fontRenderer.getStringWidth(str); mc.fontRenderer.drawString(str, left + 18 - strlen/2, top + 44, COLOR_REGULAR); str = String.valueOf(stats.getDotaMovementSpeed()); strlen = mc.fontRenderer.getStringWidth(str); mc.fontRenderer.drawString(str, left + 45 - strlen/2, top + 44, COLOR_REGULAR); baseValue = stats.baseStrength; improvedValue = stats.getStrength(); str = String.valueOf(baseValue) + (improvedValue > 0 ? (EnumChatFormatting.GREEN.toString() + "+" + improvedValue) : ""); strlen = mc.fontRenderer.getStringWidth(str); mc.fontRenderer.drawString(str, left + 93 - strlen/2, top + 11, COLOR_REGULAR); baseValue = stats.baseAgility; improvedValue = stats.getAgility(); str = String.valueOf(baseValue) + (improvedValue > 0 ? (EnumChatFormatting.GREEN.toString() + "+" + improvedValue) : ""); strlen = mc.fontRenderer.getStringWidth(str); mc.fontRenderer.drawString(str, left + 93 - strlen/2, top + 27, COLOR_REGULAR); baseValue = stats.baseIntelligence; improvedValue = stats.getIntelligence(); str = String.valueOf(baseValue) + (improvedValue > 0 ? (EnumChatFormatting.GREEN.toString() + "+" + improvedValue) : ""); strlen = mc.fontRenderer.getStringWidth(str); mc.fontRenderer.drawString(str, left + 93 - strlen/2, top + 44, COLOR_REGULAR); }
public void render() { Minecraft mc = Minecraft.getMinecraft(); // Show stats when the inventory is open: if (!(mc.currentScreen instanceof GuiContainer)) { return; } int left = 0; int top = mc.currentScreen.height - HEIGHT; GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); GL11.glDisable(GL11.GL_LIGHTING); mc.renderEngine.bindTexture("/mods/"+Dota2Items.ID+"/textures/gui/stats.png"); Tessellator tessellator = Tessellator.instance; tessellator.startDrawingQuads(); tessellator.addVertexWithUV(left+WIDTH, top+HEIGHT, 0, 1, 1); tessellator.addVertexWithUV(left+WIDTH, top, 0, 1, 0); tessellator.addVertexWithUV(left, top, 0, 0, 0); tessellator.addVertexWithUV(left, top+HEIGHT, 0, 0, 1); tessellator.draw(); EntityStats stats = Dota2Items.mechanics.getEntityStats(mc.thePlayer); float baseDmg = 1; boolean isMelee = true; ItemStack item = mc.thePlayer.getCurrentEquippedItem(); if (item != null) { // Calculating damage against himself, lol. baseDmg = item.getDamageVsEntity(mc.thePlayer); if (item.itemID == Item.bow.itemID) { isMelee = false; // Assume the damage of an arrow at average charge: 6 baseDmg = 6; } } baseDmg *= Mechanics.DOTA_VS_MINECRAFT_DAMAGE; float improvedDmg = stats.getDamage(baseDmg, isMelee); int baseValue = MathHelper.floor_float(baseDmg); int improvedValue = MathHelper.floor_float(improvedDmg) - baseValue; String str = String.valueOf(baseValue) + (improvedValue > 0 ? (EnumChatFormatting.GREEN.toString() + "+" + improvedValue) : ""); int strlen = mc.fontRenderer.getStringWidth(str); mc.fontRenderer.drawString(str, left + 32 - strlen/2, top + 8, COLOR_REGULAR); baseValue = stats.baseArmor; improvedValue = stats.getArmor(baseValue); str = String.valueOf(baseValue) + (improvedValue > 0 ? (EnumChatFormatting.GREEN.toString() + "+" + improvedValue) : ""); strlen = mc.fontRenderer.getStringWidth(str); mc.fontRenderer.drawString(str, left + 18 - strlen/2, top + 44, COLOR_REGULAR); str = String.valueOf(stats.getDotaMovementSpeed()); strlen = mc.fontRenderer.getStringWidth(str); mc.fontRenderer.drawString(str, left + 45 - strlen/2, top + 44, COLOR_REGULAR); baseValue = stats.baseStrength; improvedValue = stats.getStrength(); str = String.valueOf(baseValue) + (improvedValue > 0 ? (EnumChatFormatting.GREEN.toString() + "+" + improvedValue) : ""); strlen = mc.fontRenderer.getStringWidth(str); mc.fontRenderer.drawString(str, left + 93 - strlen/2, top + 11, COLOR_REGULAR); baseValue = stats.baseAgility; improvedValue = stats.getAgility(); str = String.valueOf(baseValue) + (improvedValue > 0 ? (EnumChatFormatting.GREEN.toString() + "+" + improvedValue) : ""); strlen = mc.fontRenderer.getStringWidth(str); mc.fontRenderer.drawString(str, left + 93 - strlen/2, top + 27, COLOR_REGULAR); baseValue = stats.baseIntelligence; improvedValue = stats.getIntelligence(); str = String.valueOf(baseValue) + (improvedValue > 0 ? (EnumChatFormatting.GREEN.toString() + "+" + improvedValue) : ""); strlen = mc.fontRenderer.getStringWidth(str); mc.fontRenderer.drawString(str, left + 93 - strlen/2, top + 44, COLOR_REGULAR); }
diff --git a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/actions/StringValueInputDialog.java b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/actions/StringValueInputDialog.java index 19c856075..8bf7712f9 100644 --- a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/actions/StringValueInputDialog.java +++ b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/actions/StringValueInputDialog.java @@ -1,272 +1,273 @@ /******************************************************************************* * Copyright (c) 2004, 2005 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial implementation *******************************************************************************/ package org.eclipse.jdt.internal.debug.ui.actions; import org.eclipse.debug.core.DebugException; import org.eclipse.debug.internal.ui.DebugUIPlugin; import org.eclipse.jdt.debug.core.IJavaVariable; import org.eclipse.jdt.internal.debug.ui.JDIDebugUIPlugin; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.jface.text.Document; import org.eclipse.jface.text.TextViewer; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Shell; /** * A dialog which prompts the user to enter a new value for a * String variable. The user is given the option of entering the * literal value that they want assigned to the String or entering * an expression for evaluation. */ public class StringValueInputDialog extends ExpressionInputDialog { private TextViewer fTextViewer; private Button fTextButton; private Button fEvaluationButton; private Button fWrapText; private Group fTextGroup; private boolean fUseLiteralValue= true; private static final String USE_EVALUATION = "USE_EVALUATION"; //$NON-NLS-1$ private static final String WRAP_TEXT = "WRAP_TEXT"; //$NON-NLS-1$ /** * @param parentShell * @param variable */ protected StringValueInputDialog(Shell parentShell, IJavaVariable variable) { super(parentShell, variable); } /** * Override superclass method to insert toggle buttons * immediately after the input area. */ protected void createInputArea(Composite parent) { super.createInputArea(parent); createRadioButtons(parent); Dialog.applyDialogFont(parent); } /** * Override superclass method to create the appropriate viewer * (source viewer or simple text viewer) in the input area. */ protected void populateInputArea() { boolean useEvaluation= false; IDialogSettings settings = getDialogSettings(); if (settings != null) { useEvaluation= settings.getBoolean(USE_EVALUATION); } if (useEvaluation) { createSourceViewer(); fUseLiteralValue= false; fEvaluationButton.setSelection(true); } else { createTextViewer(); fTextButton.setSelection(true); } } /** * Creates the text viewer that allows the user to enter a new String * value. */ private void createTextViewer() { fTextGroup= new Group(fInputArea, SWT.NONE); fTextGroup.setLayout(new GridLayout()); fTextGroup.setLayoutData(new GridData(GridData.FILL_BOTH)); fTextGroup.setText(ActionMessages.StringValueInputDialog_0); //$NON-NLS-1$ Composite parent= fTextGroup; fTextViewer= new TextViewer(parent, SWT.MULTI | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL); fTextViewer.setDocument(new Document()); GridData gridData = new GridData(GridData.FILL_BOTH); gridData.widthHint= 300; gridData.heightHint= 150; fTextViewer.getTextWidget().setLayoutData(gridData); try { String valueString = fVariable.getValue().getValueString(); fTextViewer.getDocument().set(valueString); } catch (DebugException e) { DebugUIPlugin.log(e); } + fTextViewer.getControl().setFocus(); fWrapText= new Button(parent, SWT.CHECK); fWrapText.setText(ActionMessages.StringValueInputDialog_4); //$NON-NLS-1$ boolean wrap= true; IDialogSettings settings = getDialogSettings(); if (settings != null) { wrap= settings.getBoolean(WRAP_TEXT); } fWrapText.setSelection(wrap); updateWordWrap(); fWrapText.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { updateWordWrap(); } }); Dialog.applyDialogFont(fInputArea); } private void updateWordWrap() { fTextViewer.getTextWidget().setWordWrap(fWrapText.getSelection()); } /** * Creates the radio buttons that allow the user to choose between * simple text mode and evaluation mode. */ protected void createRadioButtons(Composite parent) { fTextButton= new Button(parent, SWT.RADIO); fTextButton.setText(ActionMessages.StringValueInputDialog_1); //$NON-NLS-1$ fTextButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { handleRadioSelectionChanged(); } }); fEvaluationButton= new Button(parent, SWT.RADIO); fEvaluationButton.setText(ActionMessages.StringValueInputDialog_2); //$NON-NLS-1$ } /** * The radio button selection has changed update the input widgetry * to reflect the user's selection. */ private void handleRadioSelectionChanged() { fUseLiteralValue= fTextButton.getSelection(); if (fUseLiteralValue) { disposeSourceViewer(); createTextViewer(); } else { // Evaluation button selected disposeTextViewer(); createSourceViewer(); } fInputArea.layout(true, true); } /** * Disposes of the text viewer and associated widgets. */ protected void disposeTextViewer() { if (fTextGroup != null) { fTextGroup.dispose(); fTextGroup= null; } if (fTextViewer != null) { StyledText textWidget = fTextViewer.getTextWidget(); if (textWidget != null) { textWidget.dispose(); } fTextViewer= null; } if (fWrapText != null) { fWrapText.dispose(); fWrapText= null; } } /** * Updates the error message based on the user's input. */ protected void refreshValidState() { if (fSourceViewer != null) { super.refreshValidState(); return; } String errorMessage= null; String text= getText(); boolean valid= text != null && text.trim().length() > 0; if (!valid) { errorMessage= ActionMessages.StringValueInputDialog_3; //$NON-NLS-1$ } setErrorMessage(errorMessage); } /** * Override superclass method to persist user's evaluation/literal mode * selection. */ protected void okPressed() { IDialogSettings settings= getDialogSettings(); if (settings == null) { settings= JDIDebugUIPlugin.getDefault().getDialogSettings().addNewSection(getDialogSettingsSectionName()); } settings.put(USE_EVALUATION, fEvaluationButton.getSelection()); if (fWrapText != null) { settings.put(WRAP_TEXT, fWrapText.getSelection()); } super.okPressed(); } /** * Returns <code>true</code> if this dialog's result should be interpreted * as a literal value and <code>false</code> if the result should be interpreted * as an expression for evaluation. * * @return whether or not this dialog's result is a literal value. */ public boolean isUseLiteralValue() { return fUseLiteralValue; } /** * Override superclass method to return text from the simple text * viewer if appropriate. * @see ExpressionInputDialog#getText() */ protected String getText() { if (fTextButton.getSelection()) { return fTextViewer.getDocument().get(); } return super.getText(); } /** * Override superclass method to dispose of the simple text viewer * if appropriate. * @see ExpressionInputDialog#dispose() */ protected void dispose() { if (fTextButton.getSelection()) { disposeTextViewer(); } else { super.dispose(); } } /** * Returns the dialog settings used for this dialog * @return the dialog settings used for this dialog */ protected IDialogSettings getDialogSettings() { return JDIDebugUIPlugin.getDefault().getDialogSettings().getSection(getDialogSettingsSectionName()); } /* (non-Javadoc) * @see org.eclipse.jdt.internal.debug.ui.actions.ExpressionInputDialog#getDialogSettingsSectionName() */ protected String getDialogSettingsSectionName() { return "STRING_VALUE_INPUT_DIALOG"; //$NON-NLS-1$ } }
true
true
private void createTextViewer() { fTextGroup= new Group(fInputArea, SWT.NONE); fTextGroup.setLayout(new GridLayout()); fTextGroup.setLayoutData(new GridData(GridData.FILL_BOTH)); fTextGroup.setText(ActionMessages.StringValueInputDialog_0); //$NON-NLS-1$ Composite parent= fTextGroup; fTextViewer= new TextViewer(parent, SWT.MULTI | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL); fTextViewer.setDocument(new Document()); GridData gridData = new GridData(GridData.FILL_BOTH); gridData.widthHint= 300; gridData.heightHint= 150; fTextViewer.getTextWidget().setLayoutData(gridData); try { String valueString = fVariable.getValue().getValueString(); fTextViewer.getDocument().set(valueString); } catch (DebugException e) { DebugUIPlugin.log(e); } fWrapText= new Button(parent, SWT.CHECK); fWrapText.setText(ActionMessages.StringValueInputDialog_4); //$NON-NLS-1$ boolean wrap= true; IDialogSettings settings = getDialogSettings(); if (settings != null) { wrap= settings.getBoolean(WRAP_TEXT); } fWrapText.setSelection(wrap); updateWordWrap(); fWrapText.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { updateWordWrap(); } }); Dialog.applyDialogFont(fInputArea); }
private void createTextViewer() { fTextGroup= new Group(fInputArea, SWT.NONE); fTextGroup.setLayout(new GridLayout()); fTextGroup.setLayoutData(new GridData(GridData.FILL_BOTH)); fTextGroup.setText(ActionMessages.StringValueInputDialog_0); //$NON-NLS-1$ Composite parent= fTextGroup; fTextViewer= new TextViewer(parent, SWT.MULTI | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL); fTextViewer.setDocument(new Document()); GridData gridData = new GridData(GridData.FILL_BOTH); gridData.widthHint= 300; gridData.heightHint= 150; fTextViewer.getTextWidget().setLayoutData(gridData); try { String valueString = fVariable.getValue().getValueString(); fTextViewer.getDocument().set(valueString); } catch (DebugException e) { DebugUIPlugin.log(e); } fTextViewer.getControl().setFocus(); fWrapText= new Button(parent, SWT.CHECK); fWrapText.setText(ActionMessages.StringValueInputDialog_4); //$NON-NLS-1$ boolean wrap= true; IDialogSettings settings = getDialogSettings(); if (settings != null) { wrap= settings.getBoolean(WRAP_TEXT); } fWrapText.setSelection(wrap); updateWordWrap(); fWrapText.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { updateWordWrap(); } }); Dialog.applyDialogFont(fInputArea); }
diff --git a/Demo.java b/Demo.java index d5bd336..bd31c3c 100644 --- a/Demo.java +++ b/Demo.java @@ -1,45 +1,45 @@ import com.smsgh.ApiHost; import com.smsgh.ApiMessage; import com.smsgh.ApiException; public class Demo { /** * Main */ public static void Main(String[] args) { ApiHost apiHost = new ApiHost(); - apiHost.ClientId = "user123"; - apiHost.ClientSecret = "secret"; + apiHost.setClientId("user123"); + apiHost.setClientSecret("secret"); try { /** * Sending a quick message. */ apiHost.getMessagesResource() .send("SMSGH", "+233248183783", "Hello world!"); /** * Sending a message with extended properties. */ ApiMessage apiMessage = new ApiMessage(); apiMessage.setFrom("SMSGH"); apiMessage.setTo("+233248183783"); apiMessage.setContent("Hello world!"); apiMessage.setRegisteredDelivery(true); apiHost.getMessagesResource().send(apiMessage); /** * Scheduling a message. */ // ApiMessage apiMessage = new ApiMessage(); apiMessage.setFrom("SMSGH"); apiMessage.setTo("+233248183783"); apiMessage.setContent("Hello world!"); apiHost.getMessagesResource() .schedule(apiMessage, new java.util.Date()); } catch (ApiException ex) { System.out.println("Exception: " + ex.getMessage()); } } }
true
true
public static void Main(String[] args) { ApiHost apiHost = new ApiHost(); apiHost.ClientId = "user123"; apiHost.ClientSecret = "secret"; try { /** * Sending a quick message. */ apiHost.getMessagesResource() .send("SMSGH", "+233248183783", "Hello world!"); /** * Sending a message with extended properties. */ ApiMessage apiMessage = new ApiMessage(); apiMessage.setFrom("SMSGH"); apiMessage.setTo("+233248183783"); apiMessage.setContent("Hello world!"); apiMessage.setRegisteredDelivery(true); apiHost.getMessagesResource().send(apiMessage); /** * Scheduling a message. */ // ApiMessage apiMessage = new ApiMessage(); apiMessage.setFrom("SMSGH"); apiMessage.setTo("+233248183783"); apiMessage.setContent("Hello world!"); apiHost.getMessagesResource() .schedule(apiMessage, new java.util.Date()); } catch (ApiException ex) { System.out.println("Exception: " + ex.getMessage()); } }
public static void Main(String[] args) { ApiHost apiHost = new ApiHost(); apiHost.setClientId("user123"); apiHost.setClientSecret("secret"); try { /** * Sending a quick message. */ apiHost.getMessagesResource() .send("SMSGH", "+233248183783", "Hello world!"); /** * Sending a message with extended properties. */ ApiMessage apiMessage = new ApiMessage(); apiMessage.setFrom("SMSGH"); apiMessage.setTo("+233248183783"); apiMessage.setContent("Hello world!"); apiMessage.setRegisteredDelivery(true); apiHost.getMessagesResource().send(apiMessage); /** * Scheduling a message. */ // ApiMessage apiMessage = new ApiMessage(); apiMessage.setFrom("SMSGH"); apiMessage.setTo("+233248183783"); apiMessage.setContent("Hello world!"); apiHost.getMessagesResource() .schedule(apiMessage, new java.util.Date()); } catch (ApiException ex) { System.out.println("Exception: " + ex.getMessage()); } }
diff --git a/src/Modules/Merger.java b/src/Modules/Merger.java index 460caab..5b14104 100644 --- a/src/Modules/Merger.java +++ b/src/Modules/Merger.java @@ -1,131 +1,132 @@ /** * */ package Modules; import Engine.EngineMaster; import Engine.Module; import Engine.Pipe; import Engine.Constants; /** * @author orpheon * */ public class Merger extends Module { public static final int ADDITION = 1; public static final int MULTIPLICATION = 2; public static final int OUTPUT_PIPE = 0; private int operation = ADDITION; public Merger(EngineMaster engine) { super(engine); NUM_INPUT_PIPES = 2; NUM_OUTPUT_PIPES = 1; input_pipes = new Pipe[NUM_INPUT_PIPES]; output_pipes = new Pipe[NUM_OUTPUT_PIPES]; type = Engine.Constants.MODULE_MERGER; } public Merger(EngineMaster engine, int num_inputs) { super(engine); NUM_INPUT_PIPES = num_inputs; NUM_OUTPUT_PIPES = 1; input_pipes = new Pipe[NUM_INPUT_PIPES]; output_pipes = new Pipe[NUM_OUTPUT_PIPES]; } @Override public void get_sound() { if (output_pipes[OUTPUT_PIPE] != null) { int i, j; switch (operation) { case ADDITION: - int sum; + double sum; for (i=0; i<Constants.SNAPSHOT_SIZE; i++) { sum = 0; for (j=0; j<NUM_INPUT_PIPES; j++) { if (input_pipes[j] != null) { sum += input_pipes[j].inner_buffer[i]; } } - output_pipes[0].inner_buffer[i] = sum; + // Don't forget to normalize from -1 to 1 again + output_pipes[OUTPUT_PIPE].inner_buffer[i] = sum / NUM_INPUT_PIPES; } break; case MULTIPLICATION: - int product; + double product; for (i=0; i<Constants.SNAPSHOT_SIZE; i++) { product = 1; for (j=0; j<NUM_INPUT_PIPES; j++) { if (input_pipes[j] != null) { product *= input_pipes[j].inner_buffer[i]; } } output_pipes[OUTPUT_PIPE].inner_buffer[i] = product; } break; default: System.out.println("ERROR: Merger "+index+" has an invalid operation type: "+operation); } } } public int get_operation() { return operation; } public void set_operation(int operation) { this.operation = operation; } public int get_num_inputs() { return NUM_INPUT_PIPES; } public void set_num_inputs(int num) { // No need to change anything if there's no change if (num != NUM_INPUT_PIPES) { // If we want to lower the number of connections, then disconnect all the superfluous ones if (NUM_INPUT_PIPES > num) { for (int i=num; i<NUM_INPUT_PIPES; i++) { if (input_pipes[i] != null) { disconnect_input(i); } } } NUM_INPUT_PIPES = num; Pipe[] tmp = new Pipe[NUM_INPUT_PIPES]; System.arraycopy(input_pipes, 0, tmp, 0, Math.min(input_pipes.length, NUM_INPUT_PIPES)); input_pipes = tmp; } } }
false
true
public void get_sound() { if (output_pipes[OUTPUT_PIPE] != null) { int i, j; switch (operation) { case ADDITION: int sum; for (i=0; i<Constants.SNAPSHOT_SIZE; i++) { sum = 0; for (j=0; j<NUM_INPUT_PIPES; j++) { if (input_pipes[j] != null) { sum += input_pipes[j].inner_buffer[i]; } } output_pipes[0].inner_buffer[i] = sum; } break; case MULTIPLICATION: int product; for (i=0; i<Constants.SNAPSHOT_SIZE; i++) { product = 1; for (j=0; j<NUM_INPUT_PIPES; j++) { if (input_pipes[j] != null) { product *= input_pipes[j].inner_buffer[i]; } } output_pipes[OUTPUT_PIPE].inner_buffer[i] = product; } break; default: System.out.println("ERROR: Merger "+index+" has an invalid operation type: "+operation); } } }
public void get_sound() { if (output_pipes[OUTPUT_PIPE] != null) { int i, j; switch (operation) { case ADDITION: double sum; for (i=0; i<Constants.SNAPSHOT_SIZE; i++) { sum = 0; for (j=0; j<NUM_INPUT_PIPES; j++) { if (input_pipes[j] != null) { sum += input_pipes[j].inner_buffer[i]; } } // Don't forget to normalize from -1 to 1 again output_pipes[OUTPUT_PIPE].inner_buffer[i] = sum / NUM_INPUT_PIPES; } break; case MULTIPLICATION: double product; for (i=0; i<Constants.SNAPSHOT_SIZE; i++) { product = 1; for (j=0; j<NUM_INPUT_PIPES; j++) { if (input_pipes[j] != null) { product *= input_pipes[j].inner_buffer[i]; } } output_pipes[OUTPUT_PIPE].inner_buffer[i] = product; } break; default: System.out.println("ERROR: Merger "+index+" has an invalid operation type: "+operation); } } }
diff --git a/android/src/ru/nia/ledged/android/TransactionEditor.java b/android/src/ru/nia/ledged/android/TransactionEditor.java index 7a6aa9b..f9974c1 100644 --- a/android/src/ru/nia/ledged/android/TransactionEditor.java +++ b/android/src/ru/nia/ledged/android/TransactionEditor.java @@ -1,181 +1,182 @@ package ru.nia.ledged.android; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.text.format.DateFormat; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.inputmethod.EditorInfo; import android.widget.*; import ru.nia.ledged.core.AccountTree; import java.util.Date; public class TransactionEditor extends Activity { AccountTree accounts = new AccountTree(); // input data public static final String KEY_LEAVES_ACCOUNTS = "leaves"; public static final String KEY_DESCRIPTIONS = "descriptions"; // output data public static final String KEY_DATE = "date"; public static final String KEY_DESC = "desc"; public static final String KEY_ACCOUNTS = "accs"; public static final String KEY_AMOUNTS = "amounts"; public static final int MIN_POSTINGS_COUNT = 2; public static final int MAX_EMPTY_AMOUNTS = 1; private LinearLayout postingsEditors; private EditText dateEdit; private AutoCompleteTextView descriptionEdit; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.transaction_editor); Bundle extras = getIntent().getExtras(); String[] leaveNames = extras.getStringArray(KEY_LEAVES_ACCOUNTS); assert leaveNames != null; for (String name : leaveNames) { accounts.findOrCreateAccount(name); } String[] descriptions = extras.getStringArray(KEY_DESCRIPTIONS); dateEdit = (EditText) findViewById(R.id.date); dateEdit.setText(DateFormat.format("M-d", new Date())); dateEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() { public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) { View next = textView.focusSearch(View.FOCUS_DOWN); next.requestFocus(); return true; } }); descriptionEdit = (AutoCompleteTextView) findViewById(R.id.description); descriptionEdit.setAdapter(new ArrayAdapter<String>(this, R.layout.completion_item, descriptions)); postingsEditors = (LinearLayout) findViewById(R.id.postings); Button confirmButtion = (Button) findViewById(R.id.confirm); confirmButtion.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { save(); } }); Button cancelButton = (Button) findViewById(R.id.cancel); cancelButton.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { cancel(); } }); ImageButton addPostingEditorButton = (ImageButton) findViewById(R.id.add_posting); addPostingEditorButton.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { addPostingEditor(); } }); } private void addPostingEditor() { // TODO: custom control final LinearLayout postingEditor = new LinearLayout(this); LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE); vi.inflate(R.layout.posting_editor, postingEditor, true); AutoCompleteTextView accName = (AutoCompleteTextView) postingEditor.findViewById(R.id.account); accName.setAdapter(new AutoCompleteAdapter(this, R.layout.completion_item, accounts)); accName.setOnEditorActionListener(new TextView.OnEditorActionListener() { public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) { if (actionId == EditorInfo.IME_ACTION_SEARCH) { AutoCompleteTextView view = (AutoCompleteTextView) textView; view.getText().insert(view.getSelectionStart(), AccountTree.ACCOUNT_SEPARATOR); return true; } else { return false; } } }); ImageButton delete = (ImageButton) postingEditor.findViewById(R.id.delete); delete.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { postingsEditors.removeView(postingEditor); } }); postingsEditors.addView(postingEditor); } private void save() { String date = dateEdit.getText().toString().trim(); if (date.length() == 0) { reportError(R.string.empty_date); return; } String desc = descriptionEdit.getText().toString(); if (desc.trim().length() == 0) { reportError(R.string.empty_description); + return; } int postingsCount = postingsEditors.getChildCount(); if (postingsCount < MIN_POSTINGS_COUNT) { reportError(R.string.not_enough_postings); return; } String[] accounts = new String[postingsCount]; String[] amounts = new String[postingsCount]; int emptyAmounts = 0; for (int i = 0; i < postingsCount; ++i) { LinearLayout postingEditor = (LinearLayout) postingsEditors.getChildAt(i); AutoCompleteTextView accName = (AutoCompleteTextView) postingEditor.findViewById(R.id.account); accounts[i] = accName.getText().toString().trim(); if (accounts[i].length() == 0) { reportError(R.string.empty_account); return; } EditText amount = (EditText) postingEditor.findViewById(R.id.amount); amounts[i] = amount.getText().toString(); if (amounts[i].trim().length() == 0) { ++emptyAmounts; if (emptyAmounts > MAX_EMPTY_AMOUNTS) { reportError(R.string.too_many_empty_amounts); return; } } } Bundle extras = new Bundle(); extras.putString(KEY_DATE, date); extras.putString(KEY_DESC, desc); extras.putStringArray(KEY_ACCOUNTS, accounts); extras.putStringArray(KEY_AMOUNTS, amounts); Intent intent = new Intent(); intent.putExtras(extras); setResult(RESULT_OK, intent); finish(); } private void cancel() { setResult(RESULT_CANCELED); finish(); } private void reportError(int message_res_id) { Toast.makeText(this, message_res_id, Toast.LENGTH_LONG).show(); } }
true
true
private void save() { String date = dateEdit.getText().toString().trim(); if (date.length() == 0) { reportError(R.string.empty_date); return; } String desc = descriptionEdit.getText().toString(); if (desc.trim().length() == 0) { reportError(R.string.empty_description); } int postingsCount = postingsEditors.getChildCount(); if (postingsCount < MIN_POSTINGS_COUNT) { reportError(R.string.not_enough_postings); return; } String[] accounts = new String[postingsCount]; String[] amounts = new String[postingsCount]; int emptyAmounts = 0; for (int i = 0; i < postingsCount; ++i) { LinearLayout postingEditor = (LinearLayout) postingsEditors.getChildAt(i); AutoCompleteTextView accName = (AutoCompleteTextView) postingEditor.findViewById(R.id.account); accounts[i] = accName.getText().toString().trim(); if (accounts[i].length() == 0) { reportError(R.string.empty_account); return; } EditText amount = (EditText) postingEditor.findViewById(R.id.amount); amounts[i] = amount.getText().toString(); if (amounts[i].trim().length() == 0) { ++emptyAmounts; if (emptyAmounts > MAX_EMPTY_AMOUNTS) { reportError(R.string.too_many_empty_amounts); return; } } } Bundle extras = new Bundle(); extras.putString(KEY_DATE, date); extras.putString(KEY_DESC, desc); extras.putStringArray(KEY_ACCOUNTS, accounts); extras.putStringArray(KEY_AMOUNTS, amounts); Intent intent = new Intent(); intent.putExtras(extras); setResult(RESULT_OK, intent); finish(); }
private void save() { String date = dateEdit.getText().toString().trim(); if (date.length() == 0) { reportError(R.string.empty_date); return; } String desc = descriptionEdit.getText().toString(); if (desc.trim().length() == 0) { reportError(R.string.empty_description); return; } int postingsCount = postingsEditors.getChildCount(); if (postingsCount < MIN_POSTINGS_COUNT) { reportError(R.string.not_enough_postings); return; } String[] accounts = new String[postingsCount]; String[] amounts = new String[postingsCount]; int emptyAmounts = 0; for (int i = 0; i < postingsCount; ++i) { LinearLayout postingEditor = (LinearLayout) postingsEditors.getChildAt(i); AutoCompleteTextView accName = (AutoCompleteTextView) postingEditor.findViewById(R.id.account); accounts[i] = accName.getText().toString().trim(); if (accounts[i].length() == 0) { reportError(R.string.empty_account); return; } EditText amount = (EditText) postingEditor.findViewById(R.id.amount); amounts[i] = amount.getText().toString(); if (amounts[i].trim().length() == 0) { ++emptyAmounts; if (emptyAmounts > MAX_EMPTY_AMOUNTS) { reportError(R.string.too_many_empty_amounts); return; } } } Bundle extras = new Bundle(); extras.putString(KEY_DATE, date); extras.putString(KEY_DESC, desc); extras.putStringArray(KEY_ACCOUNTS, accounts); extras.putStringArray(KEY_AMOUNTS, amounts); Intent intent = new Intent(); intent.putExtras(extras); setResult(RESULT_OK, intent); finish(); }
diff --git a/contentconnector-core/src/main/java/com/gentics/cr/rest/RESTBinaryContainer.java b/contentconnector-core/src/main/java/com/gentics/cr/rest/RESTBinaryContainer.java index a5fa2940..f438bbf2 100644 --- a/contentconnector-core/src/main/java/com/gentics/cr/rest/RESTBinaryContainer.java +++ b/contentconnector-core/src/main/java/com/gentics/cr/rest/RESTBinaryContainer.java @@ -1,194 +1,195 @@ package com.gentics.cr.rest; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import javax.servlet.http.HttpServletRequest; import org.apache.log4j.Logger; import com.gentics.api.lib.resolving.Resolvable; import com.gentics.cr.CRConfigUtil; import com.gentics.cr.CRRequest; import com.gentics.cr.CRResolvableBean; import com.gentics.cr.RequestProcessor; import com.gentics.cr.exceptions.CRException; import com.gentics.cr.util.CRBinaryRequestBuilder; import com.gentics.cr.util.response.IResponseTypeSetter; /** * * Last changed: $Date: 2010-04-01 15:25:54 +0200 (Do, 01 Apr 2010) $ * @version $Revision: 545 $ * @author $Author: [email protected] $ * */ public class RESTBinaryContainer{ private RequestProcessor rp; private String response_encoding; private String contenttype=""; private static Logger log = Logger.getLogger(RESTBinaryContainer.class); CRConfigUtil crConf; private final static String LIVEEDITORXHTML_KEY="container.liveeditorXHTML"; /** * get conten type as string * @return */ public String getContentType() { return(this.contenttype); } /** * Finalize the Container */ public void finalize() { if(this.rp!=null)this.rp.finalize(); } /** * Create new instance * @param crConf */ public RESTBinaryContainer(CRConfigUtil crConf) { this.response_encoding = crConf.getEncoding(); this.crConf = crConf; try { this.rp = crConf.getNewRequestProcessorInstance(1); } catch (CRException e) { CRException ex = new CRException(e); log.error("FAILED TO INITIALIZE REQUEST PROCESSOR... "+ex.getStringStackTrace()); } } private void respondWithError(OutputStream stream, CRException ex, boolean debug) { String ret = ""+ex.getMessage(); if(debug) ret+= " - "+ ex.getStringStackTrace(); try { OutputStreamWriter wr = new OutputStreamWriter(stream, this.response_encoding); wr.write(ret); wr.flush(); wr.close(); } catch (IOException e) { e.printStackTrace(); } } /** * Process the whole Service * @param reqBuilder * @param wrappedObjectsToDeploy * @param stream * @param responsetypesetter */ public void processService(CRBinaryRequestBuilder reqBuilder, Map<String,Resolvable> wrappedObjectsToDeploy, OutputStream stream, IResponseTypeSetter responsetypesetter) { CRBinaryRequestBuilder myReqBuilder = reqBuilder; CRResolvableBean crBean = null; CRRequest req; try { req = myReqBuilder.getBinaryRequest(); //DEPLOY OBJECTS TO REQUEST for (Iterator<Map.Entry<String, Resolvable>> i = wrappedObjectsToDeploy.entrySet().iterator() ; i.hasNext() ; ) { Map.Entry<String,Resolvable> entry = (Entry<String,Resolvable>) i.next(); req.addObjectForFilterDeployment((String)entry.getKey(), entry.getValue()); } if(this.crConf.usesContentidUrl()) { if(req.getContentid()==null) { Object obj = reqBuilder.getRequest(); if(obj instanceof HttpServletRequest) { String[] reqURI = ((HttpServletRequest)obj).getRequestURI().split("/"); ArrayList<String> reqList = new ArrayList<String>(Arrays.asList(reqURI)); int index = reqList.indexOf(((HttpServletRequest)obj).getServletPath().replaceAll("/","")); if(reqList.size()>=index+1) { req.setRequestFilter("object.contentid=="+reqList.get(index+1).toString()); } } //contentid=request.getRequestURI().replaceFirst(request.getContextPath()+request.getServletPath()+"/","").replaceAll("/",""); } } + req.setAttributeArray(new String[]{"mimetype"}); // load by url if no contentid if (req.isUrlRequest()) { crBean = rp.getContentByUrl(req); } else { crBean = rp.getContent(req); } if(crBean!=null) { // set mimetype. if(crBean.getMimetype()==null) { CRConfigUtil rpConf = crConf.getRequestProcessorConfig(1); if(crBean.getObj_type().equals(rpConf.getPageType())) { this.contenttype="text/html; charset="+this.response_encoding; log.info("Responding with mimetype: text/html"); } else { log.info("Mimetype has not been set, using standard instead. ("+crBean.getObj_type()+"!="+rpConf.getPageType()+")"); } } else { this.contenttype=crBean.getMimetype()+"; charset="+this.response_encoding; log.info("Responding with mimetype: "+crBean.getMimetype()); } responsetypesetter.setContentType(this.getContentType()); // output data. if (crBean.isBinary()) { log.debug("Size of content: "+crBean.getBinaryContent().length); stream.write(crBean.getBinaryContent()); } else { OutputStreamWriter wr = new OutputStreamWriter(stream, this.response_encoding); String content = crBean.getContent(this.response_encoding); if(Boolean.parseBoolean((String) crConf.get(LIVEEDITORXHTML_KEY))){ //Gentics Content.Node Liveeditor produces non XHTML brakes. Therefore we must replace them before we return the code content = content.replace("<BR>", "</ br>"); } wr.write(content); wr.flush(); wr.close(); } } else { CRException crex = new CRException("NoDataFound","Data could not be found."); this.respondWithError(stream,crex,myReqBuilder.isDebug()); } stream.flush(); stream.close(); } catch (CRException e1) { this.contenttype="text/html; charset="+this.response_encoding; respondWithError((OutputStream)stream,e1,myReqBuilder.isDebug()); e1.printStackTrace(); } catch(Exception e) { log.error("Error while processing service (RESTBinaryContainer)",e); CRException crex = new CRException(e); this.respondWithError(stream,crex,myReqBuilder.isDebug()); } } }
true
true
public void processService(CRBinaryRequestBuilder reqBuilder, Map<String,Resolvable> wrappedObjectsToDeploy, OutputStream stream, IResponseTypeSetter responsetypesetter) { CRBinaryRequestBuilder myReqBuilder = reqBuilder; CRResolvableBean crBean = null; CRRequest req; try { req = myReqBuilder.getBinaryRequest(); //DEPLOY OBJECTS TO REQUEST for (Iterator<Map.Entry<String, Resolvable>> i = wrappedObjectsToDeploy.entrySet().iterator() ; i.hasNext() ; ) { Map.Entry<String,Resolvable> entry = (Entry<String,Resolvable>) i.next(); req.addObjectForFilterDeployment((String)entry.getKey(), entry.getValue()); } if(this.crConf.usesContentidUrl()) { if(req.getContentid()==null) { Object obj = reqBuilder.getRequest(); if(obj instanceof HttpServletRequest) { String[] reqURI = ((HttpServletRequest)obj).getRequestURI().split("/"); ArrayList<String> reqList = new ArrayList<String>(Arrays.asList(reqURI)); int index = reqList.indexOf(((HttpServletRequest)obj).getServletPath().replaceAll("/","")); if(reqList.size()>=index+1) { req.setRequestFilter("object.contentid=="+reqList.get(index+1).toString()); } } //contentid=request.getRequestURI().replaceFirst(request.getContextPath()+request.getServletPath()+"/","").replaceAll("/",""); } } // load by url if no contentid if (req.isUrlRequest()) { crBean = rp.getContentByUrl(req); } else { crBean = rp.getContent(req); } if(crBean!=null) { // set mimetype. if(crBean.getMimetype()==null) { CRConfigUtil rpConf = crConf.getRequestProcessorConfig(1); if(crBean.getObj_type().equals(rpConf.getPageType())) { this.contenttype="text/html; charset="+this.response_encoding; log.info("Responding with mimetype: text/html"); } else { log.info("Mimetype has not been set, using standard instead. ("+crBean.getObj_type()+"!="+rpConf.getPageType()+")"); } } else { this.contenttype=crBean.getMimetype()+"; charset="+this.response_encoding; log.info("Responding with mimetype: "+crBean.getMimetype()); } responsetypesetter.setContentType(this.getContentType()); // output data. if (crBean.isBinary()) { log.debug("Size of content: "+crBean.getBinaryContent().length); stream.write(crBean.getBinaryContent()); } else { OutputStreamWriter wr = new OutputStreamWriter(stream, this.response_encoding); String content = crBean.getContent(this.response_encoding); if(Boolean.parseBoolean((String) crConf.get(LIVEEDITORXHTML_KEY))){ //Gentics Content.Node Liveeditor produces non XHTML brakes. Therefore we must replace them before we return the code content = content.replace("<BR>", "</ br>"); } wr.write(content); wr.flush(); wr.close(); } } else { CRException crex = new CRException("NoDataFound","Data could not be found."); this.respondWithError(stream,crex,myReqBuilder.isDebug()); } stream.flush(); stream.close(); } catch (CRException e1) { this.contenttype="text/html; charset="+this.response_encoding; respondWithError((OutputStream)stream,e1,myReqBuilder.isDebug()); e1.printStackTrace(); } catch(Exception e) { log.error("Error while processing service (RESTBinaryContainer)",e); CRException crex = new CRException(e); this.respondWithError(stream,crex,myReqBuilder.isDebug()); } }
public void processService(CRBinaryRequestBuilder reqBuilder, Map<String,Resolvable> wrappedObjectsToDeploy, OutputStream stream, IResponseTypeSetter responsetypesetter) { CRBinaryRequestBuilder myReqBuilder = reqBuilder; CRResolvableBean crBean = null; CRRequest req; try { req = myReqBuilder.getBinaryRequest(); //DEPLOY OBJECTS TO REQUEST for (Iterator<Map.Entry<String, Resolvable>> i = wrappedObjectsToDeploy.entrySet().iterator() ; i.hasNext() ; ) { Map.Entry<String,Resolvable> entry = (Entry<String,Resolvable>) i.next(); req.addObjectForFilterDeployment((String)entry.getKey(), entry.getValue()); } if(this.crConf.usesContentidUrl()) { if(req.getContentid()==null) { Object obj = reqBuilder.getRequest(); if(obj instanceof HttpServletRequest) { String[] reqURI = ((HttpServletRequest)obj).getRequestURI().split("/"); ArrayList<String> reqList = new ArrayList<String>(Arrays.asList(reqURI)); int index = reqList.indexOf(((HttpServletRequest)obj).getServletPath().replaceAll("/","")); if(reqList.size()>=index+1) { req.setRequestFilter("object.contentid=="+reqList.get(index+1).toString()); } } //contentid=request.getRequestURI().replaceFirst(request.getContextPath()+request.getServletPath()+"/","").replaceAll("/",""); } } req.setAttributeArray(new String[]{"mimetype"}); // load by url if no contentid if (req.isUrlRequest()) { crBean = rp.getContentByUrl(req); } else { crBean = rp.getContent(req); } if(crBean!=null) { // set mimetype. if(crBean.getMimetype()==null) { CRConfigUtil rpConf = crConf.getRequestProcessorConfig(1); if(crBean.getObj_type().equals(rpConf.getPageType())) { this.contenttype="text/html; charset="+this.response_encoding; log.info("Responding with mimetype: text/html"); } else { log.info("Mimetype has not been set, using standard instead. ("+crBean.getObj_type()+"!="+rpConf.getPageType()+")"); } } else { this.contenttype=crBean.getMimetype()+"; charset="+this.response_encoding; log.info("Responding with mimetype: "+crBean.getMimetype()); } responsetypesetter.setContentType(this.getContentType()); // output data. if (crBean.isBinary()) { log.debug("Size of content: "+crBean.getBinaryContent().length); stream.write(crBean.getBinaryContent()); } else { OutputStreamWriter wr = new OutputStreamWriter(stream, this.response_encoding); String content = crBean.getContent(this.response_encoding); if(Boolean.parseBoolean((String) crConf.get(LIVEEDITORXHTML_KEY))){ //Gentics Content.Node Liveeditor produces non XHTML brakes. Therefore we must replace them before we return the code content = content.replace("<BR>", "</ br>"); } wr.write(content); wr.flush(); wr.close(); } } else { CRException crex = new CRException("NoDataFound","Data could not be found."); this.respondWithError(stream,crex,myReqBuilder.isDebug()); } stream.flush(); stream.close(); } catch (CRException e1) { this.contenttype="text/html; charset="+this.response_encoding; respondWithError((OutputStream)stream,e1,myReqBuilder.isDebug()); e1.printStackTrace(); } catch(Exception e) { log.error("Error while processing service (RESTBinaryContainer)",e); CRException crex = new CRException(e); this.respondWithError(stream,crex,myReqBuilder.isDebug()); } }
diff --git a/src/com/kelsonprime/oregontrail/controller/Events.java b/src/com/kelsonprime/oregontrail/controller/Events.java index a03e1f4..b97b889 100644 --- a/src/com/kelsonprime/oregontrail/controller/Events.java +++ b/src/com/kelsonprime/oregontrail/controller/Events.java @@ -1,134 +1,127 @@ package com.kelsonprime.oregontrail.controller; import java.util.Random; import javax.swing.JOptionPane; import com.kelsonprime.oregontrail.model.Companion; import com.kelsonprime.oregontrail.model.Farmer; import com.kelsonprime.oregontrail.model.Game; import com.kelsonprime.oregontrail.model.Item; import com.kelsonprime.oregontrail.model.Player; import com.kelsonprime.oregontrail.model.Wagon; /** * Generates random events for the game * * @author kurt * @version $Revision: 1.0 $ */ public class Events { private static Random rand = new Random(); /** * Prevent instantiations of this class */ private Events() { } /** * Generated death * * @param wagon * Wagon * @param companion * Companion */ public static void death(Wagon wagon, Companion companion) { JOptionPane.showMessageDialog(null, companion.getName() + " has suddenly died :("); wagon.removeCompanion(companion); } /** * Randomly calculate an event */ public static void calculateRandomEvent() { } /** * Generates next day */ public static void nextDay(Game game) { int event = rand.nextInt(200); Wagon wagon = game.getWagon(); Player player = wagon.getPlayer(); if (event < 4) ;// Catch Sickness //else if (event < 6) // ;// Random Part Breakdown else if (event < 7){ //Random party member death wagon.killRandomPartyMember(); } - else if (event < 8) - //Random Oxen Death - try { - wagon.add(Item.OXEN, -1); - JOptionPane.showMessageDialog(null, "1 of your Oxen has suddenly died!"); - } catch (UserInputException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } + //else if (event < 8) + // ;//Random Oxen Death else if (event < 11){ //Theft String item = wagon.removeRandomItem(); if (item != null) JOptionPane.showMessageDialog(null, "1 " + item + " has been stolen from you!"); } else if (event < 12) ;//Attacked else if (event < 17){ if (player.getOccupation() instanceof Farmer) try { int gained = rand.nextInt(25)+25; wagon.add(Item.FOOD, gained); JOptionPane.showMessageDialog(null, "You find " + Integer.valueOf(gained) + "lbs of food!"); } catch (UserInputException e) { e.printStackTrace(); } } else if (event < 18) ;// Find Wagon of free stuff else if (event < 20) ;// Oxen Weak (Pace halved) else if (event < 22) ;// Random Party member recovery (health XOR sickness) else ;// Storm lose days } /** * Lose random items * @param wagon Wagon to lose from * @param percent Percent of weight to lose */ public static void loseItems(Wagon wagon, double percent){ int foodCt, clothesCt, bulletCt, axleCt, wheelCt, tongueCt; foodCt = clothesCt = bulletCt = axleCt = wheelCt = tongueCt = 0; String cur; int loseCt = (int) (wagon.countItems() * percent); for (int i = 0; i < loseCt; i++) { cur = wagon.removeRandomItem(); if (cur == null) break; else if (cur.equals("food")) foodCt ++; else if (cur.equals("clothes")) clothesCt ++; else if (cur.equals("bullet")) bulletCt ++; else if (cur.equals("axle")) axleCt ++; else if (cur.equals("tongue")) tongueCt++; else if (cur.equals("wheel")) wheelCt++; } JOptionPane.showMessageDialog(null, "You have lost:\n" + foodCt + "lbs of Food\n" + clothesCt + " Clothes\n" + bulletCt + " Bullets\n" + axleCt + " Spare Axles\n" + wheelCt + " Spare Wheels\n" + tongueCt + " Spare Tongues"); } }
true
true
public static void nextDay(Game game) { int event = rand.nextInt(200); Wagon wagon = game.getWagon(); Player player = wagon.getPlayer(); if (event < 4) ;// Catch Sickness //else if (event < 6) // ;// Random Part Breakdown else if (event < 7){ //Random party member death wagon.killRandomPartyMember(); } else if (event < 8) //Random Oxen Death try { wagon.add(Item.OXEN, -1); JOptionPane.showMessageDialog(null, "1 of your Oxen has suddenly died!"); } catch (UserInputException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } else if (event < 11){ //Theft String item = wagon.removeRandomItem(); if (item != null) JOptionPane.showMessageDialog(null, "1 " + item + " has been stolen from you!"); } else if (event < 12) ;//Attacked else if (event < 17){ if (player.getOccupation() instanceof Farmer) try { int gained = rand.nextInt(25)+25; wagon.add(Item.FOOD, gained); JOptionPane.showMessageDialog(null, "You find " + Integer.valueOf(gained) + "lbs of food!"); } catch (UserInputException e) { e.printStackTrace(); } } else if (event < 18) ;// Find Wagon of free stuff else if (event < 20) ;// Oxen Weak (Pace halved) else if (event < 22) ;// Random Party member recovery (health XOR sickness) else ;// Storm lose days }
public static void nextDay(Game game) { int event = rand.nextInt(200); Wagon wagon = game.getWagon(); Player player = wagon.getPlayer(); if (event < 4) ;// Catch Sickness //else if (event < 6) // ;// Random Part Breakdown else if (event < 7){ //Random party member death wagon.killRandomPartyMember(); } //else if (event < 8) // ;//Random Oxen Death else if (event < 11){ //Theft String item = wagon.removeRandomItem(); if (item != null) JOptionPane.showMessageDialog(null, "1 " + item + " has been stolen from you!"); } else if (event < 12) ;//Attacked else if (event < 17){ if (player.getOccupation() instanceof Farmer) try { int gained = rand.nextInt(25)+25; wagon.add(Item.FOOD, gained); JOptionPane.showMessageDialog(null, "You find " + Integer.valueOf(gained) + "lbs of food!"); } catch (UserInputException e) { e.printStackTrace(); } } else if (event < 18) ;// Find Wagon of free stuff else if (event < 20) ;// Oxen Weak (Pace halved) else if (event < 22) ;// Random Party member recovery (health XOR sickness) else ;// Storm lose days }
diff --git a/src/test/java/net/codestory/CodeStoryResourceTest.java b/src/test/java/net/codestory/CodeStoryResourceTest.java index c7fbafd..40f0f74 100644 --- a/src/test/java/net/codestory/CodeStoryResourceTest.java +++ b/src/test/java/net/codestory/CodeStoryResourceTest.java @@ -1,35 +1,35 @@ package net.codestory; import com.google.common.io.*; import net.gageot.test.rules.*; import org.junit.*; import java.io.*; import java.net.*; import static com.google.common.base.Charsets.*; import static com.jayway.restassured.RestAssured.*; import static net.gageot.test.rules.ServiceRule.*; import static org.fest.assertions.Assertions.*; import static org.hamcrest.Matchers.*; public class CodeStoryResourceTest { @ClassRule public static ServiceRule<CodeStoryServer> codeStoryServer = startWithRandomPort(CodeStoryServer.class); private static int port() { return codeStoryServer.service().getPort(); } @Test public void should_return_commits_json() { given().port(port()).expect().body("author", hasItems("jlm", "dgageot")).when().get("/commits"); } @Test public void should_serve_style_as_less() throws IOException { String css = Resources.toString(new URL("http://localhost:" + port() + "/style.less"), UTF_8); - assertThat(css).contains("background-color: #000000;"); + assertThat(css).contains("color: #ffffff;"); } }
true
true
public void should_serve_style_as_less() throws IOException { String css = Resources.toString(new URL("http://localhost:" + port() + "/style.less"), UTF_8); assertThat(css).contains("background-color: #000000;"); }
public void should_serve_style_as_less() throws IOException { String css = Resources.toString(new URL("http://localhost:" + port() + "/style.less"), UTF_8); assertThat(css).contains("color: #ffffff;"); }
diff --git a/badiff/src/main/java/org/badiff/q/UndoOpQueue.java b/badiff/src/main/java/org/badiff/q/UndoOpQueue.java index 4377ac4..d18e443 100644 --- a/badiff/src/main/java/org/badiff/q/UndoOpQueue.java +++ b/badiff/src/main/java/org/badiff/q/UndoOpQueue.java @@ -1,56 +1,56 @@ /** * badiff - byte array diff - fast pure-java byte-level diffing * * Copyright (c) 2013, Robin Kirkman All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1) Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2) Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3) Neither the name of the badiff 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 HOLDER 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.badiff.q; import org.badiff.Op; public class UndoOpQueue extends FilterOpQueue { public UndoOpQueue(OpQueue source) { super(source); } @Override protected boolean pull() { if(!require(1)) return flush(); - Op e = filtering.get(0); + Op e = filtering.remove(0); Op u; if(e.getOp() == Op.DELETE) u = new Op(Op.INSERT, e.getRun(), e.getData()); else if(e.getOp() == Op.INSERT) u = new Op(Op.DELETE, e.getRun(), e.getData()); else u = e; prepare(u); return true; } }
true
true
protected boolean pull() { if(!require(1)) return flush(); Op e = filtering.get(0); Op u; if(e.getOp() == Op.DELETE) u = new Op(Op.INSERT, e.getRun(), e.getData()); else if(e.getOp() == Op.INSERT) u = new Op(Op.DELETE, e.getRun(), e.getData()); else u = e; prepare(u); return true; }
protected boolean pull() { if(!require(1)) return flush(); Op e = filtering.remove(0); Op u; if(e.getOp() == Op.DELETE) u = new Op(Op.INSERT, e.getRun(), e.getData()); else if(e.getOp() == Op.INSERT) u = new Op(Op.DELETE, e.getRun(), e.getData()); else u = e; prepare(u); return true; }
diff --git a/java/src/org/broadinstitute/sting/gatk/datasources/shards/BlockDelimitedReadShardStrategy.java b/java/src/org/broadinstitute/sting/gatk/datasources/shards/BlockDelimitedReadShardStrategy.java index f0df40a79..9b9d1d36e 100644 --- a/java/src/org/broadinstitute/sting/gatk/datasources/shards/BlockDelimitedReadShardStrategy.java +++ b/java/src/org/broadinstitute/sting/gatk/datasources/shards/BlockDelimitedReadShardStrategy.java @@ -1,161 +1,162 @@ package org.broadinstitute.sting.gatk.datasources.shards; import net.sf.samtools.*; import net.sf.picard.filter.SamRecordFilter; import java.util.*; import org.broadinstitute.sting.utils.StingException; import org.broadinstitute.sting.utils.GenomeLocSortedSet; import org.broadinstitute.sting.gatk.datasources.simpleDataSources.SAMDataSource; import org.broadinstitute.sting.gatk.datasources.simpleDataSources.BlockDrivenSAMDataSource; import org.broadinstitute.sting.gatk.datasources.simpleDataSources.SAMReaderID; /** * A read shard strategy that delimits based on the number of * blocks in the BAM file. * * @author mhanna * @version 0.1 */ public class BlockDelimitedReadShardStrategy extends ReadShardStrategy { /** * What is the maximum number of reads which should go into a read shard. */ protected static final int MAX_READS = 10000; /** * The data source used to shard. */ protected final BlockDrivenSAMDataSource dataSource; private Shard nextShard = null; /** our storage of the genomic locations they'd like to shard over */ private final List<FilePointer> filePointers = new ArrayList<FilePointer>(); /** * Iterator over the list of file pointers. */ private final Iterator<FilePointer> filePointerIterator; /** * The file pointer currently being processed. */ private FilePointer currentFilePointer; /** * Ending position of the last shard in the file. */ private Map<SAMReaderID,Chunk> position; /** * Create a new read shard strategy, loading read shards from the given BAM file. * @param dataSource Data source from which to load shards. */ public BlockDelimitedReadShardStrategy(SAMDataSource dataSource, GenomeLocSortedSet locations) { if(!(dataSource instanceof BlockDrivenSAMDataSource)) throw new StingException("Block-delimited read shard strategy cannot work without a block-driven data source."); this.dataSource = (BlockDrivenSAMDataSource)dataSource; this.position = this.dataSource.getCurrentPosition(); if(locations != null) filePointers.addAll(IntervalSharder.shardIntervals(this.dataSource,locations.toList(),this.dataSource.getNumIndexLevels()-1)); filePointerIterator = filePointers.iterator(); if(filePointerIterator.hasNext()) currentFilePointer = filePointerIterator.next(); advance(); } /** * do we have another read shard? * @return True if any more data is available. False otherwise. */ public boolean hasNext() { return nextShard != null; } /** * Retrieves the next shard, if available. * @return The next shard, if available. * @throws NoSuchElementException if no such shard is available. */ public Shard next() { if(!hasNext()) throw new NoSuchElementException("No next read shard available"); Shard currentShard = nextShard; advance(); return currentShard; } public void advance() { Map<SAMReaderID,List<Chunk>> shardPosition = null; nextShard = null; SamRecordFilter filter = null; if(!filePointers.isEmpty()) { Map<SAMReaderID,List<Chunk>> selectedReaders = new HashMap<SAMReaderID,List<Chunk>>(); while(selectedReaders.size() == 0 && currentFilePointer != null) { shardPosition = dataSource.getFilePointersBounding(currentFilePointer.bin); for(SAMReaderID id: shardPosition.keySet()) { List<Chunk> chunks = shardPosition.get(id); List<Chunk> selectedChunks = new ArrayList<Chunk>(); Chunk filePosition = position.get(id); for(Chunk chunk: chunks) if(filePosition.getChunkStart() <= chunk.getChunkStart()) selectedChunks.add(chunk); else if(filePosition.getChunkStart() > chunk.getChunkStart() && filePosition.getChunkStart() < chunk.getChunkEnd()) { selectedChunks.add(new Chunk(filePosition.getChunkStart(),chunk.getChunkEnd())); } if(selectedChunks.size() > 0) selectedReaders.put(id,selectedChunks); } if(selectedReaders.size() > 0) { + filter = new ReadOverlapFilter(currentFilePointer.locations); BAMFormatAwareShard shard = new BlockDelimitedReadShard(dataSource.getReadsInfo(),selectedReaders,filter,Shard.ShardType.READ); dataSource.fillShard(shard); if(!shard.isBufferEmpty()) { - filter = new ReadOverlapFilter(currentFilePointer.locations); nextShard = shard; break; } } + selectedReaders.clear(); currentFilePointer = filePointerIterator.hasNext() ? filePointerIterator.next() : null; } } else { // TODO: This level of processing should not be necessary. shardPosition = new HashMap<SAMReaderID,List<Chunk>>(); for(Map.Entry<SAMReaderID,Chunk> entry: position.entrySet()) shardPosition.put(entry.getKey(),Collections.singletonList(entry.getValue())); filter = null; BAMFormatAwareShard shard = new BlockDelimitedReadShard(dataSource.getReadsInfo(),shardPosition,filter,Shard.ShardType.READ); dataSource.fillShard(shard); nextShard = !shard.isBufferEmpty() ? shard : null; } this.position = dataSource.getCurrentPosition(); } /** * @throws UnsupportedOperationException always. */ public void remove() { throw new UnsupportedOperationException("Remove not supported"); } /** * Convenience method for using ShardStrategy in an foreach loop. * @return A iterator over shards. */ public Iterator<Shard> iterator() { return this; } }
false
true
public void advance() { Map<SAMReaderID,List<Chunk>> shardPosition = null; nextShard = null; SamRecordFilter filter = null; if(!filePointers.isEmpty()) { Map<SAMReaderID,List<Chunk>> selectedReaders = new HashMap<SAMReaderID,List<Chunk>>(); while(selectedReaders.size() == 0 && currentFilePointer != null) { shardPosition = dataSource.getFilePointersBounding(currentFilePointer.bin); for(SAMReaderID id: shardPosition.keySet()) { List<Chunk> chunks = shardPosition.get(id); List<Chunk> selectedChunks = new ArrayList<Chunk>(); Chunk filePosition = position.get(id); for(Chunk chunk: chunks) if(filePosition.getChunkStart() <= chunk.getChunkStart()) selectedChunks.add(chunk); else if(filePosition.getChunkStart() > chunk.getChunkStart() && filePosition.getChunkStart() < chunk.getChunkEnd()) { selectedChunks.add(new Chunk(filePosition.getChunkStart(),chunk.getChunkEnd())); } if(selectedChunks.size() > 0) selectedReaders.put(id,selectedChunks); } if(selectedReaders.size() > 0) { BAMFormatAwareShard shard = new BlockDelimitedReadShard(dataSource.getReadsInfo(),selectedReaders,filter,Shard.ShardType.READ); dataSource.fillShard(shard); if(!shard.isBufferEmpty()) { filter = new ReadOverlapFilter(currentFilePointer.locations); nextShard = shard; break; } } currentFilePointer = filePointerIterator.hasNext() ? filePointerIterator.next() : null; } } else { // TODO: This level of processing should not be necessary. shardPosition = new HashMap<SAMReaderID,List<Chunk>>(); for(Map.Entry<SAMReaderID,Chunk> entry: position.entrySet()) shardPosition.put(entry.getKey(),Collections.singletonList(entry.getValue())); filter = null; BAMFormatAwareShard shard = new BlockDelimitedReadShard(dataSource.getReadsInfo(),shardPosition,filter,Shard.ShardType.READ); dataSource.fillShard(shard); nextShard = !shard.isBufferEmpty() ? shard : null; } this.position = dataSource.getCurrentPosition(); }
public void advance() { Map<SAMReaderID,List<Chunk>> shardPosition = null; nextShard = null; SamRecordFilter filter = null; if(!filePointers.isEmpty()) { Map<SAMReaderID,List<Chunk>> selectedReaders = new HashMap<SAMReaderID,List<Chunk>>(); while(selectedReaders.size() == 0 && currentFilePointer != null) { shardPosition = dataSource.getFilePointersBounding(currentFilePointer.bin); for(SAMReaderID id: shardPosition.keySet()) { List<Chunk> chunks = shardPosition.get(id); List<Chunk> selectedChunks = new ArrayList<Chunk>(); Chunk filePosition = position.get(id); for(Chunk chunk: chunks) if(filePosition.getChunkStart() <= chunk.getChunkStart()) selectedChunks.add(chunk); else if(filePosition.getChunkStart() > chunk.getChunkStart() && filePosition.getChunkStart() < chunk.getChunkEnd()) { selectedChunks.add(new Chunk(filePosition.getChunkStart(),chunk.getChunkEnd())); } if(selectedChunks.size() > 0) selectedReaders.put(id,selectedChunks); } if(selectedReaders.size() > 0) { filter = new ReadOverlapFilter(currentFilePointer.locations); BAMFormatAwareShard shard = new BlockDelimitedReadShard(dataSource.getReadsInfo(),selectedReaders,filter,Shard.ShardType.READ); dataSource.fillShard(shard); if(!shard.isBufferEmpty()) { nextShard = shard; break; } } selectedReaders.clear(); currentFilePointer = filePointerIterator.hasNext() ? filePointerIterator.next() : null; } } else { // TODO: This level of processing should not be necessary. shardPosition = new HashMap<SAMReaderID,List<Chunk>>(); for(Map.Entry<SAMReaderID,Chunk> entry: position.entrySet()) shardPosition.put(entry.getKey(),Collections.singletonList(entry.getValue())); filter = null; BAMFormatAwareShard shard = new BlockDelimitedReadShard(dataSource.getReadsInfo(),shardPosition,filter,Shard.ShardType.READ); dataSource.fillShard(shard); nextShard = !shard.isBufferEmpty() ? shard : null; } this.position = dataSource.getCurrentPosition(); }
diff --git a/branches/kernel-1.2.x/kernel-impl/src/main/java/org/sakaiproject/content/impl/CollectionAccessFormatter.java b/branches/kernel-1.2.x/kernel-impl/src/main/java/org/sakaiproject/content/impl/CollectionAccessFormatter.java index 96e03eb3..2c998414 100644 --- a/branches/kernel-1.2.x/kernel-impl/src/main/java/org/sakaiproject/content/impl/CollectionAccessFormatter.java +++ b/branches/kernel-1.2.x/kernel-impl/src/main/java/org/sakaiproject/content/impl/CollectionAccessFormatter.java @@ -1,292 +1,292 @@ /********************************************************************************** * $URL$ * $Id$ *********************************************************************************** * * Copyright (c) 2006, 2007, 2008, 2009 Sakai Foundation * * Licensed under the Educational Community 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.osedu.org/licenses/ECL-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.sakaiproject.content.impl; import java.io.PrintWriter; import java.net.URI; import java.util.Collections; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.sakaiproject.component.cover.ServerConfigurationService; import org.sakaiproject.content.api.ContentCollection; import org.sakaiproject.content.api.ContentEntity; import org.sakaiproject.content.cover.ContentHostingService; import org.sakaiproject.entity.api.Entity; import org.sakaiproject.entity.api.Reference; import org.sakaiproject.entity.api.ResourceProperties; import org.sakaiproject.exception.IdUnusedException; import org.sakaiproject.site.api.Site; import org.sakaiproject.site.cover.SiteService; import org.sakaiproject.user.api.User; import org.sakaiproject.user.api.UserNotDefinedException; import org.sakaiproject.user.cover.UserDirectoryService; import org.sakaiproject.util.ResourceLoader; import org.sakaiproject.util.Validator; /** * <p> * CollectionAccessFormatter is formatter for collection access. * </p> */ @SuppressWarnings("deprecation") public class CollectionAccessFormatter { private static final Log M_log = LogFactory.getLog(CollectionAccessFormatter.class); /** * Format the collection as an HTML display. */ @SuppressWarnings({ "unchecked" }) public static void format(ContentCollection x, Reference ref, HttpServletRequest req, HttpServletResponse res, ResourceLoader rb, String accessPointTrue, String accessPointFalse) { // do not allow directory listings for /attachments and its subfolders if(ContentHostingService.isAttachmentResource(x.getId())) { try { res.sendError(HttpServletResponse.SC_NOT_FOUND); return; } catch ( java.io.IOException e ) { return; } } PrintWriter out = null; // don't set the writer until we verify that // getallresources is going to work. boolean printedHeader = false; boolean printedDiv = false; try { res.setContentType("text/html; charset=UTF-8"); out = res.getWriter(); ResourceProperties pl = x.getProperties(); String webappRoot = ServerConfigurationService.getServerUrl(); String skinRepo = ServerConfigurationService.getString("skin.repo", "/library/skin"); String skinName = "default"; String[] parts= StringUtils.split(x.getId(), Entity.SEPARATOR); // Is this a site folder (Resources or Dropbox)? If so, get the site skin if (x.getId().startsWith(org.sakaiproject.content.api.ContentHostingService.COLLECTION_SITE) || x.getId().startsWith(org.sakaiproject.content.api.ContentHostingService.COLLECTION_DROPBOX)) { if (parts.length > 1) { String siteId = parts[1]; try { Site site = SiteService.getSite(siteId); if (site.getSkin() != null) { skinName = site.getSkin(); } } catch (IdUnusedException e) { // Cannot get site - ignore it } } } // Output the headers out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">"); out.println("<html><head>"); out.println("<title>" + rb.getFormattedMessage("colformat.pagetitle", new Object[]{ Validator.escapeHtml(pl.getProperty(ResourceProperties.PROP_DISPLAY_NAME))}) + "</title>"); out.println("<link href=\"" + webappRoot + skinRepo+ "/" + skinName + "/access.css\" type=\"text/css\" rel=\"stylesheet\" media=\"screen\">"); out.println("<script src=\"" + webappRoot + "/library/js/jquery.js\" type=\"text/javascript\">"); out.println("</script>"); out.println("</head><body class=\"specialLink\">"); - out.println("<script type=\"text/javascript\">$(document).ready(function(){resizeFrame();function resizeFrame(){if (window.name != \"\") {var frame = parent.document.getElementById(window.name);if (frame) {var clientH = document.body.clientHeight + 10;$(frame).height(clientH);}}}jQuery.fn.fadeToggle = function(speed, easing, callback){return this.animate({opacity: \'toggle\'}, speed, easing, callback);};if ($(\'.textPanel\').size() < 1){$(\'a#toggler\').hide();}$(\'a#toggler\').click(function(){$(\'.textPanel\').fadeToggle(\'1000\', \'\', \'resizeFrame\');});\n$(\'.file a\').each(function (i){\n$(this).addClass(getFileExtension($(this).attr(\'href\')));\n})\nfunction getFileExtension(filename)\n{\nvar ext = /^.+\\.([^.]+)$/.exec(filename);\nreturn ext == null ? \"\" : ext[1].toLowerCase();\n}\n});</script>"); + out.println("<script type=\"text/javascript\" src=\"/library/js/access.js\"></script>"); out.println("<div class=\"directoryIndex\">"); // for content listing it's best to use a real title out.println("<h3>" + Validator.escapeHtml(pl.getProperty(ResourceProperties.PROP_DISPLAY_NAME)) + "</h3>"); out.println("<p id=\"toggle\"><a id=\"toggler\" href=\"#\">" + rb.getString("colformat.showhide") + "</a></p>"); String folderdesc = pl.getProperty(ResourceProperties.PROP_DESCRIPTION); if (folderdesc != null && !folderdesc.equals("")) out.println("<div class=\"textPanel\">" + folderdesc + "</div>"); out.println("<ul>"); out.println("<li style=\"display:none\">"); out.println("</li>"); printedHeader = true; printedDiv = true; if (parts.length > 2) { // go up a level out.println("<li class=\"upfolder\"><a href=\"../\"><img src=\"/library/image/sakai/folder-up.gif\" alt=\"" + rb.getString("colformat.uplevel.alttext") + "\"/>" + rb.getString("colformat.uplevel") + "</a></li>"); } // Sort the collection items List<ContentEntity> members = x.getMemberResources(); boolean hasCustomSort = false; try { hasCustomSort = x.getProperties().getBooleanProperty(ResourceProperties.PROP_HAS_CUSTOM_SORT); } catch (Exception e) { // use false that's already there } if (hasCustomSort) Collections.sort(members, new ContentHostingComparator(ResourceProperties.PROP_CONTENT_PRIORITY, true)); else Collections.sort(members, new ContentHostingComparator(ResourceProperties.PROP_DISPLAY_NAME, true)); // Iterate through content items URI baseUri = new URI(x.getUrl()); for (ContentEntity content : members) { ResourceProperties properties = content.getProperties(); boolean isCollection = content.isCollection(); String xs = content.getId(); String contentUrl = content.getUrl(); // These both perform the same check in the implementation but we should observe the API. // This also checks to see if a resource is hidden or time limited. if ( isCollection) { if (!ContentHostingService.allowGetCollection(xs)) { continue; } } else { if (!ContentHostingService.allowGetResource(xs)) { continue; } } if (isCollection) { xs = xs.substring(0, xs.length() - 1); xs = xs.substring(xs.lastIndexOf('/') + 1) + '/'; } else { xs = xs.substring(xs.lastIndexOf('/') + 1); } try { // Relativize the URL (canonical item URL relative to canonical collection URL). // Inter alias this will preserve alternate access paths via aliases, e.g. /web/ URI contentUri = new URI(contentUrl); URI relativeUri = baseUri.relativize(contentUri); contentUrl = relativeUri.toString(); if (isCollection) { // Folder String desc = properties.getProperty(ResourceProperties.PROP_DESCRIPTION); if ((desc == null) || desc.equals("")) desc = ""; else desc = "<div class=\"textPanel\">" + desc + "</div>"; out.println("<li class=\"folder\"><a href=\"" + contentUrl + "\">" + Validator.escapeHtml(properties.getProperty(ResourceProperties.PROP_DISPLAY_NAME)) + "</a>" + desc + "</li>"); } else { // File /* String createdBy = getUserProperty(properties, ResourceProperties.PROP_CREATOR).getDisplayName(); Time modTime = properties.getTimeProperty(ResourceProperties.PROP_MODIFIED_DATE); String modifiedTime = modTime.toStringLocalShortDate() + " " + modTime.toStringLocalShort(); ContentResource contentResource = (ContentResource) content; long filesize = ((contentResource.getContentLength() - 1) / 1024) + 1; String filetype = contentResource.getContentType(); */ String desc = properties.getProperty(ResourceProperties.PROP_DESCRIPTION); if ((desc == null) || desc.equals("")) desc = ""; else desc = "<div class=\"textPanel\">" + Validator.escapeHtml(desc) + "</div>"; String resourceType = content.getResourceType().replace('.', '_'); out.println("<li class=\"file\"><a href=\"" + contentUrl + "\" target=_blank class=\"" + resourceType+"\">" + Validator.escapeHtml(properties.getProperty(ResourceProperties.PROP_DISPLAY_NAME)) + "</a>" + desc + "</li>"); } } catch (Exception ignore) { // TODO - what types of failures are being caught here? out.println("<li class=\"file\"><a href=\"" + contentUrl + "\" target=_blank>" + Validator.escapeHtml(xs) + "</a></li>"); } } } catch (Exception e) { M_log.warn("Problem formatting HTML for collection: "+ x.getId(), e); } if (out != null && printedHeader) { out.println("</ul>"); if (printedDiv) out.println("</div>"); out.println("</body></html>"); } } protected static User getUserProperty(ResourceProperties props, String name) { String id = props.getProperty(name); if (id != null) { try { return UserDirectoryService.getUser(id); } catch (UserNotDefinedException e) { } } return null; } }
true
true
public static void format(ContentCollection x, Reference ref, HttpServletRequest req, HttpServletResponse res, ResourceLoader rb, String accessPointTrue, String accessPointFalse) { // do not allow directory listings for /attachments and its subfolders if(ContentHostingService.isAttachmentResource(x.getId())) { try { res.sendError(HttpServletResponse.SC_NOT_FOUND); return; } catch ( java.io.IOException e ) { return; } } PrintWriter out = null; // don't set the writer until we verify that // getallresources is going to work. boolean printedHeader = false; boolean printedDiv = false; try { res.setContentType("text/html; charset=UTF-8"); out = res.getWriter(); ResourceProperties pl = x.getProperties(); String webappRoot = ServerConfigurationService.getServerUrl(); String skinRepo = ServerConfigurationService.getString("skin.repo", "/library/skin"); String skinName = "default"; String[] parts= StringUtils.split(x.getId(), Entity.SEPARATOR); // Is this a site folder (Resources or Dropbox)? If so, get the site skin if (x.getId().startsWith(org.sakaiproject.content.api.ContentHostingService.COLLECTION_SITE) || x.getId().startsWith(org.sakaiproject.content.api.ContentHostingService.COLLECTION_DROPBOX)) { if (parts.length > 1) { String siteId = parts[1]; try { Site site = SiteService.getSite(siteId); if (site.getSkin() != null) { skinName = site.getSkin(); } } catch (IdUnusedException e) { // Cannot get site - ignore it } } } // Output the headers out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">"); out.println("<html><head>"); out.println("<title>" + rb.getFormattedMessage("colformat.pagetitle", new Object[]{ Validator.escapeHtml(pl.getProperty(ResourceProperties.PROP_DISPLAY_NAME))}) + "</title>"); out.println("<link href=\"" + webappRoot + skinRepo+ "/" + skinName + "/access.css\" type=\"text/css\" rel=\"stylesheet\" media=\"screen\">"); out.println("<script src=\"" + webappRoot + "/library/js/jquery.js\" type=\"text/javascript\">"); out.println("</script>"); out.println("</head><body class=\"specialLink\">"); out.println("<script type=\"text/javascript\">$(document).ready(function(){resizeFrame();function resizeFrame(){if (window.name != \"\") {var frame = parent.document.getElementById(window.name);if (frame) {var clientH = document.body.clientHeight + 10;$(frame).height(clientH);}}}jQuery.fn.fadeToggle = function(speed, easing, callback){return this.animate({opacity: \'toggle\'}, speed, easing, callback);};if ($(\'.textPanel\').size() < 1){$(\'a#toggler\').hide();}$(\'a#toggler\').click(function(){$(\'.textPanel\').fadeToggle(\'1000\', \'\', \'resizeFrame\');});\n$(\'.file a\').each(function (i){\n$(this).addClass(getFileExtension($(this).attr(\'href\')));\n})\nfunction getFileExtension(filename)\n{\nvar ext = /^.+\\.([^.]+)$/.exec(filename);\nreturn ext == null ? \"\" : ext[1].toLowerCase();\n}\n});</script>"); out.println("<div class=\"directoryIndex\">"); // for content listing it's best to use a real title out.println("<h3>" + Validator.escapeHtml(pl.getProperty(ResourceProperties.PROP_DISPLAY_NAME)) + "</h3>"); out.println("<p id=\"toggle\"><a id=\"toggler\" href=\"#\">" + rb.getString("colformat.showhide") + "</a></p>"); String folderdesc = pl.getProperty(ResourceProperties.PROP_DESCRIPTION); if (folderdesc != null && !folderdesc.equals("")) out.println("<div class=\"textPanel\">" + folderdesc + "</div>"); out.println("<ul>"); out.println("<li style=\"display:none\">"); out.println("</li>"); printedHeader = true; printedDiv = true; if (parts.length > 2) { // go up a level out.println("<li class=\"upfolder\"><a href=\"../\"><img src=\"/library/image/sakai/folder-up.gif\" alt=\"" + rb.getString("colformat.uplevel.alttext") + "\"/>" + rb.getString("colformat.uplevel") + "</a></li>"); } // Sort the collection items List<ContentEntity> members = x.getMemberResources(); boolean hasCustomSort = false; try { hasCustomSort = x.getProperties().getBooleanProperty(ResourceProperties.PROP_HAS_CUSTOM_SORT); } catch (Exception e) { // use false that's already there } if (hasCustomSort) Collections.sort(members, new ContentHostingComparator(ResourceProperties.PROP_CONTENT_PRIORITY, true)); else Collections.sort(members, new ContentHostingComparator(ResourceProperties.PROP_DISPLAY_NAME, true)); // Iterate through content items URI baseUri = new URI(x.getUrl()); for (ContentEntity content : members) { ResourceProperties properties = content.getProperties(); boolean isCollection = content.isCollection(); String xs = content.getId(); String contentUrl = content.getUrl(); // These both perform the same check in the implementation but we should observe the API. // This also checks to see if a resource is hidden or time limited. if ( isCollection) { if (!ContentHostingService.allowGetCollection(xs)) { continue; } } else { if (!ContentHostingService.allowGetResource(xs)) { continue; } } if (isCollection) { xs = xs.substring(0, xs.length() - 1); xs = xs.substring(xs.lastIndexOf('/') + 1) + '/'; } else { xs = xs.substring(xs.lastIndexOf('/') + 1); } try { // Relativize the URL (canonical item URL relative to canonical collection URL). // Inter alias this will preserve alternate access paths via aliases, e.g. /web/ URI contentUri = new URI(contentUrl); URI relativeUri = baseUri.relativize(contentUri); contentUrl = relativeUri.toString(); if (isCollection) { // Folder String desc = properties.getProperty(ResourceProperties.PROP_DESCRIPTION); if ((desc == null) || desc.equals("")) desc = ""; else desc = "<div class=\"textPanel\">" + desc + "</div>"; out.println("<li class=\"folder\"><a href=\"" + contentUrl + "\">" + Validator.escapeHtml(properties.getProperty(ResourceProperties.PROP_DISPLAY_NAME)) + "</a>" + desc + "</li>"); } else { // File /* String createdBy = getUserProperty(properties, ResourceProperties.PROP_CREATOR).getDisplayName(); Time modTime = properties.getTimeProperty(ResourceProperties.PROP_MODIFIED_DATE); String modifiedTime = modTime.toStringLocalShortDate() + " " + modTime.toStringLocalShort(); ContentResource contentResource = (ContentResource) content; long filesize = ((contentResource.getContentLength() - 1) / 1024) + 1; String filetype = contentResource.getContentType(); */ String desc = properties.getProperty(ResourceProperties.PROP_DESCRIPTION); if ((desc == null) || desc.equals("")) desc = ""; else desc = "<div class=\"textPanel\">" + Validator.escapeHtml(desc) + "</div>"; String resourceType = content.getResourceType().replace('.', '_'); out.println("<li class=\"file\"><a href=\"" + contentUrl + "\" target=_blank class=\"" + resourceType+"\">" + Validator.escapeHtml(properties.getProperty(ResourceProperties.PROP_DISPLAY_NAME)) + "</a>" + desc + "</li>"); } } catch (Exception ignore) { // TODO - what types of failures are being caught here? out.println("<li class=\"file\"><a href=\"" + contentUrl + "\" target=_blank>" + Validator.escapeHtml(xs) + "</a></li>"); } } } catch (Exception e) { M_log.warn("Problem formatting HTML for collection: "+ x.getId(), e); } if (out != null && printedHeader) { out.println("</ul>"); if (printedDiv) out.println("</div>"); out.println("</body></html>"); } }
public static void format(ContentCollection x, Reference ref, HttpServletRequest req, HttpServletResponse res, ResourceLoader rb, String accessPointTrue, String accessPointFalse) { // do not allow directory listings for /attachments and its subfolders if(ContentHostingService.isAttachmentResource(x.getId())) { try { res.sendError(HttpServletResponse.SC_NOT_FOUND); return; } catch ( java.io.IOException e ) { return; } } PrintWriter out = null; // don't set the writer until we verify that // getallresources is going to work. boolean printedHeader = false; boolean printedDiv = false; try { res.setContentType("text/html; charset=UTF-8"); out = res.getWriter(); ResourceProperties pl = x.getProperties(); String webappRoot = ServerConfigurationService.getServerUrl(); String skinRepo = ServerConfigurationService.getString("skin.repo", "/library/skin"); String skinName = "default"; String[] parts= StringUtils.split(x.getId(), Entity.SEPARATOR); // Is this a site folder (Resources or Dropbox)? If so, get the site skin if (x.getId().startsWith(org.sakaiproject.content.api.ContentHostingService.COLLECTION_SITE) || x.getId().startsWith(org.sakaiproject.content.api.ContentHostingService.COLLECTION_DROPBOX)) { if (parts.length > 1) { String siteId = parts[1]; try { Site site = SiteService.getSite(siteId); if (site.getSkin() != null) { skinName = site.getSkin(); } } catch (IdUnusedException e) { // Cannot get site - ignore it } } } // Output the headers out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">"); out.println("<html><head>"); out.println("<title>" + rb.getFormattedMessage("colformat.pagetitle", new Object[]{ Validator.escapeHtml(pl.getProperty(ResourceProperties.PROP_DISPLAY_NAME))}) + "</title>"); out.println("<link href=\"" + webappRoot + skinRepo+ "/" + skinName + "/access.css\" type=\"text/css\" rel=\"stylesheet\" media=\"screen\">"); out.println("<script src=\"" + webappRoot + "/library/js/jquery.js\" type=\"text/javascript\">"); out.println("</script>"); out.println("</head><body class=\"specialLink\">"); out.println("<script type=\"text/javascript\" src=\"/library/js/access.js\"></script>"); out.println("<div class=\"directoryIndex\">"); // for content listing it's best to use a real title out.println("<h3>" + Validator.escapeHtml(pl.getProperty(ResourceProperties.PROP_DISPLAY_NAME)) + "</h3>"); out.println("<p id=\"toggle\"><a id=\"toggler\" href=\"#\">" + rb.getString("colformat.showhide") + "</a></p>"); String folderdesc = pl.getProperty(ResourceProperties.PROP_DESCRIPTION); if (folderdesc != null && !folderdesc.equals("")) out.println("<div class=\"textPanel\">" + folderdesc + "</div>"); out.println("<ul>"); out.println("<li style=\"display:none\">"); out.println("</li>"); printedHeader = true; printedDiv = true; if (parts.length > 2) { // go up a level out.println("<li class=\"upfolder\"><a href=\"../\"><img src=\"/library/image/sakai/folder-up.gif\" alt=\"" + rb.getString("colformat.uplevel.alttext") + "\"/>" + rb.getString("colformat.uplevel") + "</a></li>"); } // Sort the collection items List<ContentEntity> members = x.getMemberResources(); boolean hasCustomSort = false; try { hasCustomSort = x.getProperties().getBooleanProperty(ResourceProperties.PROP_HAS_CUSTOM_SORT); } catch (Exception e) { // use false that's already there } if (hasCustomSort) Collections.sort(members, new ContentHostingComparator(ResourceProperties.PROP_CONTENT_PRIORITY, true)); else Collections.sort(members, new ContentHostingComparator(ResourceProperties.PROP_DISPLAY_NAME, true)); // Iterate through content items URI baseUri = new URI(x.getUrl()); for (ContentEntity content : members) { ResourceProperties properties = content.getProperties(); boolean isCollection = content.isCollection(); String xs = content.getId(); String contentUrl = content.getUrl(); // These both perform the same check in the implementation but we should observe the API. // This also checks to see if a resource is hidden or time limited. if ( isCollection) { if (!ContentHostingService.allowGetCollection(xs)) { continue; } } else { if (!ContentHostingService.allowGetResource(xs)) { continue; } } if (isCollection) { xs = xs.substring(0, xs.length() - 1); xs = xs.substring(xs.lastIndexOf('/') + 1) + '/'; } else { xs = xs.substring(xs.lastIndexOf('/') + 1); } try { // Relativize the URL (canonical item URL relative to canonical collection URL). // Inter alias this will preserve alternate access paths via aliases, e.g. /web/ URI contentUri = new URI(contentUrl); URI relativeUri = baseUri.relativize(contentUri); contentUrl = relativeUri.toString(); if (isCollection) { // Folder String desc = properties.getProperty(ResourceProperties.PROP_DESCRIPTION); if ((desc == null) || desc.equals("")) desc = ""; else desc = "<div class=\"textPanel\">" + desc + "</div>"; out.println("<li class=\"folder\"><a href=\"" + contentUrl + "\">" + Validator.escapeHtml(properties.getProperty(ResourceProperties.PROP_DISPLAY_NAME)) + "</a>" + desc + "</li>"); } else { // File /* String createdBy = getUserProperty(properties, ResourceProperties.PROP_CREATOR).getDisplayName(); Time modTime = properties.getTimeProperty(ResourceProperties.PROP_MODIFIED_DATE); String modifiedTime = modTime.toStringLocalShortDate() + " " + modTime.toStringLocalShort(); ContentResource contentResource = (ContentResource) content; long filesize = ((contentResource.getContentLength() - 1) / 1024) + 1; String filetype = contentResource.getContentType(); */ String desc = properties.getProperty(ResourceProperties.PROP_DESCRIPTION); if ((desc == null) || desc.equals("")) desc = ""; else desc = "<div class=\"textPanel\">" + Validator.escapeHtml(desc) + "</div>"; String resourceType = content.getResourceType().replace('.', '_'); out.println("<li class=\"file\"><a href=\"" + contentUrl + "\" target=_blank class=\"" + resourceType+"\">" + Validator.escapeHtml(properties.getProperty(ResourceProperties.PROP_DISPLAY_NAME)) + "</a>" + desc + "</li>"); } } catch (Exception ignore) { // TODO - what types of failures are being caught here? out.println("<li class=\"file\"><a href=\"" + contentUrl + "\" target=_blank>" + Validator.escapeHtml(xs) + "</a></li>"); } } } catch (Exception e) { M_log.warn("Problem formatting HTML for collection: "+ x.getId(), e); } if (out != null && printedHeader) { out.println("</ul>"); if (printedDiv) out.println("</div>"); out.println("</body></html>"); } }
diff --git a/solr/core/src/test/org/apache/solr/handler/TestReplicationHandler.java b/solr/core/src/test/org/apache/solr/handler/TestReplicationHandler.java index afc5f2649..1cdb72a97 100644 --- a/solr/core/src/test/org/apache/solr/handler/TestReplicationHandler.java +++ b/solr/core/src/test/org/apache/solr/handler/TestReplicationHandler.java @@ -1,1033 +1,1036 @@ /** * 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.solr.handler; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.Writer; import java.net.URL; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.io.IOUtils; import org.apache.lucene.index.IndexReader; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.MatchAllDocsQuery; import org.apache.lucene.search.TopDocs; import org.apache.lucene.store.Directory; import org.apache.lucene.store.SimpleFSDirectory; import org.apache.solr.BaseDistributedSearchTestCase; import org.apache.solr.SolrTestCaseJ4; import org.apache.solr.TestDistributedSearch; import org.apache.solr.client.solrj.SolrServer; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.embedded.JettySolrRunner; import org.apache.solr.client.solrj.impl.HttpSolrServer; import org.apache.solr.client.solrj.request.QueryRequest; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrDocumentList; import org.apache.solr.common.SolrInputDocument; import org.apache.solr.common.params.ModifiableSolrParams; import org.apache.solr.common.util.NamedList; import org.apache.solr.common.util.SimpleOrderedMap; import org.apache.solr.util.AbstractSolrTestCase; import org.junit.AfterClass; import org.junit.BeforeClass; /** * Test for ReplicationHandler * * * @since 1.4 */ // TODO: can this test be sped up? it used to not be so slow... public class TestReplicationHandler extends SolrTestCaseJ4 { private static final String CONF_DIR = "." + File.separator + "solr" + File.separator + "conf" + File.separator; static JettySolrRunner masterJetty, slaveJetty; static SolrServer masterClient, slaveClient; static SolrInstance master = null, slave = null; static String context = "/solr"; // number of docs to index... decremented for each test case to tell if we accidentally reuse // index from previous test method static int nDocs = 500; // TODO: fix this test to not require FSDirectory.. doesnt even work with MockFSDirectory... wtf? static String savedFactory; @BeforeClass public static void beforeClass() throws Exception { savedFactory = System.getProperty("solr.DirectoryFactory"); System.setProperty("solr.directoryFactory", "solr.StandardDirectoryFactory"); master = new SolrInstance("master", null); master.setUp(); masterJetty = createJetty(master); masterClient = createNewSolrServer(masterJetty.getLocalPort()); slave = new SolrInstance("slave", masterJetty.getLocalPort()); slave.setUp(); slaveJetty = createJetty(slave); slaveClient = createNewSolrServer(slaveJetty.getLocalPort()); } public void clearIndexWithReplication() throws Exception { NamedList res = query("*:*", masterClient); SolrDocumentList docs = (SolrDocumentList)res.get("response"); if (docs.getNumFound() != 0) { masterClient.deleteByQuery("*:*"); masterClient.commit(); // wait for replication to sync res = rQuery(0, "*:*", slaveClient); assertEquals(0, ((SolrDocumentList) res.get("response")).getNumFound()); } } @AfterClass public static void afterClass() throws Exception { masterJetty.stop(); slaveJetty.stop(); master.tearDown(); slave.tearDown(); if (savedFactory == null) { System.clearProperty("solr.directoryFactory"); } else { System.setProperty("solr.directoryFactory", savedFactory); } } private static JettySolrRunner createJetty(SolrInstance instance) throws Exception { System.setProperty("solr.data.dir", instance.getDataDir()); JettySolrRunner jetty = new JettySolrRunner(instance.getHomeDir(), "/solr", 0); jetty.start(); return jetty; } private static SolrServer createNewSolrServer(int port) { try { // setup the server... String url = "http://localhost:" + port + context; HttpSolrServer s = new HttpSolrServer(url); s.setDefaultMaxConnectionsPerHost(100); s.setMaxTotalConnections(100); return s; } catch (Exception ex) { throw new RuntimeException(ex); } } int index(SolrServer s, Object... fields) throws Exception { SolrInputDocument doc = new SolrInputDocument(); for (int i = 0; i < fields.length; i += 2) { doc.addField((String) (fields[i]), fields[i + 1]); } return s.add(doc).getStatus(); } NamedList query(String query, SolrServer s) throws SolrServerException { NamedList res = new SimpleOrderedMap(); ModifiableSolrParams params = new ModifiableSolrParams(); params.add("q", query); QueryResponse qres = s.query(params); res = qres.getResponse(); return res; } /** will sleep up to 30 seconds, looking for expectedDocCount */ private NamedList rQuery(int expectedDocCount, String query, SolrServer server) throws Exception { int timeSlept = 0; NamedList res = null; SolrDocumentList docList = null; do { res = query(query, server); docList = (SolrDocumentList) res.get("response"); timeSlept += 100; Thread.sleep(100); } while(docList.getNumFound() != expectedDocCount && timeSlept < 30000); return res; } private NamedList<Object> getDetails(SolrServer s) throws Exception { ModifiableSolrParams params = new ModifiableSolrParams(); params.set("command","details"); params.set("qt","/replication"); QueryRequest req = new QueryRequest(params); NamedList<Object> res = s.request(req); assertNotNull("null response from server", res); @SuppressWarnings("unchecked") NamedList<Object> details = (NamedList<Object>) res.get("details"); assertNotNull("null details", details); return details; } private NamedList<Object> getCommits(SolrServer s) throws Exception { ModifiableSolrParams params = new ModifiableSolrParams(); params.set("command","commits"); params.set("qt","/replication"); QueryRequest req = new QueryRequest(params); NamedList<Object> res = s.request(req); assertNotNull("null response from server", res); return res; } private NamedList<Object> getIndexVersion(SolrServer s) throws Exception { ModifiableSolrParams params = new ModifiableSolrParams(); params.set("command","indexversion"); params.set("qt","/replication"); QueryRequest req = new QueryRequest(params); NamedList<Object> res = s.request(req); assertNotNull("null response from server", res); return res; } private NamedList<Object> reloadCore(SolrServer s, String core) throws Exception { ModifiableSolrParams params = new ModifiableSolrParams(); params.set("action","reload"); params.set("core", core); params.set("qt","/admin/cores"); QueryRequest req = new QueryRequest(params); NamedList<Object> res = s.request(req); assertNotNull("null response from server", res); return res; } public void test() throws Exception { doTestReplicateAfterCoreReload(); doTestDetails(); doTestReplicateAfterWrite2Slave(); doTestIndexAndConfigReplication(); doTestStopPoll(); doTestSnapPullWithMasterUrl(); doTestReplicateAfterStartup(); doTestIndexAndConfigAliasReplication(); doTestBackup(); } private void doTestDetails() throws Exception { { NamedList<Object> details = getDetails(masterClient); assertEquals("master isMaster?", "true", details.get("isMaster")); assertEquals("master isSlave?", "false", details.get("isSlave")); assertNotNull("master has master section", details.get("master")); } { NamedList<Object> details = getDetails(slaveClient); assertEquals("slave isMaster?", "false", details.get("isMaster")); assertEquals("slave isSlave?", "true", details.get("isSlave")); assertNotNull("slave has slave section", details.get("slave")); } SolrInstance repeater = null; JettySolrRunner repeaterJetty = null; SolrServer repeaterClient = null; try { repeater = new SolrInstance("repeater", masterJetty.getLocalPort()); repeater.setUp(); repeaterJetty = createJetty(repeater); repeaterClient = createNewSolrServer(repeaterJetty.getLocalPort()); NamedList<Object> details = getDetails(repeaterClient); assertEquals("repeater isMaster?", "true", details.get("isMaster")); assertEquals("repeater isSlave?", "true", details.get("isSlave")); assertNotNull("repeater has master section", details.get("master")); assertNotNull("repeater has slave section", details.get("slave")); } finally { try { if (repeaterJetty != null) repeaterJetty.stop(); } catch (Exception e) { /* :NOOP: */ } try { if (repeater != null) repeater.tearDown(); } catch (Exception e) { /* :NOOP: */ } } } private void doTestReplicateAfterWrite2Slave() throws Exception { clearIndexWithReplication(); nDocs--; for (int i = 0; i < nDocs; i++) { index(masterClient, "id", i, "name", "name = " + i); } String masterUrl = "http://localhost:" + masterJetty.getLocalPort() + "/solr/replication?command=disableReplication"; URL url = new URL(masterUrl); InputStream stream = url.openStream(); try { stream.close(); } catch (IOException e) { //e.printStackTrace(); } masterClient.commit(); NamedList masterQueryRsp = rQuery(nDocs, "*:*", masterClient); SolrDocumentList masterQueryResult = (SolrDocumentList) masterQueryRsp.get("response"); assertEquals(nDocs, masterQueryResult.getNumFound()); // Make sure that both the index version and index generation on the slave is // higher than that of the master, just to make the test harder. index(slaveClient, "id", 551, "name", "name = " + 551); slaveClient.commit(true, true); index(slaveClient, "id", 552, "name", "name = " + 552); slaveClient.commit(true, true); index(slaveClient, "id", 553, "name", "name = " + 553); slaveClient.commit(true, true); index(slaveClient, "id", 554, "name", "name = " + 554); slaveClient.commit(true, true); index(slaveClient, "id", 555, "name", "name = " + 555); slaveClient.commit(true, true); //this doc is added to slave so it should show an item w/ that result SolrDocumentList slaveQueryResult = null; NamedList slaveQueryRsp; slaveQueryRsp = rQuery(1, "id:555", slaveClient); slaveQueryResult = (SolrDocumentList) slaveQueryRsp.get("response"); assertEquals(1, slaveQueryResult.getNumFound()); masterUrl = "http://localhost:" + masterJetty.getLocalPort() + "/solr/replication?command=enableReplication"; url = new URL(masterUrl); stream = url.openStream(); try { stream.close(); } catch (IOException e) { //e.printStackTrace(); } //the slave should have done a full copy of the index so the doc with id:555 should not be there in the slave now slaveQueryRsp = rQuery(0, "id:555", slaveClient); slaveQueryResult = (SolrDocumentList) slaveQueryRsp.get("response"); assertEquals(0, slaveQueryResult.getNumFound()); // make sure we replicated the correct index from the master slaveQueryRsp = rQuery(nDocs, "*:*", slaveClient); slaveQueryResult = (SolrDocumentList) slaveQueryRsp.get("response"); assertEquals(nDocs, slaveQueryResult.getNumFound()); } private void doTestIndexAndConfigReplication() throws Exception { clearIndexWithReplication(); nDocs--; for (int i = 0; i < nDocs; i++) index(masterClient, "id", i, "name", "name = " + i); masterClient.commit(); NamedList masterQueryRsp = rQuery(nDocs, "*:*", masterClient); SolrDocumentList masterQueryResult = (SolrDocumentList) masterQueryRsp.get("response"); assertEquals(nDocs, masterQueryResult.getNumFound()); //get docs from slave and check if number is equal to master NamedList slaveQueryRsp = rQuery(nDocs, "*:*", slaveClient); SolrDocumentList slaveQueryResult = (SolrDocumentList) slaveQueryRsp.get("response"); assertEquals(nDocs, slaveQueryResult.getNumFound()); //compare results String cmp = BaseDistributedSearchTestCase.compare(masterQueryResult, slaveQueryResult, 0, null); assertEquals(null, cmp); //start config files replication test masterClient.deleteByQuery("*:*"); masterClient.commit(); //change the schema on master master.copyConfigFile(CONF_DIR + "schema-replication2.xml", "schema.xml"); masterJetty.stop(); masterJetty = createJetty(master); masterClient = createNewSolrServer(masterJetty.getLocalPort()); slave.setTestPort(masterJetty.getLocalPort()); slave.copyConfigFile(slave.getSolrConfigFile(), "solrconfig.xml"); slaveJetty.stop(); slaveJetty = createJetty(slave); slaveClient = createNewSolrServer(slaveJetty.getLocalPort()); //add a doc with new field and commit on master to trigger snappull from slave. index(masterClient, "id", "2000", "name", "name = " + 2000, "newname", "newname = " + 2000); masterClient.commit(); NamedList masterQueryRsp2 = rQuery(1, "*:*", masterClient); SolrDocumentList masterQueryResult2 = (SolrDocumentList) masterQueryRsp2.get("response"); assertEquals(1, masterQueryResult2.getNumFound()); slaveQueryRsp = rQuery(1, "*:*", slaveClient); SolrDocument d = ((SolrDocumentList) slaveQueryRsp.get("response")).get(0); assertEquals("newname = 2000", (String) d.getFieldValue("newname")); } private void doTestStopPoll() throws Exception { clearIndexWithReplication(); // Test: // setup master/slave. // stop polling on slave, add a doc to master and verify slave hasn't picked it. nDocs--; for (int i = 0; i < nDocs; i++) index(masterClient, "id", i, "name", "name = " + i); masterClient.commit(); NamedList masterQueryRsp = rQuery(nDocs, "*:*", masterClient); SolrDocumentList masterQueryResult = (SolrDocumentList) masterQueryRsp.get("response"); assertEquals(nDocs, masterQueryResult.getNumFound()); //get docs from slave and check if number is equal to master NamedList slaveQueryRsp = rQuery(nDocs, "*:*", slaveClient); SolrDocumentList slaveQueryResult = (SolrDocumentList) slaveQueryRsp.get("response"); assertEquals(nDocs, slaveQueryResult.getNumFound()); //compare results String cmp = BaseDistributedSearchTestCase.compare(masterQueryResult, slaveQueryResult, 0, null); assertEquals(null, cmp); // start stop polling test String slaveURL = "http://localhost:" + slaveJetty.getLocalPort() + "/solr/replication?command=disablepoll"; URL url = new URL(slaveURL); InputStream stream = url.openStream(); try { stream.close(); } catch (IOException e) { //e.printStackTrace(); } index(masterClient, "id", 501, "name", "name = " + 501); masterClient.commit(); //get docs from master and check if number is equal to master masterQueryRsp = rQuery(nDocs+1, "*:*", masterClient); masterQueryResult = (SolrDocumentList) masterQueryRsp.get("response"); assertEquals(nDocs+1, masterQueryResult.getNumFound()); // NOTE: this test is wierd, we want to verify it DOESNT replicate... // for now, add a sleep for this.., but the logic is wierd. Thread.sleep(3000); //get docs from slave and check if number is not equal to master; polling is disabled slaveQueryRsp = rQuery(nDocs, "*:*", slaveClient); slaveQueryResult = (SolrDocumentList) slaveQueryRsp.get("response"); assertEquals(nDocs, slaveQueryResult.getNumFound()); // re-enable replication slaveURL = "http://localhost:" + slaveJetty.getLocalPort() + "/solr/replication?command=enablepoll"; url = new URL(slaveURL); stream = url.openStream(); try { stream.close(); } catch (IOException e) { //e.printStackTrace(); } slaveQueryRsp = rQuery(nDocs+1, "*:*", slaveClient); slaveQueryResult = (SolrDocumentList) slaveQueryRsp.get("response"); assertEquals(nDocs+1, slaveQueryResult.getNumFound()); } private void doTestSnapPullWithMasterUrl() throws Exception { //change solrconfig on slave //this has no entry for pollinginterval slave.copyConfigFile(CONF_DIR + "solrconfig-slave1.xml", "solrconfig.xml"); slaveJetty.stop(); slaveJetty = createJetty(slave); slaveClient = createNewSolrServer(slaveJetty.getLocalPort()); masterClient.deleteByQuery("*:*"); nDocs--; for (int i = 0; i < nDocs; i++) index(masterClient, "id", i, "name", "name = " + i); masterClient.commit(); NamedList masterQueryRsp = rQuery(nDocs, "*:*", masterClient); SolrDocumentList masterQueryResult = (SolrDocumentList) masterQueryRsp.get("response"); assertEquals(nDocs, masterQueryResult.getNumFound()); // snappull String masterUrl = "http://localhost:" + slaveJetty.getLocalPort() + "/solr/replication?command=fetchindex&masterUrl="; masterUrl += "http://localhost:" + masterJetty.getLocalPort() + "/solr/replication"; URL url = new URL(masterUrl); InputStream stream = url.openStream(); try { stream.close(); } catch (IOException e) { //e.printStackTrace(); } //get docs from slave and check if number is equal to master NamedList slaveQueryRsp = rQuery(nDocs, "*:*", slaveClient); SolrDocumentList slaveQueryResult = (SolrDocumentList) slaveQueryRsp.get("response"); assertEquals(nDocs, slaveQueryResult.getNumFound()); //compare results String cmp = BaseDistributedSearchTestCase.compare(masterQueryResult, slaveQueryResult, 0, null); assertEquals(null, cmp); System.out.println("replicate slave to master"); // snappull from the slave to the master for (int i = 0; i < 3; i++) index(slaveClient, "id", i, "name", "name = " + i); slaveClient.commit(); masterUrl = "http://localhost:" + masterJetty.getLocalPort() + "/solr/replication?command=fetchindex&masterUrl="; masterUrl += "http://localhost:" + slaveJetty.getLocalPort() + "/solr/replication"; url = new URL(masterUrl); stream = url.openStream(); try { stream.close(); } catch (IOException e) { //e.printStackTrace(); } // get the details // just ensures we don't get an exception NamedList<Object> details = getDetails(masterClient); //System.out.println("details:" + details); // NOTE: at this point, the slave is not polling any more // restore it. slave.copyConfigFile(CONF_DIR + "solrconfig-slave.xml", "solrconfig.xml"); slaveJetty.stop(); slaveJetty = createJetty(slave); slaveClient = createNewSolrServer(slaveJetty.getLocalPort()); } private void doTestReplicateAfterStartup() throws Exception { //stop slave slaveJetty.stop(); nDocs--; masterClient.deleteByQuery("*:*"); for (int i = 0; i < nDocs; i++) index(masterClient, "id", i, "name", "name = " + i); masterClient.commit(); NamedList masterQueryRsp = rQuery(nDocs, "*:*", masterClient); SolrDocumentList masterQueryResult = (SolrDocumentList) masterQueryRsp.get("response"); assertEquals(nDocs, masterQueryResult.getNumFound()); //change solrconfig having 'replicateAfter startup' option on master master.copyConfigFile(CONF_DIR + "solrconfig-master2.xml", "solrconfig.xml"); masterJetty.stop(); masterJetty = createJetty(master); masterClient = createNewSolrServer(masterJetty.getLocalPort()); slave.setTestPort(masterJetty.getLocalPort()); slave.copyConfigFile(slave.getSolrConfigFile(), "solrconfig.xml"); //start slave slaveJetty = createJetty(slave); slaveClient = createNewSolrServer(slaveJetty.getLocalPort()); //get docs from slave and check if number is equal to master NamedList slaveQueryRsp = rQuery(nDocs, "*:*", slaveClient); SolrDocumentList slaveQueryResult = (SolrDocumentList) slaveQueryRsp.get("response"); assertEquals(nDocs, slaveQueryResult.getNumFound()); //compare results String cmp = BaseDistributedSearchTestCase.compare(masterQueryResult, slaveQueryResult, 0, null); assertEquals(null, cmp); // NOTE: the master only replicates after startup now! // revert that change. master.copyConfigFile(CONF_DIR + "solrconfig-master.xml", "solrconfig.xml"); masterJetty.stop(); masterJetty = createJetty(master); masterClient = createNewSolrServer(masterJetty.getLocalPort()); slave.setTestPort(masterJetty.getLocalPort()); slave.copyConfigFile(slave.getSolrConfigFile(), "solrconfig.xml"); //start slave slaveJetty.stop(); slaveJetty = createJetty(slave); slaveClient = createNewSolrServer(slaveJetty.getLocalPort()); } private void doTestReplicateAfterCoreReload() throws Exception { //stop slave slaveJetty.stop(); masterClient.deleteByQuery("*:*"); for (int i = 0; i < 10; i++) index(masterClient, "id", i, "name", "name = " + i); masterClient.commit(); NamedList masterQueryRsp = rQuery(10, "*:*", masterClient); SolrDocumentList masterQueryResult = (SolrDocumentList) masterQueryRsp.get("response"); assertEquals(10, masterQueryResult.getNumFound()); //change solrconfig having 'replicateAfter startup' option on master master.copyConfigFile(CONF_DIR + "solrconfig-master3.xml", "solrconfig.xml"); masterJetty.stop(); masterJetty = createJetty(master); masterClient = createNewSolrServer(masterJetty.getLocalPort()); slave.setTestPort(masterJetty.getLocalPort()); slave.copyConfigFile(slave.getSolrConfigFile(), "solrconfig.xml"); //start slave slaveJetty = createJetty(slave); slaveClient = createNewSolrServer(slaveJetty.getLocalPort()); //get docs from slave and check if number is equal to master NamedList slaveQueryRsp = rQuery(10, "*:*", slaveClient); SolrDocumentList slaveQueryResult = (SolrDocumentList) slaveQueryRsp.get("response"); assertEquals(10, slaveQueryResult.getNumFound()); //compare results String cmp = BaseDistributedSearchTestCase.compare(masterQueryResult, slaveQueryResult, 0, null); assertEquals(null, cmp); Object version = getIndexVersion(masterClient).get("indexversion"); NamedList<Object> commits = getCommits(masterClient); reloadCore(masterClient, "collection1"); assertEquals(version, getIndexVersion(masterClient).get("indexversion")); assertEquals(commits.get("commits"), getCommits(masterClient).get("commits")); index(masterClient, "id", 110, "name", "name = 1"); index(masterClient, "id", 120, "name", "name = 2"); masterClient.commit(); NamedList resp = rQuery(12, "*:*", masterClient); masterQueryResult = (SolrDocumentList) resp.get("response"); assertEquals(12, masterQueryResult.getNumFound()); //get docs from slave and check if number is equal to master slaveQueryRsp = rQuery(12, "*:*", slaveClient); slaveQueryResult = (SolrDocumentList) slaveQueryRsp.get("response"); assertEquals(12, slaveQueryResult.getNumFound()); // NOTE: revert config on master. master.copyConfigFile(CONF_DIR + "solrconfig-master.xml", "solrconfig.xml"); masterJetty.stop(); masterJetty = createJetty(master); masterClient = createNewSolrServer(masterJetty.getLocalPort()); slave.setTestPort(masterJetty.getLocalPort()); slave.copyConfigFile(slave.getSolrConfigFile(), "solrconfig.xml"); //start slave slaveJetty.stop(); slaveJetty = createJetty(slave); slaveClient = createNewSolrServer(slaveJetty.getLocalPort()); } private void doTestIndexAndConfigAliasReplication() throws Exception { clearIndexWithReplication(); nDocs--; for (int i = 0; i < nDocs; i++) index(masterClient, "id", i, "name", "name = " + i); masterClient.commit(); NamedList masterQueryRsp = rQuery(nDocs, "*:*", masterClient); SolrDocumentList masterQueryResult = (SolrDocumentList) masterQueryRsp.get("response"); assertEquals(nDocs, masterQueryResult.getNumFound()); //get docs from slave and check if number is equal to master NamedList slaveQueryRsp = rQuery(nDocs, "*:*", slaveClient); SolrDocumentList slaveQueryResult = (SolrDocumentList) slaveQueryRsp.get("response"); assertEquals(nDocs, slaveQueryResult.getNumFound()); //compare results String cmp = BaseDistributedSearchTestCase.compare(masterQueryResult, slaveQueryResult, 0, null); assertEquals(null, cmp); //start config files replication test //clear master index masterClient.deleteByQuery("*:*"); masterClient.commit(); //change solrconfig on master master.copyConfigFile(CONF_DIR + "solrconfig-master1.xml", "solrconfig.xml"); //change schema on master master.copyConfigFile(CONF_DIR + "schema-replication2.xml", "schema.xml"); //keep a copy of the new schema master.copyConfigFile(CONF_DIR + "schema-replication2.xml", "schema-replication2.xml"); masterJetty.stop(); masterJetty = createJetty(master); masterClient = createNewSolrServer(masterJetty.getLocalPort()); slave.setTestPort(masterJetty.getLocalPort()); slave.copyConfigFile(slave.getSolrConfigFile(), "solrconfig.xml"); slaveJetty.stop(); slaveJetty = createJetty(slave); slaveClient = createNewSolrServer(slaveJetty.getLocalPort()); //add a doc with new field and commit on master to trigger snappull from slave. index(masterClient, "id", "2000", "name", "name = " + 2000, "newname", "newname = " + 2000); masterClient.commit(); NamedList masterQueryRsp2 = rQuery(1, "*:*", masterClient); SolrDocumentList masterQueryResult2 = (SolrDocumentList) masterQueryRsp2.get("response"); assertEquals(1, masterQueryResult2.getNumFound()); NamedList slaveQueryRsp2 = rQuery(1, "*:*", slaveClient); SolrDocumentList slaveQueryResult2 = (SolrDocumentList) slaveQueryRsp2.get("response"); assertEquals(1, slaveQueryResult2.getNumFound()); index(slaveClient, "id", "2000", "name", "name = " + 2001, "newname", "newname = " + 2001); slaveClient.commit(); slaveQueryRsp = rQuery(1, "*:*", slaveClient); SolrDocument d = ((SolrDocumentList) slaveQueryRsp.get("response")).get(0); assertEquals("newname = 2001", (String) d.getFieldValue("newname")); } private void doTestBackup() throws Exception { String configFile = "solrconfig-master1.xml"; boolean addNumberToKeepInRequest = true; String backupKeepParamName = ReplicationHandler.NUMBER_BACKUPS_TO_KEEP_REQUEST_PARAM; if(random().nextBoolean()) { configFile = "solrconfig-master1-keepOneBackup.xml"; addNumberToKeepInRequest = false; } masterJetty.stop(); master.copyConfigFile(CONF_DIR + configFile, "solrconfig.xml"); masterJetty = createJetty(master); masterClient = createNewSolrServer(masterJetty.getLocalPort()); nDocs--; masterClient.deleteByQuery("*:*"); for (int i = 0; i < nDocs; i++) index(masterClient, "id", i, "name", "name = " + i); masterClient.commit(); class BackupThread extends Thread { volatile String fail = null; final boolean addNumberToKeepInRequest; String backupKeepParamName; BackupThread(boolean addNumberToKeepInRequest, String backupKeepParamName) { this.addNumberToKeepInRequest = addNumberToKeepInRequest; this.backupKeepParamName = backupKeepParamName; } @Override public void run() { String masterUrl = "http://localhost:" + masterJetty.getLocalPort() + "/solr/replication?command=" + ReplicationHandler.CMD_BACKUP + (addNumberToKeepInRequest ? "&" + backupKeepParamName + "=1" : ""); URL url; InputStream stream = null; try { url = new URL(masterUrl); stream = url.openStream(); stream.close(); } catch (Exception e) { fail = e.getMessage(); } finally { IOUtils.closeQuietly(stream); } }; }; class CheckStatus extends Thread { volatile String fail = null; volatile String response = null; volatile boolean success = false; volatile String backupTimestamp = null; final String lastBackupTimestamp; final Pattern p = Pattern.compile("<str name=\"snapshotCompletedAt\">(.*?)</str>"); CheckStatus(String lastBackupTimestamp) { this.lastBackupTimestamp = lastBackupTimestamp; } @Override public void run() { String masterUrl = "http://localhost:" + masterJetty.getLocalPort() + "/solr/replication?command=" + ReplicationHandler.CMD_DETAILS; URL url; InputStream stream = null; try { url = new URL(masterUrl); stream = url.openStream(); response = IOUtils.toString(stream, "UTF-8"); if(response.contains("<str name=\"status\">success</str>")) { Matcher m = p.matcher(response); if(!m.find()) { fail("could not find the completed timestamp in response."); } backupTimestamp = m.group(1); if(!backupTimestamp.equals(lastBackupTimestamp)) { success = true; } } stream.close(); } catch (Exception e) { fail = e.getMessage(); } finally { IOUtils.closeQuietly(stream); } }; }; File[] snapDir = new File[2]; String firstBackupTimestamp = null; for(int i=0 ; i<2 ; i++) { BackupThread backupThread = null; if(!addNumberToKeepInRequest) { if(random().nextBoolean()) { masterClient.commit(); + } else { + backupThread = new BackupThread(addNumberToKeepInRequest, backupKeepParamName); + backupThread.start(); } } else { backupThread = new BackupThread(addNumberToKeepInRequest, backupKeepParamName); backupThread.start(); } File dataDir = new File(master.getDataDir()); int waitCnt = 0; CheckStatus checkStatus = new CheckStatus(firstBackupTimestamp); while(true) { checkStatus.run(); if(checkStatus.fail != null) { fail(checkStatus.fail); } if(checkStatus.success) { if(i==0) { firstBackupTimestamp = checkStatus.backupTimestamp; Thread.sleep(1000); //ensure the next backup will have a different timestamp. } break; } Thread.sleep(200); if(waitCnt == 10) { fail("Backup success not detected:" + checkStatus.response); } waitCnt++; } if(backupThread!= null && backupThread.fail != null) { fail(backupThread.fail); } File[] files = dataDir.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { if(name.startsWith("snapshot")) { return true; } return false; } }); assertEquals(1, files.length); snapDir[i] = files[0]; Directory dir = new SimpleFSDirectory(snapDir[i].getAbsoluteFile()); IndexReader reader = IndexReader.open(dir); IndexSearcher searcher = new IndexSearcher(reader); TopDocs hits = searcher.search(new MatchAllDocsQuery(), 1); assertEquals(nDocs, hits.totalHits); reader.close(); dir.close(); } if(snapDir[0].exists()) { fail("The first backup should have been cleaned up because " + backupKeepParamName + " was set to 1."); } for(int i=0 ; i< snapDir.length ; i++) { AbstractSolrTestCase.recurseDelete(snapDir[i]); // clean up the snap dir } } /* character copy of file using UTF-8 */ private static void copyFile(File src, File dst) throws IOException { copyFile(src, dst, null); } /** * character copy of file using UTF-8. If port is non-null, will be substituted any time "TEST_PORT" is found. */ private static void copyFile(File src, File dst, Integer port) throws IOException { BufferedReader in = new BufferedReader(new FileReader(src)); Writer out = new FileWriter(dst); for (String line = in.readLine(); null != line; line = in.readLine()) { if (null != port) line = line.replace("TEST_PORT", port.toString()); out.write(line); } in.close(); out.close(); } private static class SolrInstance { private String name; private Integer testPort; private File homeDir; private File confDir; private File dataDir; /** * @param name used to pick new solr home dir, as well as which * "solrconfig-${name}.xml" file gets copied * to solrconfig.xml in new conf dir. * @param testPort if not null, used as a replacement for * TEST_PORT in the cloned config files. */ public SolrInstance(String name, Integer testPort) { this.name = name; this.testPort = testPort; } public String getHomeDir() { return homeDir.toString(); } public String getSchemaFile() { return CONF_DIR + "schema-replication1.xml"; } public String getConfDir() { return confDir.toString(); } public String getDataDir() { return dataDir.toString(); } public String getSolrConfigFile() { return CONF_DIR + "solrconfig-"+name+".xml"; } /** If it needs to change */ public void setTestPort(Integer testPort) { this.testPort = testPort; } public void setUp() throws Exception { System.setProperty("solr.test.sys.prop1", "propone"); System.setProperty("solr.test.sys.prop2", "proptwo"); File home = new File(TEMP_DIR, getClass().getName() + "-" + System.currentTimeMillis()); homeDir = new File(home, name); dataDir = new File(homeDir, "data"); confDir = new File(homeDir, "conf"); homeDir.mkdirs(); dataDir.mkdirs(); confDir.mkdirs(); copyConfigFile(getSolrConfigFile(), "solrconfig.xml"); copyConfigFile(getSchemaFile(), "schema.xml"); } public void tearDown() throws Exception { AbstractSolrTestCase.recurseDelete(homeDir); } public void copyConfigFile(String srcFile, String destFile) throws IOException { copyFile(getFile(srcFile), new File(confDir, destFile), testPort); } } }
true
true
private void doTestBackup() throws Exception { String configFile = "solrconfig-master1.xml"; boolean addNumberToKeepInRequest = true; String backupKeepParamName = ReplicationHandler.NUMBER_BACKUPS_TO_KEEP_REQUEST_PARAM; if(random().nextBoolean()) { configFile = "solrconfig-master1-keepOneBackup.xml"; addNumberToKeepInRequest = false; } masterJetty.stop(); master.copyConfigFile(CONF_DIR + configFile, "solrconfig.xml"); masterJetty = createJetty(master); masterClient = createNewSolrServer(masterJetty.getLocalPort()); nDocs--; masterClient.deleteByQuery("*:*"); for (int i = 0; i < nDocs; i++) index(masterClient, "id", i, "name", "name = " + i); masterClient.commit(); class BackupThread extends Thread { volatile String fail = null; final boolean addNumberToKeepInRequest; String backupKeepParamName; BackupThread(boolean addNumberToKeepInRequest, String backupKeepParamName) { this.addNumberToKeepInRequest = addNumberToKeepInRequest; this.backupKeepParamName = backupKeepParamName; } @Override public void run() { String masterUrl = "http://localhost:" + masterJetty.getLocalPort() + "/solr/replication?command=" + ReplicationHandler.CMD_BACKUP + (addNumberToKeepInRequest ? "&" + backupKeepParamName + "=1" : ""); URL url; InputStream stream = null; try { url = new URL(masterUrl); stream = url.openStream(); stream.close(); } catch (Exception e) { fail = e.getMessage(); } finally { IOUtils.closeQuietly(stream); } }; }; class CheckStatus extends Thread { volatile String fail = null; volatile String response = null; volatile boolean success = false; volatile String backupTimestamp = null; final String lastBackupTimestamp; final Pattern p = Pattern.compile("<str name=\"snapshotCompletedAt\">(.*?)</str>"); CheckStatus(String lastBackupTimestamp) { this.lastBackupTimestamp = lastBackupTimestamp; } @Override public void run() { String masterUrl = "http://localhost:" + masterJetty.getLocalPort() + "/solr/replication?command=" + ReplicationHandler.CMD_DETAILS; URL url; InputStream stream = null; try { url = new URL(masterUrl); stream = url.openStream(); response = IOUtils.toString(stream, "UTF-8"); if(response.contains("<str name=\"status\">success</str>")) { Matcher m = p.matcher(response); if(!m.find()) { fail("could not find the completed timestamp in response."); } backupTimestamp = m.group(1); if(!backupTimestamp.equals(lastBackupTimestamp)) { success = true; } } stream.close(); } catch (Exception e) { fail = e.getMessage(); } finally { IOUtils.closeQuietly(stream); } }; }; File[] snapDir = new File[2]; String firstBackupTimestamp = null; for(int i=0 ; i<2 ; i++) { BackupThread backupThread = null; if(!addNumberToKeepInRequest) { if(random().nextBoolean()) { masterClient.commit(); } } else { backupThread = new BackupThread(addNumberToKeepInRequest, backupKeepParamName); backupThread.start(); } File dataDir = new File(master.getDataDir()); int waitCnt = 0; CheckStatus checkStatus = new CheckStatus(firstBackupTimestamp); while(true) { checkStatus.run(); if(checkStatus.fail != null) { fail(checkStatus.fail); } if(checkStatus.success) { if(i==0) { firstBackupTimestamp = checkStatus.backupTimestamp; Thread.sleep(1000); //ensure the next backup will have a different timestamp. } break; } Thread.sleep(200); if(waitCnt == 10) { fail("Backup success not detected:" + checkStatus.response); } waitCnt++; } if(backupThread!= null && backupThread.fail != null) { fail(backupThread.fail); } File[] files = dataDir.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { if(name.startsWith("snapshot")) { return true; } return false; } }); assertEquals(1, files.length); snapDir[i] = files[0]; Directory dir = new SimpleFSDirectory(snapDir[i].getAbsoluteFile()); IndexReader reader = IndexReader.open(dir); IndexSearcher searcher = new IndexSearcher(reader); TopDocs hits = searcher.search(new MatchAllDocsQuery(), 1); assertEquals(nDocs, hits.totalHits); reader.close(); dir.close(); } if(snapDir[0].exists()) { fail("The first backup should have been cleaned up because " + backupKeepParamName + " was set to 1."); } for(int i=0 ; i< snapDir.length ; i++) { AbstractSolrTestCase.recurseDelete(snapDir[i]); // clean up the snap dir } }
private void doTestBackup() throws Exception { String configFile = "solrconfig-master1.xml"; boolean addNumberToKeepInRequest = true; String backupKeepParamName = ReplicationHandler.NUMBER_BACKUPS_TO_KEEP_REQUEST_PARAM; if(random().nextBoolean()) { configFile = "solrconfig-master1-keepOneBackup.xml"; addNumberToKeepInRequest = false; } masterJetty.stop(); master.copyConfigFile(CONF_DIR + configFile, "solrconfig.xml"); masterJetty = createJetty(master); masterClient = createNewSolrServer(masterJetty.getLocalPort()); nDocs--; masterClient.deleteByQuery("*:*"); for (int i = 0; i < nDocs; i++) index(masterClient, "id", i, "name", "name = " + i); masterClient.commit(); class BackupThread extends Thread { volatile String fail = null; final boolean addNumberToKeepInRequest; String backupKeepParamName; BackupThread(boolean addNumberToKeepInRequest, String backupKeepParamName) { this.addNumberToKeepInRequest = addNumberToKeepInRequest; this.backupKeepParamName = backupKeepParamName; } @Override public void run() { String masterUrl = "http://localhost:" + masterJetty.getLocalPort() + "/solr/replication?command=" + ReplicationHandler.CMD_BACKUP + (addNumberToKeepInRequest ? "&" + backupKeepParamName + "=1" : ""); URL url; InputStream stream = null; try { url = new URL(masterUrl); stream = url.openStream(); stream.close(); } catch (Exception e) { fail = e.getMessage(); } finally { IOUtils.closeQuietly(stream); } }; }; class CheckStatus extends Thread { volatile String fail = null; volatile String response = null; volatile boolean success = false; volatile String backupTimestamp = null; final String lastBackupTimestamp; final Pattern p = Pattern.compile("<str name=\"snapshotCompletedAt\">(.*?)</str>"); CheckStatus(String lastBackupTimestamp) { this.lastBackupTimestamp = lastBackupTimestamp; } @Override public void run() { String masterUrl = "http://localhost:" + masterJetty.getLocalPort() + "/solr/replication?command=" + ReplicationHandler.CMD_DETAILS; URL url; InputStream stream = null; try { url = new URL(masterUrl); stream = url.openStream(); response = IOUtils.toString(stream, "UTF-8"); if(response.contains("<str name=\"status\">success</str>")) { Matcher m = p.matcher(response); if(!m.find()) { fail("could not find the completed timestamp in response."); } backupTimestamp = m.group(1); if(!backupTimestamp.equals(lastBackupTimestamp)) { success = true; } } stream.close(); } catch (Exception e) { fail = e.getMessage(); } finally { IOUtils.closeQuietly(stream); } }; }; File[] snapDir = new File[2]; String firstBackupTimestamp = null; for(int i=0 ; i<2 ; i++) { BackupThread backupThread = null; if(!addNumberToKeepInRequest) { if(random().nextBoolean()) { masterClient.commit(); } else { backupThread = new BackupThread(addNumberToKeepInRequest, backupKeepParamName); backupThread.start(); } } else { backupThread = new BackupThread(addNumberToKeepInRequest, backupKeepParamName); backupThread.start(); } File dataDir = new File(master.getDataDir()); int waitCnt = 0; CheckStatus checkStatus = new CheckStatus(firstBackupTimestamp); while(true) { checkStatus.run(); if(checkStatus.fail != null) { fail(checkStatus.fail); } if(checkStatus.success) { if(i==0) { firstBackupTimestamp = checkStatus.backupTimestamp; Thread.sleep(1000); //ensure the next backup will have a different timestamp. } break; } Thread.sleep(200); if(waitCnt == 10) { fail("Backup success not detected:" + checkStatus.response); } waitCnt++; } if(backupThread!= null && backupThread.fail != null) { fail(backupThread.fail); } File[] files = dataDir.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { if(name.startsWith("snapshot")) { return true; } return false; } }); assertEquals(1, files.length); snapDir[i] = files[0]; Directory dir = new SimpleFSDirectory(snapDir[i].getAbsoluteFile()); IndexReader reader = IndexReader.open(dir); IndexSearcher searcher = new IndexSearcher(reader); TopDocs hits = searcher.search(new MatchAllDocsQuery(), 1); assertEquals(nDocs, hits.totalHits); reader.close(); dir.close(); } if(snapDir[0].exists()) { fail("The first backup should have been cleaned up because " + backupKeepParamName + " was set to 1."); } for(int i=0 ; i< snapDir.length ; i++) { AbstractSolrTestCase.recurseDelete(snapDir[i]); // clean up the snap dir } }
diff --git a/hazelcast-client/src/main/java/com/hazelcast/client/ExecutorServiceClientProxy.java b/hazelcast-client/src/main/java/com/hazelcast/client/ExecutorServiceClientProxy.java index 675dddbb..b9d8a6cb 100644 --- a/hazelcast-client/src/main/java/com/hazelcast/client/ExecutorServiceClientProxy.java +++ b/hazelcast-client/src/main/java/com/hazelcast/client/ExecutorServiceClientProxy.java @@ -1,231 +1,231 @@ /* * Copyright (c) 2008-2010, Hazel Ltd. 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 com.hazelcast.client; import com.hazelcast.core.DistributedTask; import com.hazelcast.core.Member; import com.hazelcast.core.MemberLeftException; import com.hazelcast.core.MultiTask; import com.hazelcast.impl.ClientDistributedTask; import com.hazelcast.impl.ClusterOperation; import com.hazelcast.impl.ExecutionManagerCallback; import com.hazelcast.impl.InnerFutureTask; import java.io.Serializable; import java.util.*; import java.util.concurrent.*; import static com.hazelcast.client.Serializer.toObject; public class ExecutorServiceClientProxy implements ExecutorService { final ProxyHelper proxyHelper; final ExecutorService callBackExecutors = Executors.newFixedThreadPool(5); public ExecutorServiceClientProxy(HazelcastClient client, String name) { proxyHelper = new ProxyHelper(name, client); } public void shutdown() { } public List<Runnable> shutdownNow() { return new ArrayList<Runnable>(); } public boolean isShutdown() { throw new UnsupportedOperationException(); } public boolean isTerminated() { throw new UnsupportedOperationException(); } public boolean awaitTermination(long l, TimeUnit timeUnit) throws InterruptedException { return false; } public <T> Future<T> submit(Callable<T> callable) { return submit(new DistributedTask(callable)); } private <T> Future<T> submit(DistributedTask dt) { ClientDistributedTask cdt = null; InnerFutureTask inner = (InnerFutureTask) dt.getInner(); check(inner.getCallable()); if (dt instanceof MultiTask) { if (inner.getMembers() == null) { Set<Member> set = new HashSet<Member>(); set.add(inner.getMember()); cdt = new ClientDistributedTask(inner.getCallable(), null, set, null); } } if (cdt == null) { cdt = new ClientDistributedTask(inner.getCallable(), inner.getMember(), inner.getMembers(), inner.getKey()); } return submit(dt, cdt); } private <T> void check(Object o) { if (o == null) { throw new NullPointerException("Object cannot be null."); } if (!(o instanceof Serializable)) { throw new IllegalArgumentException(o.getClass().getName() + " is not Serializable."); } } private Future submit(final DistributedTask dt, final ClientDistributedTask cdt) { final Packet request = proxyHelper.prepareRequest(ClusterOperation.EXECUTE, cdt, null); final InnerFutureTask inner = (InnerFutureTask) dt.getInner(); final Call call = new Call(ProxyHelper.newCallId(), request) { public void onDisconnect(final Member member) { setResponse(new MemberLeftException(member)); } public void setResponse(Object response) { super.setResponse(response); if (dt.getExecutionCallback() != null) { callBackExecutors.execute(new Runnable() { public void run() { dt.getExecutionCallback().done(dt); } }); } } }; inner.setExecutionManagerCallback(new ExecutionManagerCallback() { public boolean cancel(boolean mayInterruptIfRunning) { return false; } public void get() throws InterruptedException, ExecutionException { try { Object response = call.getResponse(); handle(response); } catch (Throwable e) { handle(e); } } public void get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException { try { Object response = call.getResponse(timeout, unit); handle(response); } catch (Throwable e) { handle(e); } } private void handle(Object response) { Object result = response; if (response == null) { - inner.innerSetException(new TimeoutException()); + inner.innerSetException(new TimeoutException(), false); } else { if (response instanceof Packet) { Packet responsePacket = (Packet) response; result = toObject(responsePacket.getValue()); } if (result instanceof MemberLeftException) { MemberLeftException memberLeftException = (MemberLeftException) result; inner.innerSetMemberLeft(memberLeftException.getMember()); } else if (result instanceof Throwable) { - inner.innerSetException((Throwable) result); + inner.innerSetException((Throwable) result, true); } else { if (dt instanceof MultiTask) { if (result != null) { Collection colResults = (Collection) result; for (Object obj : colResults) { inner.innerSet(obj); } } else { inner.innerSet(result); } } else { inner.innerSet(result); } } } inner.innerDone(); } }); proxyHelper.sendCall(call); return dt; } public <T> Future<T> submit(Runnable runnable, T t) { if (runnable instanceof DistributedTask) { return submit((DistributedTask) runnable); } else { return submit(DistributedTask.callable(runnable, t)); } } public Future<?> submit(Runnable runnable) { return submit(runnable, null); } public List<Future> invokeAll(Collection tasks) throws InterruptedException { // Inspired to JDK7 if (tasks == null) throw new NullPointerException(); List<Future> futures = new ArrayList<Future>(tasks.size()); boolean done = false; try { for (Object command : tasks) { futures.add(submit((Callable) command)); } for (Future f : futures) { if (!f.isDone()) { try { f.get(); } catch (CancellationException ignore) { } catch (ExecutionException ignore) { } } } done = true; return futures; } finally { if (!done) for (Future f : futures) f.cancel(true); } } public List invokeAll(Collection tasks, long timeout, TimeUnit unit) throws InterruptedException { throw new UnsupportedOperationException(); } public Object invokeAny(Collection tasks) throws InterruptedException, ExecutionException { throw new UnsupportedOperationException(); } public Object invokeAny(Collection tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { throw new UnsupportedOperationException(); } public void execute(Runnable runnable) { submit(runnable, null); } }
false
true
private Future submit(final DistributedTask dt, final ClientDistributedTask cdt) { final Packet request = proxyHelper.prepareRequest(ClusterOperation.EXECUTE, cdt, null); final InnerFutureTask inner = (InnerFutureTask) dt.getInner(); final Call call = new Call(ProxyHelper.newCallId(), request) { public void onDisconnect(final Member member) { setResponse(new MemberLeftException(member)); } public void setResponse(Object response) { super.setResponse(response); if (dt.getExecutionCallback() != null) { callBackExecutors.execute(new Runnable() { public void run() { dt.getExecutionCallback().done(dt); } }); } } }; inner.setExecutionManagerCallback(new ExecutionManagerCallback() { public boolean cancel(boolean mayInterruptIfRunning) { return false; } public void get() throws InterruptedException, ExecutionException { try { Object response = call.getResponse(); handle(response); } catch (Throwable e) { handle(e); } } public void get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException { try { Object response = call.getResponse(timeout, unit); handle(response); } catch (Throwable e) { handle(e); } } private void handle(Object response) { Object result = response; if (response == null) { inner.innerSetException(new TimeoutException()); } else { if (response instanceof Packet) { Packet responsePacket = (Packet) response; result = toObject(responsePacket.getValue()); } if (result instanceof MemberLeftException) { MemberLeftException memberLeftException = (MemberLeftException) result; inner.innerSetMemberLeft(memberLeftException.getMember()); } else if (result instanceof Throwable) { inner.innerSetException((Throwable) result); } else { if (dt instanceof MultiTask) { if (result != null) { Collection colResults = (Collection) result; for (Object obj : colResults) { inner.innerSet(obj); } } else { inner.innerSet(result); } } else { inner.innerSet(result); } } } inner.innerDone(); } }); proxyHelper.sendCall(call); return dt; }
private Future submit(final DistributedTask dt, final ClientDistributedTask cdt) { final Packet request = proxyHelper.prepareRequest(ClusterOperation.EXECUTE, cdt, null); final InnerFutureTask inner = (InnerFutureTask) dt.getInner(); final Call call = new Call(ProxyHelper.newCallId(), request) { public void onDisconnect(final Member member) { setResponse(new MemberLeftException(member)); } public void setResponse(Object response) { super.setResponse(response); if (dt.getExecutionCallback() != null) { callBackExecutors.execute(new Runnable() { public void run() { dt.getExecutionCallback().done(dt); } }); } } }; inner.setExecutionManagerCallback(new ExecutionManagerCallback() { public boolean cancel(boolean mayInterruptIfRunning) { return false; } public void get() throws InterruptedException, ExecutionException { try { Object response = call.getResponse(); handle(response); } catch (Throwable e) { handle(e); } } public void get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException { try { Object response = call.getResponse(timeout, unit); handle(response); } catch (Throwable e) { handle(e); } } private void handle(Object response) { Object result = response; if (response == null) { inner.innerSetException(new TimeoutException(), false); } else { if (response instanceof Packet) { Packet responsePacket = (Packet) response; result = toObject(responsePacket.getValue()); } if (result instanceof MemberLeftException) { MemberLeftException memberLeftException = (MemberLeftException) result; inner.innerSetMemberLeft(memberLeftException.getMember()); } else if (result instanceof Throwable) { inner.innerSetException((Throwable) result, true); } else { if (dt instanceof MultiTask) { if (result != null) { Collection colResults = (Collection) result; for (Object obj : colResults) { inner.innerSet(obj); } } else { inner.innerSet(result); } } else { inner.innerSet(result); } } } inner.innerDone(); } }); proxyHelper.sendCall(call); return dt; }
diff --git a/src/de/fuberlin/optimierung/LLVM_Optimization.java b/src/de/fuberlin/optimierung/LLVM_Optimization.java index eacf22e6..a13f8ee5 100644 --- a/src/de/fuberlin/optimierung/LLVM_Optimization.java +++ b/src/de/fuberlin/optimierung/LLVM_Optimization.java @@ -1,232 +1,231 @@ package de.fuberlin.optimierung; import java.io.*; import java.util.LinkedList; public class LLVM_Optimization implements ILLVM_Optimization { private String code = ""; private String beforeFunc = ""; private LinkedList<LLVM_Function> functions; public static final boolean DEBUG = true; public static final boolean STATISTIC = true; public LLVM_Optimization(){ functions = new LinkedList<LLVM_Function>(); } private void parseCode() throws LLVM_OptimizationException{ // Splitte in Funktionen String[] functions = this.code.split("define "); this.beforeFunc = functions[0]; for (int i = 1; i < functions.length; i++) { this.functions.add(new LLVM_Function(functions[i])); } } private String optimizeCode() throws LLVM_OptimizationException{ // Code steht als String in this.code // Starte Optimierung this.parseCode(); String outputLLVM = this.beforeFunc; if(STATISTIC) { System.out.println("Before optimization\n"+getStatistic()); } // Gehe Funktionen durch for(LLVM_Function tmp : this.functions) { // Erstelle Flussgraph tmp.createFlowGraph(); // Optimierungsfunktionen tmp.createRegisterMaps(); //Constant Folding tmp.constantFolding(); // Reaching vor Lebendigkeitsanalyse // Koennen tote Stores entstehen, also vor live variable analysis tmp.reachingAnalysis(); // Dead register elimination tmp.eliminateDeadRegisters(); tmp.eliminateDeadBlocks(); // CommonExpressions // Store/Load-Paare muessen vorher eliminiert werden, also nach reaching analysis tmp.removeCommonExpressions(); - tmp.reachingAnalysis(); // Globale Lebendigkeitsanalyse fuer Store, Load tmp.globalLiveVariableAnalysis(); // Entferne Bloecke, die nur unbedingten Sprungbefehl enthalten tmp.deleteEmptyBlocks(); tmp.strengthReduction(); // Optimierte Ausgabe tmp.updateUnnamedLabelNames(); outputLLVM += tmp.toString(); //createGraph("func"+i, tmp); } if(STATISTIC) { System.out.println("After optimization\n"+getStatistic()); } return outputLLVM; } private void createGraph(String filename, LLVM_Function func) { try{ FileWriter fstream = new FileWriter(System.getProperty("user.home")+"/"+filename+".dot"); BufferedWriter out = new BufferedWriter(fstream); out.write(func.toGraph()); out.close(); Runtime r = Runtime.getRuntime(); String[] cmds = {"/bin/sh", "-c", "/opt/local/bin/dot -Tjpg "+System.getProperty("user.home")+"/"+filename+".dot -o "+System.getProperty("user.home")+"/"+filename+".jpg"}; Process proc = r.exec(cmds); InputStream stderr = proc.getErrorStream(); InputStreamReader isr = new InputStreamReader(stderr); BufferedReader br = new BufferedReader(new InputStreamReader(proc.getInputStream())); String line = null; while((line = br.readLine()) != null) { System.out.println(line); } BufferedReader brerr = new BufferedReader(isr); while((line = brerr.readLine()) != null) { System.err.println(line); } }catch(Exception e){ System.err.println(e.getMessage()); } } private void readCodeFromFile(String fileName){ try { BufferedReader fileReader = new BufferedReader(new FileReader(fileName)); String line = ""; while((line = fileReader.readLine()) != null) { this.code = this.code + line; this.code = this.code + "\n"; } fileReader.close(); } catch (IOException e) { e.printStackTrace(); } } public String optimizeCodeFromString(String code) throws LLVM_OptimizationException{ this.code = code; return this.optimizeCode(); } public String optimizeCodeFromFile(String fileName) throws LLVM_OptimizationException{ this.readCodeFromFile(fileName); return this.optimizeCode(); } public String getCode(){ return this.code; } private int getBlockCount(){ int count = 0; for (LLVM_Function f : functions) { count += f.getBlocks().size(); } return count; } private int getCommandsCount(){ int count = 0; for (LLVM_Function f : functions) { for(LLVM_Block c : f.getBlocks()) { count += c.countCommands(); } } return count; } public String getStatistic(){ String out = ""; out += "############################\n"; out += "Count Functions: "+functions.size()+"\n"; out += "Count Blocks: "+getBlockCount()+"\n"; out += "Count Commands: "+getCommandsCount()+"\n"; out += "############################\n"; return out; } public static void main(String args[]) { ILLVM_Optimization optimization = new LLVM_Optimization(); try{ if(args.length>0) { String optimizedCode = optimization.optimizeCodeFromFile(args[0]); System.out.println(optimizedCode); } else { optimization = new LLVM_Optimization(); //String optimizedCode = optimization.optimizeCodeFromFile("input/de/fuberlin/optimierung/llvm_test.llvm"); //String optimizedCode = optimization.optimizeCodeFromFile("input/de/fuberlin/optimierung/llvm_constant_folding1"); //String optimizedCode = optimization.optimizeCodeFromFile("input/de/fuberlin/optimierung/llvm_cf_prop_deadb"); //String optimizedCode = optimization.optimizeCodeFromFile("input/de/fuberlin/optimierung/llvm_lebendigkeit_global1"); //String optimizedCode = optimization.optimizeCodeFromFile("input/de/fuberlin/optimierung/llvm_dag"); //String optimizedCode = optimization.optimizeCodeFromFile("input/de/fuberlin/optimierung/llvm_dead_block"); //String optimizedCode = optimization.optimizeCodeFromFile("input/de/fuberlin/optimierung/llvm_localsub_registerprop"); //String optimizedCode = optimization.optimizeCodeFromFile("input/de/fuberlin/optimierung/llvm_array"); //String optimizedCode = optimization.optimizeCodeFromFile("input/de/fuberlin/optimierung/llvm_parsertest1"); //String optimizedCode = optimization.optimizeCodeFromFile("input/de/fuberlin/optimierung/llvm_clangdemo"); //String optimizedCode = optimization.optimizeCodeFromFile("input/de/fuberlin/optimierung/strength_reduction_argv.s");//test_new.ll"); //String optimizedCode = optimization.optimizeCodeFromFile("input/de/fuberlin/optimierung/llvm_maschco");//test_new.ll"); //String optimizedCode = optimization.optimizeCodeFromFile("input/de/fuberlin/optimierung/srem_test.ll"); String optimizedCode = optimization.optimizeCodeFromFile("input/de/fuberlin/optimierung/test1_double_2blocks.s"); System.out.println("###########################################################"); System.out.println("################## Optimization Input #####################"); System.out.println("###########################################################"); System.out.println(optimization.getCode()); System.out.println("###########################################################"); System.out.println("################## Optimization Output ####################"); System.out.println("###########################################################"); System.out.println(optimizedCode); } } catch (LLVM_OptimizationException e){ // Unoptimierten Code weiterleiten System.out.println(optimization.getCode()); } catch (Exception e) { e.printStackTrace(); } } }
true
true
private String optimizeCode() throws LLVM_OptimizationException{ // Code steht als String in this.code // Starte Optimierung this.parseCode(); String outputLLVM = this.beforeFunc; if(STATISTIC) { System.out.println("Before optimization\n"+getStatistic()); } // Gehe Funktionen durch for(LLVM_Function tmp : this.functions) { // Erstelle Flussgraph tmp.createFlowGraph(); // Optimierungsfunktionen tmp.createRegisterMaps(); //Constant Folding tmp.constantFolding(); // Reaching vor Lebendigkeitsanalyse // Koennen tote Stores entstehen, also vor live variable analysis tmp.reachingAnalysis(); // Dead register elimination tmp.eliminateDeadRegisters(); tmp.eliminateDeadBlocks(); // CommonExpressions // Store/Load-Paare muessen vorher eliminiert werden, also nach reaching analysis tmp.removeCommonExpressions(); tmp.reachingAnalysis(); // Globale Lebendigkeitsanalyse fuer Store, Load tmp.globalLiveVariableAnalysis(); // Entferne Bloecke, die nur unbedingten Sprungbefehl enthalten tmp.deleteEmptyBlocks(); tmp.strengthReduction(); // Optimierte Ausgabe tmp.updateUnnamedLabelNames(); outputLLVM += tmp.toString(); //createGraph("func"+i, tmp); } if(STATISTIC) { System.out.println("After optimization\n"+getStatistic()); } return outputLLVM; }
private String optimizeCode() throws LLVM_OptimizationException{ // Code steht als String in this.code // Starte Optimierung this.parseCode(); String outputLLVM = this.beforeFunc; if(STATISTIC) { System.out.println("Before optimization\n"+getStatistic()); } // Gehe Funktionen durch for(LLVM_Function tmp : this.functions) { // Erstelle Flussgraph tmp.createFlowGraph(); // Optimierungsfunktionen tmp.createRegisterMaps(); //Constant Folding tmp.constantFolding(); // Reaching vor Lebendigkeitsanalyse // Koennen tote Stores entstehen, also vor live variable analysis tmp.reachingAnalysis(); // Dead register elimination tmp.eliminateDeadRegisters(); tmp.eliminateDeadBlocks(); // CommonExpressions // Store/Load-Paare muessen vorher eliminiert werden, also nach reaching analysis tmp.removeCommonExpressions(); // Globale Lebendigkeitsanalyse fuer Store, Load tmp.globalLiveVariableAnalysis(); // Entferne Bloecke, die nur unbedingten Sprungbefehl enthalten tmp.deleteEmptyBlocks(); tmp.strengthReduction(); // Optimierte Ausgabe tmp.updateUnnamedLabelNames(); outputLLVM += tmp.toString(); //createGraph("func"+i, tmp); } if(STATISTIC) { System.out.println("After optimization\n"+getStatistic()); } return outputLLVM; }
diff --git a/src/es/mompes/supermanager/util/EnumPosicion.java b/src/es/mompes/supermanager/util/EnumPosicion.java index 5ba7f09..4184f8e 100644 --- a/src/es/mompes/supermanager/util/EnumPosicion.java +++ b/src/es/mompes/supermanager/util/EnumPosicion.java @@ -1,76 +1,76 @@ package es.mompes.supermanager.util; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; /** * Refleja las posiciones que puede ocupar un jugador en un equipo. * * @author Juan Mompe�n Esteban * */ public enum EnumPosicion implements Serializable { /** * El base del equipo. */ BASE, /** * El alero del equipo. */ ALERO, /** * El p�vot del equipo. */ PIVOT; /** * Transforma el enum en un string. * * @return El equivalente al enum en string. */ public String toString() { switch (this) { case BASE: return "Base"; case ALERO: return "Alero"; case PIVOT: - return "Pívot"; + return "P�vot"; default: return ""; } } /** * Devuelve el equivalente en el enumerado del string. * * @param position * Posici�n consultada. * @return Equivalente en el enumerado o null si no hay coincidencia. */ public static final EnumPosicion stringToPosition(final String position) { for (EnumPosicion enumPosition : EnumPosicion.values()) { if (enumPosition.toString().toUpperCase() .equals(position.toUpperCase())) { return enumPosition; } } return null; } protected void readObject(ObjectInputStream aInputStream) throws ClassNotFoundException, IOException { // always perform the default de-serialization first aInputStream.defaultReadObject(); } protected void writeObject(ObjectOutputStream aOutputStream) throws IOException { // perform the default serialization for all non-transient, non-static // fields aOutputStream.defaultWriteObject(); } }
true
true
public String toString() { switch (this) { case BASE: return "Base"; case ALERO: return "Alero"; case PIVOT: return "Pívot"; default: return ""; } }
public String toString() { switch (this) { case BASE: return "Base"; case ALERO: return "Alero"; case PIVOT: return "P�vot"; default: return ""; } }
diff --git a/src/org/broad/igv/data/GenomeSummaryData.java b/src/org/broad/igv/data/GenomeSummaryData.java index 14bf1ccc..1b3fe257 100644 --- a/src/org/broad/igv/data/GenomeSummaryData.java +++ b/src/org/broad/igv/data/GenomeSummaryData.java @@ -1,175 +1,176 @@ /* * Copyright (c) 2007-2011 by The Broad Institute of MIT and Harvard. All Rights Reserved. * * This software is licensed under the terms of the GNU Lesser General Public License (LGPL), * Version 2.1 which is available at http://www.opensource.org/licenses/lgpl-2.1.php. * * THE SOFTWARE IS PROVIDED "AS IS." THE BROAD AND MIT MAKE NO REPRESENTATIONS OR * WARRANTES OF ANY KIND CONCERNING THE SOFTWARE, EXPRESS OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, WHETHER * OR NOT DISCOVERABLE. IN NO EVENT SHALL THE BROAD OR MIT, OR THEIR RESPECTIVE * TRUSTEES, DIRECTORS, OFFICERS, EMPLOYEES, AND AFFILIATES BE LIABLE FOR ANY DAMAGES * OF ANY KIND, INCLUDING, WITHOUT LIMITATION, INCIDENTAL OR CONSEQUENTIAL DAMAGES, * ECONOMIC DAMAGES OR INJURY TO PROPERTY AND LOST PROFITS, REGARDLESS OF WHETHER * THE BROAD OR MIT SHALL BE ADVISED, SHALL HAVE OTHER REASON TO KNOW, OR IN FACT * SHALL KNOW OF THE POSSIBILITY OF THE FOREGOING. */ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.broad.igv.data; import org.apache.log4j.Logger; import org.broad.igv.feature.genome.Genome; import org.broad.igv.tdf.Accumulator; import org.broad.igv.track.WindowFunction; import org.broad.igv.util.collections.FloatArrayList; import org.broad.igv.util.collections.IntArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author jrobinso */ public class GenomeSummaryData { private static Logger log = Logger.getLogger(GenomeSummaryData.class); // Genome coordinates are in KB private static final double locationUnit = 1000.0; /** * Number of virtual pixels */ int nPixels = 1000; Genome genome; String[] samples; Map<String, Map<String, FloatArrayList>> dataMap = new HashMap(); Map<String, IntArrayList> locationMap; int[] locations; Map<String, float[]> data; int nDataPts = 0; /** * Scale in KB / pixel */ double scale; public GenomeSummaryData(Genome genome, String[] samples) { this.genome = genome; this.samples = samples; scale = (genome.getLength() / locationUnit) / nPixels; List<String> chrNames = genome.getChromosomeNames(); locationMap = new HashMap(); dataMap = new HashMap(); for (String chr : chrNames) { locationMap.put(chr, new IntArrayList(nPixels / 10)); dataMap.put(chr, new HashMap()); for (String s : samples) { dataMap.get(chr).put(s, new FloatArrayList(nPixels / 10)); } } } public void addData(String chr, int[] locs, Map<String, float[]> sampleData) { IntArrayList locations = locationMap.get(chr); if (locations == null) { log.info("Skipping data for: " + chr); + return; } int lastPixel = -1; Map<String, Accumulator> dataPoints = new HashMap(); for (int i = 0; i < locs.length; i++) { int genomeLocation = genome.getGenomeCoordinate(chr, locs[i]); int pixel = (int) (genomeLocation / scale); if (i > 0 && pixel != lastPixel) { nDataPts++; locations.add(genomeLocation); for (String s : dataMap.get(chr).keySet()) { Accumulator dp = dataPoints.get(s); dp.finish(); dataMap.get(chr).get(s).add(dp.getValue()); } dataPoints.clear(); } for (String s : samples) { float[] data = sampleData.get(s); Accumulator dp = dataPoints.get(s); if (dp == null) { dp = new Accumulator(WindowFunction.mean); dataPoints.put(s, dp); } try { dp.add(1, data[i], null); } catch (Exception e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } lastPixel = pixel; } } public int[] getLocations() { if (locations == null) { createDataArrays(); } return locations; } public float[] getData(String sample) { if (!data.containsKey(sample)) { createDataArrays(); } return data.get(sample); } private synchronized void createDataArrays() { locations = new int[nDataPts]; int offset = 0; List<String> chrNames = genome.getChromosomeNames(); for (String chr : chrNames) { int[] chrLocs = locationMap.get(chr).toArray(); System.arraycopy(chrLocs, 0, locations, offset, chrLocs.length); offset += chrLocs.length; } data = new HashMap(); for (String s : samples) { float[] sampleData = new float[nDataPts]; offset = 0; for (String chr : chrNames) { float[] chrData = dataMap.get(chr).get(s).toArray(); System.arraycopy(chrData, 0, sampleData, offset, chrData.length); offset += chrData.length; } data.put(s, sampleData); } locationMap.clear(); dataMap.clear(); } }
true
true
public void addData(String chr, int[] locs, Map<String, float[]> sampleData) { IntArrayList locations = locationMap.get(chr); if (locations == null) { log.info("Skipping data for: " + chr); } int lastPixel = -1; Map<String, Accumulator> dataPoints = new HashMap(); for (int i = 0; i < locs.length; i++) { int genomeLocation = genome.getGenomeCoordinate(chr, locs[i]); int pixel = (int) (genomeLocation / scale); if (i > 0 && pixel != lastPixel) { nDataPts++; locations.add(genomeLocation); for (String s : dataMap.get(chr).keySet()) { Accumulator dp = dataPoints.get(s); dp.finish(); dataMap.get(chr).get(s).add(dp.getValue()); } dataPoints.clear(); } for (String s : samples) { float[] data = sampleData.get(s); Accumulator dp = dataPoints.get(s); if (dp == null) { dp = new Accumulator(WindowFunction.mean); dataPoints.put(s, dp); } try { dp.add(1, data[i], null); } catch (Exception e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } lastPixel = pixel; } }
public void addData(String chr, int[] locs, Map<String, float[]> sampleData) { IntArrayList locations = locationMap.get(chr); if (locations == null) { log.info("Skipping data for: " + chr); return; } int lastPixel = -1; Map<String, Accumulator> dataPoints = new HashMap(); for (int i = 0; i < locs.length; i++) { int genomeLocation = genome.getGenomeCoordinate(chr, locs[i]); int pixel = (int) (genomeLocation / scale); if (i > 0 && pixel != lastPixel) { nDataPts++; locations.add(genomeLocation); for (String s : dataMap.get(chr).keySet()) { Accumulator dp = dataPoints.get(s); dp.finish(); dataMap.get(chr).get(s).add(dp.getValue()); } dataPoints.clear(); } for (String s : samples) { float[] data = sampleData.get(s); Accumulator dp = dataPoints.get(s); if (dp == null) { dp = new Accumulator(WindowFunction.mean); dataPoints.put(s, dp); } try { dp.add(1, data[i], null); } catch (Exception e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } lastPixel = pixel; } }
diff --git a/src/sirp/Entidades/Dia.java b/src/sirp/Entidades/Dia.java index c8095e1..50e9340 100644 --- a/src/sirp/Entidades/Dia.java +++ b/src/sirp/Entidades/Dia.java @@ -1,46 +1,46 @@ package sirp.Entidades; import java.util.Date; import sirp.*; public class Dia { private int id_dia; private Date dia; public Dia(Date dia) { this.dia = dia; java.text.SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd"); - if(SIRP.con.nSeleccionados("SELECT id_dia FROM registro.dia WHERE dia ='"+format.format(dia)+"'")==0) + if(SIRP.con.nSeleccionados("SELECT id_dia FROM registro.dia WHERE dia ='"+format.format(dia)+"'")!=0) id_dia = SIRP.con.ultimo("registro.dia", "id_dia")+1; else id_dia = Integer.parseInt(SIRP.con.ver("SELECT id_dia FROM registro.dia WHERE dia ='"+format.format(dia)+"'", "id_dia")); } public int getId_dia() { return id_dia; } public Dia(){ dia = new Date(); id_dia = SIRP.con.ultimo("registro.dia", "id_dia")+1; } public String getDia(){ java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd"); return sdf.format(dia); } public void insert(){ java.text.SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd"); if(SIRP.con.nSeleccionados("SELECT id_dia FROM registro.dia WHERE dia ='"+format.format(dia)+"'")==0){ SIRP.con.query("INSERT INTO registro.dia(id_dia,dia)VALUES('"+ id_dia+"','"+ format.format(dia)+"');"); } } @Override public String toString(){ String s=""; s+=id_dia+" "+dia.toString(); return s; } }
true
true
public Dia(Date dia) { this.dia = dia; java.text.SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd"); if(SIRP.con.nSeleccionados("SELECT id_dia FROM registro.dia WHERE dia ='"+format.format(dia)+"'")==0) id_dia = SIRP.con.ultimo("registro.dia", "id_dia")+1; else id_dia = Integer.parseInt(SIRP.con.ver("SELECT id_dia FROM registro.dia WHERE dia ='"+format.format(dia)+"'", "id_dia")); }
public Dia(Date dia) { this.dia = dia; java.text.SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd"); if(SIRP.con.nSeleccionados("SELECT id_dia FROM registro.dia WHERE dia ='"+format.format(dia)+"'")!=0) id_dia = SIRP.con.ultimo("registro.dia", "id_dia")+1; else id_dia = Integer.parseInt(SIRP.con.ver("SELECT id_dia FROM registro.dia WHERE dia ='"+format.format(dia)+"'", "id_dia")); }
diff --git a/src/main/java/gov/usgs/cida/geoutils/geoutils/geoserver/servlet/ShapefileUploadServlet.java b/src/main/java/gov/usgs/cida/geoutils/geoutils/geoserver/servlet/ShapefileUploadServlet.java index accc0fd..09578d0 100644 --- a/src/main/java/gov/usgs/cida/geoutils/geoutils/geoserver/servlet/ShapefileUploadServlet.java +++ b/src/main/java/gov/usgs/cida/geoutils/geoutils/geoserver/servlet/ShapefileUploadServlet.java @@ -1,366 +1,369 @@ package gov.usgs.cida.geoutils.geoutils.geoserver.servlet; import gov.usgs.cida.config.DynamicReadOnlyProperties; import gov.usgs.cida.owsutils.commons.communication.RequestResponse; import gov.usgs.cida.owsutils.commons.io.FileHelper; import gov.usgs.cida.owsutils.commons.properties.JNDISingleton; import gov.usgs.cida.owsutils.commons.shapefile.ProjectionUtils; import it.geosolutions.geoserver.rest.GeoServerRESTManager; import it.geosolutions.geoserver.rest.GeoServerRESTPublisher; import it.geosolutions.geoserver.rest.GeoServerRESTPublisher.UploadMethod; import it.geosolutions.geoserver.rest.encoder.GSResourceEncoder.ProjectionPolicy; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.*; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; import org.slf4j.LoggerFactory; public class ShapefileUploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(ShapefileUploadServlet.class); private static DynamicReadOnlyProperties props = null; private static String applicationName; private static Integer maxFileSize; private static String geoserverEndpoint; private static URL geoserverEndpointURL; private static String geoserverUsername; private static String geoserverPassword; private static GeoServerRESTManager gsRestManager; // Defaults private static String defaultWorkspaceName; private static String defaultStoreName; private static String defaultSRS; private static String defaultFilenameParam = "qqfile"; // Legacy to handle jquery fineuploader private static Integer defaultMaxFileSize = Integer.MAX_VALUE; private static boolean defaultUseBaseCRSFallback = true; private static boolean defaultOverwriteExistingLayer = false; private static ProjectionPolicy defaultProjectionPolicy = ProjectionPolicy.REPROJECT_TO_DECLARED; private static ServletConfig servletConfig; @Override public void init(ServletConfig servletConfig) throws ServletException { super.init(); ShapefileUploadServlet.servletConfig = servletConfig; props = JNDISingleton.getInstance(); applicationName = servletConfig.getInitParameter("application.name"); // The maximum upload file size allowd by this server, 0 = Integer.MAX_VALUE String mfsInitParam = servletConfig.getInitParameter("max.upload.file.size"); String mfsJndiProp = props.getProperty(applicationName + ".max.upload.file.size"); if (StringUtils.isNotBlank(mfsInitParam)) { maxFileSize = Integer.parseInt(mfsInitParam); } else if (StringUtils.isNotBlank(mfsJndiProp)) { maxFileSize = Integer.parseInt(mfsJndiProp); } else { maxFileSize = defaultMaxFileSize; } if (maxFileSize == 0) { maxFileSize = defaultMaxFileSize; } LOG.trace("Maximum allowable file size set to: " + maxFileSize + " bytes"); String gsepInitParam = servletConfig.getInitParameter("geoserver.endpoint"); String gsepJndiProp = props.getProperty(applicationName + ".geoserver.endpoint"); if (StringUtils.isNotBlank(gsepInitParam)) { geoserverEndpoint = gsepInitParam; } else if (StringUtils.isNotBlank(gsepJndiProp)) { geoserverEndpoint = gsepJndiProp; } else { throw new ServletException("Geoserver endpoint is not defined."); } LOG.trace("Geoserver endpoint set to: " + geoserverEndpoint); try { geoserverEndpointURL = new URL(geoserverEndpoint); } catch (MalformedURLException ex) { throw new ServletException("Geoserver endpoint (" + geoserverEndpoint + ") could not be parsed into a valid URL."); } String gsuserInitParam = servletConfig.getInitParameter("geoserver.username"); String gsuserJndiProp = props.getProperty(applicationName + ".geoserver.username"); if (StringUtils.isNotBlank(gsuserInitParam)) { geoserverUsername = gsuserInitParam; } else if (StringUtils.isNotBlank(gsuserJndiProp)) { geoserverUsername = gsuserJndiProp; } else { throw new ServletException("Geoserver username is not defined."); } LOG.trace("Geoserver username set to: " + geoserverUsername); // This should only be coming from JNDI or JVM properties String gspassJndiProp = props.getProperty(applicationName + ".geoserver.password"); if (StringUtils.isNotBlank(gspassJndiProp)) { geoserverPassword = gspassJndiProp; } else { throw new ServletException("Geoserver password is not defined."); } LOG.trace("Geoserver password is set"); try { gsRestManager = new GeoServerRESTManager(geoserverEndpointURL, geoserverUsername, geoserverPassword); } catch (IllegalArgumentException ex) { throw new ServletException("Geoserver manager count not be built", ex); } catch (MalformedURLException ex) { // This should not happen since we take care of it above - we can probably move this into the try block above throw new ServletException("Geoserver endpoint (" + geoserverEndpoint + ") could not be parsed into a valid URL."); } String dwInitParam = servletConfig.getInitParameter("default.upload.workspace"); String dwJndiProp = props.getProperty(applicationName + ".default.upload.workspace"); if (StringUtils.isNotBlank(dwInitParam)) { defaultWorkspaceName = dwInitParam; } else if (StringUtils.isNotBlank(dwJndiProp)) { defaultWorkspaceName = dwInitParam; } else { defaultWorkspaceName = ""; LOG.warn("Default workspace is not defined. If a workspace is not passed to during the request, the request will fail;"); } LOG.trace("Default workspace set to: " + defaultWorkspaceName); String dsnInitParam = servletConfig.getInitParameter("default.upload.storename"); String dsnJndiProp = props.getProperty(applicationName + ".default.upload.storename"); if (StringUtils.isNotBlank(dsnInitParam)) { defaultStoreName = dwInitParam; } else if (StringUtils.isNotBlank(dsnJndiProp)) { defaultStoreName = dwInitParam; } else { defaultStoreName = ""; LOG.warn("Default store name is not defined. If a store name is not passed to during the request, the request will fail;"); } LOG.trace("Default store name set to: " + defaultStoreName); String dsrsInitParam = servletConfig.getInitParameter("default.srs"); String dsrsJndiProp = props.getProperty(applicationName + ".default.srs"); if (StringUtils.isNotBlank(dsrsInitParam)) { defaultSRS = dsrsInitParam; } else if (StringUtils.isNotBlank(dsrsJndiProp)) { defaultSRS = dsrsJndiProp; } else { defaultSRS = ""; LOG.warn("Default SRS is not defined. If a SRS name is not passed to during the request, the request will fail"); } LOG.trace("Default SRS set to: " + defaultSRS); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, FileNotFoundException { doPost(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, FileNotFoundException { String filenameParam; boolean useBaseCRSFailover; boolean overwriteExistingLayer; // "reproject" (default), "force", "none" ProjectionPolicy projectionPolicy; Map<String, String> responseMap = new HashMap<String, String>(); RequestResponse.ResponseType responseType = RequestResponse.ResponseType.XML; String responseEncoding = request.getParameter("response.encoding"); if (StringUtils.isBlank(responseEncoding) || responseEncoding.toLowerCase().contains("json")) { responseType = RequestResponse.ResponseType.JSON; } LOG.trace("Response type set to " + responseType.toString()); int fileSize = Integer.parseInt(request.getHeader("Content-Length")); if (fileSize > maxFileSize) { responseMap.put("error", "Upload exceeds max file size of " + maxFileSize + " bytes"); RequestResponse.sendErrorResponse(response, responseMap, responseType); return; } // The key to search for in the upload form post to find the file String fnInitParam = servletConfig.getInitParameter("filename.param"); String fnJndiProp = props.getProperty(applicationName + ".filename.param"); String fnReqParam = request.getParameter("filename.param"); if (StringUtils.isNotBlank(fnReqParam)) { filenameParam = fnReqParam; } else if (StringUtils.isNotBlank(fnInitParam)) { filenameParam = fnInitParam; } else if (StringUtils.isNotBlank(fnJndiProp)) { filenameParam = fnJndiProp; } else { filenameParam = defaultFilenameParam; } LOG.trace("Filename parameter set to: " + filenameParam); String oelInitParam = servletConfig.getInitParameter("overwrite.existing.layer"); String oelJndiProp = props.getProperty(applicationName + ".overwrite.existing.layer"); String oelReqParam = request.getParameter("overwrite.existing.layer"); if (StringUtils.isNotBlank(oelReqParam)) { overwriteExistingLayer = Boolean.parseBoolean(oelReqParam); } else if (StringUtils.isNotBlank(oelInitParam)) { overwriteExistingLayer = Boolean.parseBoolean(oelInitParam); } else if (StringUtils.isNotBlank(oelJndiProp)) { overwriteExistingLayer = Boolean.parseBoolean(oelJndiProp); } else { overwriteExistingLayer = defaultOverwriteExistingLayer; } LOG.trace("Overwrite existing layer set to: " + overwriteExistingLayer); String filename = request.getParameter(filenameParam); String tempDir = System.getProperty("java.io.tmpdir"); File shapeZipFile = new File(tempDir + File.separator + filename); LOG.trace("Temporary file set to " + shapeZipFile.getPath()); String workspaceName = request.getParameter("workspace"); if (StringUtils.isBlank(workspaceName)) { workspaceName = defaultWorkspaceName; } if (StringUtils.isBlank(workspaceName)) { responseMap.put("error", "Parameter \"workspace\" is mandatory"); RequestResponse.sendErrorResponse(response, responseMap, responseType); return; } LOG.trace("Workspace name set to " + workspaceName); String storeName = request.getParameter("store"); if (StringUtils.isBlank(storeName)) { storeName = defaultStoreName; } if (StringUtils.isBlank(storeName)) { responseMap.put("error", "Parameter \"store\" is mandatory"); RequestResponse.sendErrorResponse(response, responseMap, responseType); return; } LOG.trace("Store name set to " + storeName); String srsName = request.getParameter("srs"); if (StringUtils.isBlank(srsName)) { srsName = defaultSRS; } if (StringUtils.isBlank(srsName)) { responseMap.put("error", "Parameter \"srs\" is mandatory"); RequestResponse.sendErrorResponse(response, responseMap, responseType); return; } LOG.trace("SRS name set to " + srsName); String bCRSfoInitParam = servletConfig.getInitParameter("use.crs.failover"); String bCRSfoJndiProp = props.getProperty(applicationName + ".use.crs.failover"); String bCRSfoReqParam = request.getParameter("use.crs.failover"); if (StringUtils.isNotBlank(bCRSfoReqParam)) { useBaseCRSFailover = Boolean.parseBoolean(bCRSfoReqParam); } else if (StringUtils.isNotBlank(bCRSfoInitParam)) { useBaseCRSFailover = Boolean.parseBoolean(bCRSfoInitParam); } else if (StringUtils.isNotBlank(bCRSfoJndiProp)) { useBaseCRSFailover = Boolean.parseBoolean(bCRSfoJndiProp); } else { useBaseCRSFailover = defaultUseBaseCRSFallback; } LOG.trace("Use base CRS failover set to: " + useBaseCRSFailover); String projectionPolicyReqParam = request.getParameter("projection.policy"); String ppInitParam = servletConfig.getInitParameter("projection.policy"); String ppJndiProp = props.getProperty(applicationName + ".projection.policy"); if (StringUtils.isNotBlank(projectionPolicyReqParam)) { if (projectionPolicyReqParam.equalsIgnoreCase("reproject")) { projectionPolicy = ProjectionPolicy.REPROJECT_TO_DECLARED; } else if (projectionPolicyReqParam.equalsIgnoreCase("force")) { projectionPolicy = ProjectionPolicy.FORCE_DECLARED; } else { projectionPolicy = defaultProjectionPolicy; } } else if (StringUtils.isNotBlank(ppInitParam)) { if (ppInitParam.equalsIgnoreCase("reproject")) { projectionPolicy = ProjectionPolicy.REPROJECT_TO_DECLARED; } else if (ppInitParam.equalsIgnoreCase("force")) { projectionPolicy = ProjectionPolicy.FORCE_DECLARED; } else { projectionPolicy = ProjectionPolicy.NONE; } } else if (StringUtils.isNotBlank(ppJndiProp)) { if (ppJndiProp.equalsIgnoreCase("reproject")) { projectionPolicy = ProjectionPolicy.REPROJECT_TO_DECLARED; } else if (ppJndiProp.equalsIgnoreCase("force")) { projectionPolicy = ProjectionPolicy.FORCE_DECLARED; } else { projectionPolicy = ProjectionPolicy.NONE; } } else { projectionPolicy = defaultProjectionPolicy; } LOG.trace("Projection policy set to: " + projectionPolicy.name()); LOG.trace("Projection policy re-set to: " + projectionPolicy); String layerName = request.getParameter("layer"); if (StringUtils.isBlank(layerName)) { layerName = filename.split("\\.")[0]; } layerName = layerName.trim().replaceAll("\\.", "_").replaceAll(" ", "_"); LOG.trace("Layer name set to " + layerName); try { RequestResponse.saveFileFromRequest(request, shapeZipFile, filenameParam); LOG.trace("File saved to " + shapeZipFile.getPath()); FileHelper.flattenZipFile(shapeZipFile.getPath()); LOG.trace("Zip file directory structure flattened"); if (!FileHelper.validateShapefileZip(shapeZipFile)) { throw new IOException("Unable to verify shapefile. Upload failed."); } LOG.trace("Zip file seems to be a valid shapefile"); } catch (Exception ex) { LOG.warn(ex.getMessage()); responseMap.put("error", "Unable to upload file"); responseMap.put("exception", ex.getMessage()); RequestResponse.sendErrorResponse(response, responseMap, responseType); return; } String nativeCRS; try { nativeCRS = ProjectionUtils.getProjectionFromShapefileZip(shapeZipFile, useBaseCRSFailover); } catch (Exception ex) { LOG.warn(ex.getMessage()); responseMap.put("error", "Could not evince projection from shapefile"); responseMap.put("exception", ex.getMessage()); RequestResponse.sendErrorResponse(response, responseMap, responseType); return; } try { GeoServerRESTPublisher gsPublisher = gsRestManager.getPublisher(); if (overwriteExistingLayer) { // TODO- Using this library, I am unable to rename a layer. If publishing the layer // fails, we will have lost this layer due to removal here. - gsPublisher.removeLayer(workspaceName, layerName); + if (gsPublisher.unpublishFeatureType(workspaceName, storeName, layerName)) { + gsPublisher.unpublishCoverage(workspaceName, storeName, layerName); + gsPublisher.reloadStore(workspaceName, storeName, GeoServerRESTPublisher.StoreType.DATASTORES); + } } // Currently not doing any checks to see if workspace, store or layer already exist Boolean success = gsPublisher.publishShp(workspaceName, storeName, null, layerName, UploadMethod.FILE, shapeZipFile.toURI(), srsName, nativeCRS, projectionPolicy, null); if (success) { LOG.debug("Shapefile has been imported successfully"); responseMap.put("name", layerName); responseMap.put("workspace", workspaceName); responseMap.put("store", storeName); RequestResponse.sendSuccessResponse(response, responseMap, responseType); } else { LOG.debug("Shapefile could not be imported successfully"); responseMap.put("error", "Shapefile could not be imported successfully"); RequestResponse.sendErrorResponse(response, responseMap, responseType); } } catch (Exception ex) { LOG.warn(ex.getMessage()); responseMap.put("error", "Unable to upload file"); responseMap.put("exception", ex.getMessage()); RequestResponse.sendErrorResponse(response, responseMap, responseType); } finally { FileUtils.deleteQuietly(shapeZipFile); } } }
true
true
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, FileNotFoundException { String filenameParam; boolean useBaseCRSFailover; boolean overwriteExistingLayer; // "reproject" (default), "force", "none" ProjectionPolicy projectionPolicy; Map<String, String> responseMap = new HashMap<String, String>(); RequestResponse.ResponseType responseType = RequestResponse.ResponseType.XML; String responseEncoding = request.getParameter("response.encoding"); if (StringUtils.isBlank(responseEncoding) || responseEncoding.toLowerCase().contains("json")) { responseType = RequestResponse.ResponseType.JSON; } LOG.trace("Response type set to " + responseType.toString()); int fileSize = Integer.parseInt(request.getHeader("Content-Length")); if (fileSize > maxFileSize) { responseMap.put("error", "Upload exceeds max file size of " + maxFileSize + " bytes"); RequestResponse.sendErrorResponse(response, responseMap, responseType); return; } // The key to search for in the upload form post to find the file String fnInitParam = servletConfig.getInitParameter("filename.param"); String fnJndiProp = props.getProperty(applicationName + ".filename.param"); String fnReqParam = request.getParameter("filename.param"); if (StringUtils.isNotBlank(fnReqParam)) { filenameParam = fnReqParam; } else if (StringUtils.isNotBlank(fnInitParam)) { filenameParam = fnInitParam; } else if (StringUtils.isNotBlank(fnJndiProp)) { filenameParam = fnJndiProp; } else { filenameParam = defaultFilenameParam; } LOG.trace("Filename parameter set to: " + filenameParam); String oelInitParam = servletConfig.getInitParameter("overwrite.existing.layer"); String oelJndiProp = props.getProperty(applicationName + ".overwrite.existing.layer"); String oelReqParam = request.getParameter("overwrite.existing.layer"); if (StringUtils.isNotBlank(oelReqParam)) { overwriteExistingLayer = Boolean.parseBoolean(oelReqParam); } else if (StringUtils.isNotBlank(oelInitParam)) { overwriteExistingLayer = Boolean.parseBoolean(oelInitParam); } else if (StringUtils.isNotBlank(oelJndiProp)) { overwriteExistingLayer = Boolean.parseBoolean(oelJndiProp); } else { overwriteExistingLayer = defaultOverwriteExistingLayer; } LOG.trace("Overwrite existing layer set to: " + overwriteExistingLayer); String filename = request.getParameter(filenameParam); String tempDir = System.getProperty("java.io.tmpdir"); File shapeZipFile = new File(tempDir + File.separator + filename); LOG.trace("Temporary file set to " + shapeZipFile.getPath()); String workspaceName = request.getParameter("workspace"); if (StringUtils.isBlank(workspaceName)) { workspaceName = defaultWorkspaceName; } if (StringUtils.isBlank(workspaceName)) { responseMap.put("error", "Parameter \"workspace\" is mandatory"); RequestResponse.sendErrorResponse(response, responseMap, responseType); return; } LOG.trace("Workspace name set to " + workspaceName); String storeName = request.getParameter("store"); if (StringUtils.isBlank(storeName)) { storeName = defaultStoreName; } if (StringUtils.isBlank(storeName)) { responseMap.put("error", "Parameter \"store\" is mandatory"); RequestResponse.sendErrorResponse(response, responseMap, responseType); return; } LOG.trace("Store name set to " + storeName); String srsName = request.getParameter("srs"); if (StringUtils.isBlank(srsName)) { srsName = defaultSRS; } if (StringUtils.isBlank(srsName)) { responseMap.put("error", "Parameter \"srs\" is mandatory"); RequestResponse.sendErrorResponse(response, responseMap, responseType); return; } LOG.trace("SRS name set to " + srsName); String bCRSfoInitParam = servletConfig.getInitParameter("use.crs.failover"); String bCRSfoJndiProp = props.getProperty(applicationName + ".use.crs.failover"); String bCRSfoReqParam = request.getParameter("use.crs.failover"); if (StringUtils.isNotBlank(bCRSfoReqParam)) { useBaseCRSFailover = Boolean.parseBoolean(bCRSfoReqParam); } else if (StringUtils.isNotBlank(bCRSfoInitParam)) { useBaseCRSFailover = Boolean.parseBoolean(bCRSfoInitParam); } else if (StringUtils.isNotBlank(bCRSfoJndiProp)) { useBaseCRSFailover = Boolean.parseBoolean(bCRSfoJndiProp); } else { useBaseCRSFailover = defaultUseBaseCRSFallback; } LOG.trace("Use base CRS failover set to: " + useBaseCRSFailover); String projectionPolicyReqParam = request.getParameter("projection.policy"); String ppInitParam = servletConfig.getInitParameter("projection.policy"); String ppJndiProp = props.getProperty(applicationName + ".projection.policy"); if (StringUtils.isNotBlank(projectionPolicyReqParam)) { if (projectionPolicyReqParam.equalsIgnoreCase("reproject")) { projectionPolicy = ProjectionPolicy.REPROJECT_TO_DECLARED; } else if (projectionPolicyReqParam.equalsIgnoreCase("force")) { projectionPolicy = ProjectionPolicy.FORCE_DECLARED; } else { projectionPolicy = defaultProjectionPolicy; } } else if (StringUtils.isNotBlank(ppInitParam)) { if (ppInitParam.equalsIgnoreCase("reproject")) { projectionPolicy = ProjectionPolicy.REPROJECT_TO_DECLARED; } else if (ppInitParam.equalsIgnoreCase("force")) { projectionPolicy = ProjectionPolicy.FORCE_DECLARED; } else { projectionPolicy = ProjectionPolicy.NONE; } } else if (StringUtils.isNotBlank(ppJndiProp)) { if (ppJndiProp.equalsIgnoreCase("reproject")) { projectionPolicy = ProjectionPolicy.REPROJECT_TO_DECLARED; } else if (ppJndiProp.equalsIgnoreCase("force")) { projectionPolicy = ProjectionPolicy.FORCE_DECLARED; } else { projectionPolicy = ProjectionPolicy.NONE; } } else { projectionPolicy = defaultProjectionPolicy; } LOG.trace("Projection policy set to: " + projectionPolicy.name()); LOG.trace("Projection policy re-set to: " + projectionPolicy); String layerName = request.getParameter("layer"); if (StringUtils.isBlank(layerName)) { layerName = filename.split("\\.")[0]; } layerName = layerName.trim().replaceAll("\\.", "_").replaceAll(" ", "_"); LOG.trace("Layer name set to " + layerName); try { RequestResponse.saveFileFromRequest(request, shapeZipFile, filenameParam); LOG.trace("File saved to " + shapeZipFile.getPath()); FileHelper.flattenZipFile(shapeZipFile.getPath()); LOG.trace("Zip file directory structure flattened"); if (!FileHelper.validateShapefileZip(shapeZipFile)) { throw new IOException("Unable to verify shapefile. Upload failed."); } LOG.trace("Zip file seems to be a valid shapefile"); } catch (Exception ex) { LOG.warn(ex.getMessage()); responseMap.put("error", "Unable to upload file"); responseMap.put("exception", ex.getMessage()); RequestResponse.sendErrorResponse(response, responseMap, responseType); return; } String nativeCRS; try { nativeCRS = ProjectionUtils.getProjectionFromShapefileZip(shapeZipFile, useBaseCRSFailover); } catch (Exception ex) { LOG.warn(ex.getMessage()); responseMap.put("error", "Could not evince projection from shapefile"); responseMap.put("exception", ex.getMessage()); RequestResponse.sendErrorResponse(response, responseMap, responseType); return; } try { GeoServerRESTPublisher gsPublisher = gsRestManager.getPublisher(); if (overwriteExistingLayer) { // TODO- Using this library, I am unable to rename a layer. If publishing the layer // fails, we will have lost this layer due to removal here. gsPublisher.removeLayer(workspaceName, layerName); } // Currently not doing any checks to see if workspace, store or layer already exist Boolean success = gsPublisher.publishShp(workspaceName, storeName, null, layerName, UploadMethod.FILE, shapeZipFile.toURI(), srsName, nativeCRS, projectionPolicy, null); if (success) { LOG.debug("Shapefile has been imported successfully"); responseMap.put("name", layerName); responseMap.put("workspace", workspaceName); responseMap.put("store", storeName); RequestResponse.sendSuccessResponse(response, responseMap, responseType); } else { LOG.debug("Shapefile could not be imported successfully"); responseMap.put("error", "Shapefile could not be imported successfully"); RequestResponse.sendErrorResponse(response, responseMap, responseType); } } catch (Exception ex) { LOG.warn(ex.getMessage()); responseMap.put("error", "Unable to upload file"); responseMap.put("exception", ex.getMessage()); RequestResponse.sendErrorResponse(response, responseMap, responseType); } finally { FileUtils.deleteQuietly(shapeZipFile); } }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, FileNotFoundException { String filenameParam; boolean useBaseCRSFailover; boolean overwriteExistingLayer; // "reproject" (default), "force", "none" ProjectionPolicy projectionPolicy; Map<String, String> responseMap = new HashMap<String, String>(); RequestResponse.ResponseType responseType = RequestResponse.ResponseType.XML; String responseEncoding = request.getParameter("response.encoding"); if (StringUtils.isBlank(responseEncoding) || responseEncoding.toLowerCase().contains("json")) { responseType = RequestResponse.ResponseType.JSON; } LOG.trace("Response type set to " + responseType.toString()); int fileSize = Integer.parseInt(request.getHeader("Content-Length")); if (fileSize > maxFileSize) { responseMap.put("error", "Upload exceeds max file size of " + maxFileSize + " bytes"); RequestResponse.sendErrorResponse(response, responseMap, responseType); return; } // The key to search for in the upload form post to find the file String fnInitParam = servletConfig.getInitParameter("filename.param"); String fnJndiProp = props.getProperty(applicationName + ".filename.param"); String fnReqParam = request.getParameter("filename.param"); if (StringUtils.isNotBlank(fnReqParam)) { filenameParam = fnReqParam; } else if (StringUtils.isNotBlank(fnInitParam)) { filenameParam = fnInitParam; } else if (StringUtils.isNotBlank(fnJndiProp)) { filenameParam = fnJndiProp; } else { filenameParam = defaultFilenameParam; } LOG.trace("Filename parameter set to: " + filenameParam); String oelInitParam = servletConfig.getInitParameter("overwrite.existing.layer"); String oelJndiProp = props.getProperty(applicationName + ".overwrite.existing.layer"); String oelReqParam = request.getParameter("overwrite.existing.layer"); if (StringUtils.isNotBlank(oelReqParam)) { overwriteExistingLayer = Boolean.parseBoolean(oelReqParam); } else if (StringUtils.isNotBlank(oelInitParam)) { overwriteExistingLayer = Boolean.parseBoolean(oelInitParam); } else if (StringUtils.isNotBlank(oelJndiProp)) { overwriteExistingLayer = Boolean.parseBoolean(oelJndiProp); } else { overwriteExistingLayer = defaultOverwriteExistingLayer; } LOG.trace("Overwrite existing layer set to: " + overwriteExistingLayer); String filename = request.getParameter(filenameParam); String tempDir = System.getProperty("java.io.tmpdir"); File shapeZipFile = new File(tempDir + File.separator + filename); LOG.trace("Temporary file set to " + shapeZipFile.getPath()); String workspaceName = request.getParameter("workspace"); if (StringUtils.isBlank(workspaceName)) { workspaceName = defaultWorkspaceName; } if (StringUtils.isBlank(workspaceName)) { responseMap.put("error", "Parameter \"workspace\" is mandatory"); RequestResponse.sendErrorResponse(response, responseMap, responseType); return; } LOG.trace("Workspace name set to " + workspaceName); String storeName = request.getParameter("store"); if (StringUtils.isBlank(storeName)) { storeName = defaultStoreName; } if (StringUtils.isBlank(storeName)) { responseMap.put("error", "Parameter \"store\" is mandatory"); RequestResponse.sendErrorResponse(response, responseMap, responseType); return; } LOG.trace("Store name set to " + storeName); String srsName = request.getParameter("srs"); if (StringUtils.isBlank(srsName)) { srsName = defaultSRS; } if (StringUtils.isBlank(srsName)) { responseMap.put("error", "Parameter \"srs\" is mandatory"); RequestResponse.sendErrorResponse(response, responseMap, responseType); return; } LOG.trace("SRS name set to " + srsName); String bCRSfoInitParam = servletConfig.getInitParameter("use.crs.failover"); String bCRSfoJndiProp = props.getProperty(applicationName + ".use.crs.failover"); String bCRSfoReqParam = request.getParameter("use.crs.failover"); if (StringUtils.isNotBlank(bCRSfoReqParam)) { useBaseCRSFailover = Boolean.parseBoolean(bCRSfoReqParam); } else if (StringUtils.isNotBlank(bCRSfoInitParam)) { useBaseCRSFailover = Boolean.parseBoolean(bCRSfoInitParam); } else if (StringUtils.isNotBlank(bCRSfoJndiProp)) { useBaseCRSFailover = Boolean.parseBoolean(bCRSfoJndiProp); } else { useBaseCRSFailover = defaultUseBaseCRSFallback; } LOG.trace("Use base CRS failover set to: " + useBaseCRSFailover); String projectionPolicyReqParam = request.getParameter("projection.policy"); String ppInitParam = servletConfig.getInitParameter("projection.policy"); String ppJndiProp = props.getProperty(applicationName + ".projection.policy"); if (StringUtils.isNotBlank(projectionPolicyReqParam)) { if (projectionPolicyReqParam.equalsIgnoreCase("reproject")) { projectionPolicy = ProjectionPolicy.REPROJECT_TO_DECLARED; } else if (projectionPolicyReqParam.equalsIgnoreCase("force")) { projectionPolicy = ProjectionPolicy.FORCE_DECLARED; } else { projectionPolicy = defaultProjectionPolicy; } } else if (StringUtils.isNotBlank(ppInitParam)) { if (ppInitParam.equalsIgnoreCase("reproject")) { projectionPolicy = ProjectionPolicy.REPROJECT_TO_DECLARED; } else if (ppInitParam.equalsIgnoreCase("force")) { projectionPolicy = ProjectionPolicy.FORCE_DECLARED; } else { projectionPolicy = ProjectionPolicy.NONE; } } else if (StringUtils.isNotBlank(ppJndiProp)) { if (ppJndiProp.equalsIgnoreCase("reproject")) { projectionPolicy = ProjectionPolicy.REPROJECT_TO_DECLARED; } else if (ppJndiProp.equalsIgnoreCase("force")) { projectionPolicy = ProjectionPolicy.FORCE_DECLARED; } else { projectionPolicy = ProjectionPolicy.NONE; } } else { projectionPolicy = defaultProjectionPolicy; } LOG.trace("Projection policy set to: " + projectionPolicy.name()); LOG.trace("Projection policy re-set to: " + projectionPolicy); String layerName = request.getParameter("layer"); if (StringUtils.isBlank(layerName)) { layerName = filename.split("\\.")[0]; } layerName = layerName.trim().replaceAll("\\.", "_").replaceAll(" ", "_"); LOG.trace("Layer name set to " + layerName); try { RequestResponse.saveFileFromRequest(request, shapeZipFile, filenameParam); LOG.trace("File saved to " + shapeZipFile.getPath()); FileHelper.flattenZipFile(shapeZipFile.getPath()); LOG.trace("Zip file directory structure flattened"); if (!FileHelper.validateShapefileZip(shapeZipFile)) { throw new IOException("Unable to verify shapefile. Upload failed."); } LOG.trace("Zip file seems to be a valid shapefile"); } catch (Exception ex) { LOG.warn(ex.getMessage()); responseMap.put("error", "Unable to upload file"); responseMap.put("exception", ex.getMessage()); RequestResponse.sendErrorResponse(response, responseMap, responseType); return; } String nativeCRS; try { nativeCRS = ProjectionUtils.getProjectionFromShapefileZip(shapeZipFile, useBaseCRSFailover); } catch (Exception ex) { LOG.warn(ex.getMessage()); responseMap.put("error", "Could not evince projection from shapefile"); responseMap.put("exception", ex.getMessage()); RequestResponse.sendErrorResponse(response, responseMap, responseType); return; } try { GeoServerRESTPublisher gsPublisher = gsRestManager.getPublisher(); if (overwriteExistingLayer) { // TODO- Using this library, I am unable to rename a layer. If publishing the layer // fails, we will have lost this layer due to removal here. if (gsPublisher.unpublishFeatureType(workspaceName, storeName, layerName)) { gsPublisher.unpublishCoverage(workspaceName, storeName, layerName); gsPublisher.reloadStore(workspaceName, storeName, GeoServerRESTPublisher.StoreType.DATASTORES); } } // Currently not doing any checks to see if workspace, store or layer already exist Boolean success = gsPublisher.publishShp(workspaceName, storeName, null, layerName, UploadMethod.FILE, shapeZipFile.toURI(), srsName, nativeCRS, projectionPolicy, null); if (success) { LOG.debug("Shapefile has been imported successfully"); responseMap.put("name", layerName); responseMap.put("workspace", workspaceName); responseMap.put("store", storeName); RequestResponse.sendSuccessResponse(response, responseMap, responseType); } else { LOG.debug("Shapefile could not be imported successfully"); responseMap.put("error", "Shapefile could not be imported successfully"); RequestResponse.sendErrorResponse(response, responseMap, responseType); } } catch (Exception ex) { LOG.warn(ex.getMessage()); responseMap.put("error", "Unable to upload file"); responseMap.put("exception", ex.getMessage()); RequestResponse.sendErrorResponse(response, responseMap, responseType); } finally { FileUtils.deleteQuietly(shapeZipFile); } }
diff --git a/src/com/taboozle/Rules.java b/src/com/taboozle/Rules.java index 7f3e7fd..87405ff 100644 --- a/src/com/taboozle/Rules.java +++ b/src/com/taboozle/Rules.java @@ -1,43 +1,53 @@ package com.taboozle; import android.app.Activity; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.widget.TextView; /** * @author The Taboozle Team * This activity class is responsible for displaying the rules of taboozle to the user. */ public class Rules extends Activity { /** * logging tag */ public static String TAG = "Rules"; /** * onCreate - initializes the activity to display the rules. */ @Override public void onCreate( Bundle savedInstanceState ) { super.onCreate( savedInstanceState ); Log.d( TAG, "onCreate()" ); this.setContentView(R.layout.rules); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this.getBaseContext()); //String used for displaying the customizable preferences to the user StringBuilder prefBuilder = new StringBuilder(); + prefBuilder.append("(These rules can be changed any time from the Settings screen.)"); - prefBuilder.append("Turn Length: " + sp.getString("turn_timer", "60") + " seconds"); - prefBuilder.append("\nSkip Penalty: " + sp.getBoolean("skip_penalty",false)); + //Turn Length rule display + prefBuilder.append("\n\nTurn Length: " + sp.getString("turn_timer", "60") + " seconds"); + //Allow Skipping rule display + if (sp.getBoolean("allow_skip",true)) + { + prefBuilder.append("\nAllow Skipping: Players may skip words."); + } + else + { + prefBuilder.append("\nAllow Skipping: Players can not skip words."); + } TextView rulePrefs = (TextView) this.findViewById(R.id.RulePreferences); rulePrefs.setText(prefBuilder); } }
false
true
public void onCreate( Bundle savedInstanceState ) { super.onCreate( savedInstanceState ); Log.d( TAG, "onCreate()" ); this.setContentView(R.layout.rules); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this.getBaseContext()); //String used for displaying the customizable preferences to the user StringBuilder prefBuilder = new StringBuilder(); prefBuilder.append("Turn Length: " + sp.getString("turn_timer", "60") + " seconds"); prefBuilder.append("\nSkip Penalty: " + sp.getBoolean("skip_penalty",false)); TextView rulePrefs = (TextView) this.findViewById(R.id.RulePreferences); rulePrefs.setText(prefBuilder); }
public void onCreate( Bundle savedInstanceState ) { super.onCreate( savedInstanceState ); Log.d( TAG, "onCreate()" ); this.setContentView(R.layout.rules); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this.getBaseContext()); //String used for displaying the customizable preferences to the user StringBuilder prefBuilder = new StringBuilder(); prefBuilder.append("(These rules can be changed any time from the Settings screen.)"); //Turn Length rule display prefBuilder.append("\n\nTurn Length: " + sp.getString("turn_timer", "60") + " seconds"); //Allow Skipping rule display if (sp.getBoolean("allow_skip",true)) { prefBuilder.append("\nAllow Skipping: Players may skip words."); } else { prefBuilder.append("\nAllow Skipping: Players can not skip words."); } TextView rulePrefs = (TextView) this.findViewById(R.id.RulePreferences); rulePrefs.setText(prefBuilder); }
diff --git a/src/com/travel/service/MenuInfService.java b/src/com/travel/service/MenuInfService.java index 85adade..91a1119 100644 --- a/src/com/travel/service/MenuInfService.java +++ b/src/com/travel/service/MenuInfService.java @@ -1,112 +1,112 @@ package com.travel.service; import java.util.List; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.travel.dao.MenuInfDAO; import com.travel.entity.MenuInf; @Service public class MenuInfService { @Autowired private MenuInfDAO menuDao; /** * @param menuList * @return */ public String generateMenuInfor(List<MenuInf> menuList) { StringBuilder menuInfStr = new StringBuilder(); for(int i = 0; i < menuList.size(); i++){ MenuInf menu = menuList.get(i); if(menu.getMenuInf() == null){ //父菜单 if(i == 0){ // 第一个父菜单 menuInfStr.append("<li><a>" + menu.getName() + "</a><ul>"); } else { menuInfStr.append("</ul></li><li><a>" + menu.getName() + "</a><ul>"); } } else { // 子菜单 menuInfStr.append("<li><a href=\"" + menu.getUrl() + "\" target=\"navTab\" rel=\"" + menu.getName() + "\">" + menu.getName() + "</a></li>"); if(i == menuList.size() - 1){ menuInfStr.append("</ul></li>"); } } } return menuInfStr.toString(); } /** * @return */ public List<MenuInf> getAllMenuItem() { return menuDao.findAll(); } /** * @param menuList * @return */ public String generateMenuInforSelect(List<MenuInf> menuList) { StringBuilder menuInfStr = new StringBuilder(); for(int i = 0; i < menuList.size(); i++){ MenuInf menu = menuList.get(i); if(menu.getMenuInf() == null){ //父菜单 if(i == 0){ // 第一个父菜单 menuInfStr.append("<li><a tname=\"treeMenuId"+ menu.getId() +"\" tvalue=\""+ menu.getId() +"\">" + menu.getName() + "</a><ul>"); } else { menuInfStr.append("</ul></li><li><a tname=\"treeMenuId"+ menu.getId() +"\" tvalue=\""+ menu.getId() +"\">" + menu.getName() + "</a><ul>"); } } else { // 子菜单 menuInfStr.append("<li><a tname=\"treeMenuId"+ menu.getId() +"\" tvalue=\""+ menu.getId() +"\">" + menu.getName() + "</a></li>"); if(i == menuList.size() - 1){ menuInfStr.append("</ul></li>"); } } } return menuInfStr.toString(); } /** * @param menuList * @return */ public String generateMenuInforSelect(List<MenuInf> menuList, List<MenuInf>selectedMenuList) { StringBuilder menuInfStr = new StringBuilder(); for(int i = 0; i < menuList.size(); i++){ MenuInf menu = menuList.get(i); - String checkStr = "checked=\"unchecked\""; + String checkStr = ""; for(MenuInf selectedMenu : selectedMenuList){ if(selectedMenu.getId().longValue() == menu.getId().longValue()){ checkStr = "checked=\"checked\""; break; } } if(menu.getMenuInf() == null){ //父菜单 if(i == 0){ // 第一个父菜单 menuInfStr.append("<li><a "+ checkStr +" tname=\"treeMenuId"+ menu.getId() +"\" tvalue=\""+ menu.getId() +"\" >" + menu.getName() + "</a><ul>"); } else { menuInfStr.append("</ul></li><li><a "+ checkStr +" tname=\"treeMenuId"+ menu.getId() +"\" tvalue=\""+ menu.getId() +"\">" + menu.getName() + "</a><ul>"); } } else { // 子菜单 menuInfStr.append("<li><a "+ checkStr +" tname=\"treeMenuId"+ menu.getId() +"\" tvalue=\""+ menu.getId() +"\">" + menu.getName() + "</a></li>"); if(i == menuList.size() - 1){ menuInfStr.append("</ul></li>"); } } } return menuInfStr.toString(); } /** * @param id * @return */ public List<MenuInf> getMenuItemByRoleId(Long id) { List<MenuInf> menuList = menuDao.findMenuByRoleId(id); return menuList; } }
true
true
public String generateMenuInforSelect(List<MenuInf> menuList, List<MenuInf>selectedMenuList) { StringBuilder menuInfStr = new StringBuilder(); for(int i = 0; i < menuList.size(); i++){ MenuInf menu = menuList.get(i); String checkStr = "checked=\"unchecked\""; for(MenuInf selectedMenu : selectedMenuList){ if(selectedMenu.getId().longValue() == menu.getId().longValue()){ checkStr = "checked=\"checked\""; break; } } if(menu.getMenuInf() == null){ //父菜单 if(i == 0){ // 第一个父菜单 menuInfStr.append("<li><a "+ checkStr +" tname=\"treeMenuId"+ menu.getId() +"\" tvalue=\""+ menu.getId() +"\" >" + menu.getName() + "</a><ul>"); } else { menuInfStr.append("</ul></li><li><a "+ checkStr +" tname=\"treeMenuId"+ menu.getId() +"\" tvalue=\""+ menu.getId() +"\">" + menu.getName() + "</a><ul>"); } } else { // 子菜单 menuInfStr.append("<li><a "+ checkStr +" tname=\"treeMenuId"+ menu.getId() +"\" tvalue=\""+ menu.getId() +"\">" + menu.getName() + "</a></li>"); if(i == menuList.size() - 1){ menuInfStr.append("</ul></li>"); } } } return menuInfStr.toString(); }
public String generateMenuInforSelect(List<MenuInf> menuList, List<MenuInf>selectedMenuList) { StringBuilder menuInfStr = new StringBuilder(); for(int i = 0; i < menuList.size(); i++){ MenuInf menu = menuList.get(i); String checkStr = ""; for(MenuInf selectedMenu : selectedMenuList){ if(selectedMenu.getId().longValue() == menu.getId().longValue()){ checkStr = "checked=\"checked\""; break; } } if(menu.getMenuInf() == null){ //父菜单 if(i == 0){ // 第一个父菜单 menuInfStr.append("<li><a "+ checkStr +" tname=\"treeMenuId"+ menu.getId() +"\" tvalue=\""+ menu.getId() +"\" >" + menu.getName() + "</a><ul>"); } else { menuInfStr.append("</ul></li><li><a "+ checkStr +" tname=\"treeMenuId"+ menu.getId() +"\" tvalue=\""+ menu.getId() +"\">" + menu.getName() + "</a><ul>"); } } else { // 子菜单 menuInfStr.append("<li><a "+ checkStr +" tname=\"treeMenuId"+ menu.getId() +"\" tvalue=\""+ menu.getId() +"\">" + menu.getName() + "</a></li>"); if(i == menuList.size() - 1){ menuInfStr.append("</ul></li>"); } } } return menuInfStr.toString(); }
diff --git a/src/server-java/testapp-interactive/lib/nextapp/echo/extras/testapp/ConsoleWindowPane.java b/src/server-java/testapp-interactive/lib/nextapp/echo/extras/testapp/ConsoleWindowPane.java index d2e1458..1779d19 100644 --- a/src/server-java/testapp-interactive/lib/nextapp/echo/extras/testapp/ConsoleWindowPane.java +++ b/src/server-java/testapp-interactive/lib/nextapp/echo/extras/testapp/ConsoleWindowPane.java @@ -1,94 +1,95 @@ /* * This file is part of the Echo Extras Project. * Copyright (C) 2005-2007 NextApp, Inc. * * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * 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. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. */ package nextapp.echo.extras.testapp; import nextapp.echo.app.Button; import nextapp.echo.app.Color; import nextapp.echo.app.Column; import nextapp.echo.app.ContentPane; import nextapp.echo.app.Extent; import nextapp.echo.app.Font; import nextapp.echo.app.Insets; import nextapp.echo.app.Label; import nextapp.echo.app.Row; import nextapp.echo.app.SplitPane; import nextapp.echo.app.WindowPane; import nextapp.echo.app.event.ActionEvent; import nextapp.echo.app.event.ActionListener; import nextapp.echo.app.layout.SplitPaneLayoutData; /** * A <code>WindowPane</code> which contains an event console. */ public class ConsoleWindowPane extends WindowPane { private Column column; private ContentPane logPane; public ConsoleWindowPane() { super(); setTitle("Console"); setStyleName("Default"); SplitPane splitPane = new SplitPane(SplitPane.ORIENTATION_VERTICAL_BOTTOM_TOP, new Extent(32)); add(splitPane); Row controlRow = new Row(); controlRow.setStyleName("ControlPane"); splitPane.add(controlRow); Button button = new Button("Clear", Styles.ICON_24_NO); button.setStyleName("ControlPane.Button"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { column.removeAll(); } }); controlRow.add(button); SplitPaneLayoutData splitPaneLayoutData; logPane = new ContentPane(); logPane.setFont(new Font(Font.MONOSPACE, Font.PLAIN, new Extent(10))); logPane.setForeground(Color.GREEN); + logPane.setBackground(Color.BLACK); splitPaneLayoutData = new SplitPaneLayoutData(); splitPaneLayoutData.setBackground(Color.BLACK); logPane.setLayoutData(splitPaneLayoutData); splitPane.add(logPane); column = new Column(); column.setInsets(new Insets(5)); logPane.add(column); } public void writeMessage(String message) { column.add(new Label(message)); logPane.setVerticalScroll(new Extent(-1)); } }
true
true
public ConsoleWindowPane() { super(); setTitle("Console"); setStyleName("Default"); SplitPane splitPane = new SplitPane(SplitPane.ORIENTATION_VERTICAL_BOTTOM_TOP, new Extent(32)); add(splitPane); Row controlRow = new Row(); controlRow.setStyleName("ControlPane"); splitPane.add(controlRow); Button button = new Button("Clear", Styles.ICON_24_NO); button.setStyleName("ControlPane.Button"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { column.removeAll(); } }); controlRow.add(button); SplitPaneLayoutData splitPaneLayoutData; logPane = new ContentPane(); logPane.setFont(new Font(Font.MONOSPACE, Font.PLAIN, new Extent(10))); logPane.setForeground(Color.GREEN); splitPaneLayoutData = new SplitPaneLayoutData(); splitPaneLayoutData.setBackground(Color.BLACK); logPane.setLayoutData(splitPaneLayoutData); splitPane.add(logPane); column = new Column(); column.setInsets(new Insets(5)); logPane.add(column); }
public ConsoleWindowPane() { super(); setTitle("Console"); setStyleName("Default"); SplitPane splitPane = new SplitPane(SplitPane.ORIENTATION_VERTICAL_BOTTOM_TOP, new Extent(32)); add(splitPane); Row controlRow = new Row(); controlRow.setStyleName("ControlPane"); splitPane.add(controlRow); Button button = new Button("Clear", Styles.ICON_24_NO); button.setStyleName("ControlPane.Button"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { column.removeAll(); } }); controlRow.add(button); SplitPaneLayoutData splitPaneLayoutData; logPane = new ContentPane(); logPane.setFont(new Font(Font.MONOSPACE, Font.PLAIN, new Extent(10))); logPane.setForeground(Color.GREEN); logPane.setBackground(Color.BLACK); splitPaneLayoutData = new SplitPaneLayoutData(); splitPaneLayoutData.setBackground(Color.BLACK); logPane.setLayoutData(splitPaneLayoutData); splitPane.add(logPane); column = new Column(); column.setInsets(new Insets(5)); logPane.add(column); }
diff --git a/core/src/main/java/net/groster/moex/forts/drunkypenguin/core/fast/ConnectionThread.java b/core/src/main/java/net/groster/moex/forts/drunkypenguin/core/fast/ConnectionThread.java index a55c3d6..d6a574a 100644 --- a/core/src/main/java/net/groster/moex/forts/drunkypenguin/core/fast/ConnectionThread.java +++ b/core/src/main/java/net/groster/moex/forts/drunkypenguin/core/fast/ConnectionThread.java @@ -1,95 +1,96 @@ package net.groster.moex.forts.drunkypenguin.core.fast; import java.io.IOException; import java.net.SocketTimeoutException; import javax.annotation.PreDestroy; import javax.inject.Inject; import javax.inject.Named; import org.openfast.MessageHandler; import org.openfast.MessageInputStream; import org.openfast.session.Connection; import org.openfast.session.FastConnectionException; import org.openfast.session.multicast.MulticastClientEndpoint; import org.openfast.template.MessageTemplate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.Scope; @Named @Scope(BeanDefinition.SCOPE_PROTOTYPE) public class ConnectionThread extends Thread { private static final Logger LOGGER = LoggerFactory.getLogger(ConnectionThread.class); private volatile boolean work = true; private MulticastClientEndpoint multicastClientEndpoint; private MessageHandler messageHandler; @Inject private FastService fastService; public void init(final String name, final MulticastClientEndpoint multicastClientEndpoint, final MessageHandler messageHandler) { setName(name); this.multicastClientEndpoint = multicastClientEndpoint; this.messageHandler = messageHandler; } @Override public void run() { LOGGER.info("starting."); while (work) { boolean wasConnected = false; MessageInputStream messageIn = null; Connection fastConnection = null; try { LOGGER.info("connecting."); fastConnection = multicastClientEndpoint.connect(); messageIn = new MessageInputStream(fastConnection.getInputStream()); for (final MessageTemplate template : fastService.getTemplates()) { messageIn.registerTemplate(Integer.parseInt(template.getId()), template); } messageIn.addMessageHandler(messageHandler); messageIn.readMessage(); LOGGER.info("connected."); wasConnected = true; while (work) { messageIn.readMessage(); } } catch (RuntimeException rE) { if (rE.getCause() instanceof SocketTimeoutException) { LOGGER.warn("socket timeout exception. Will try to reconnect"); + } else { + throw rE; } - throw rE; } catch (FastConnectionException | IOException ex) { LOGGER.error("Error connecting", ex); } finally { if (messageIn != null) { try { messageIn.close(); } catch (Exception e) { } } if (fastConnection != null) { try { fastConnection.close(); } catch (Exception e) { } } } if (wasConnected) { if (work) { LOGGER.warn("disconnected"); } else { LOGGER.info("disconnected"); } } } LOGGER.info("stopped"); } @PreDestroy public void preDestroy() { work = false; interrupt(); } }
false
true
public void run() { LOGGER.info("starting."); while (work) { boolean wasConnected = false; MessageInputStream messageIn = null; Connection fastConnection = null; try { LOGGER.info("connecting."); fastConnection = multicastClientEndpoint.connect(); messageIn = new MessageInputStream(fastConnection.getInputStream()); for (final MessageTemplate template : fastService.getTemplates()) { messageIn.registerTemplate(Integer.parseInt(template.getId()), template); } messageIn.addMessageHandler(messageHandler); messageIn.readMessage(); LOGGER.info("connected."); wasConnected = true; while (work) { messageIn.readMessage(); } } catch (RuntimeException rE) { if (rE.getCause() instanceof SocketTimeoutException) { LOGGER.warn("socket timeout exception. Will try to reconnect"); } throw rE; } catch (FastConnectionException | IOException ex) { LOGGER.error("Error connecting", ex); } finally { if (messageIn != null) { try { messageIn.close(); } catch (Exception e) { } } if (fastConnection != null) { try { fastConnection.close(); } catch (Exception e) { } } } if (wasConnected) { if (work) { LOGGER.warn("disconnected"); } else { LOGGER.info("disconnected"); } } } LOGGER.info("stopped"); }
public void run() { LOGGER.info("starting."); while (work) { boolean wasConnected = false; MessageInputStream messageIn = null; Connection fastConnection = null; try { LOGGER.info("connecting."); fastConnection = multicastClientEndpoint.connect(); messageIn = new MessageInputStream(fastConnection.getInputStream()); for (final MessageTemplate template : fastService.getTemplates()) { messageIn.registerTemplate(Integer.parseInt(template.getId()), template); } messageIn.addMessageHandler(messageHandler); messageIn.readMessage(); LOGGER.info("connected."); wasConnected = true; while (work) { messageIn.readMessage(); } } catch (RuntimeException rE) { if (rE.getCause() instanceof SocketTimeoutException) { LOGGER.warn("socket timeout exception. Will try to reconnect"); } else { throw rE; } } catch (FastConnectionException | IOException ex) { LOGGER.error("Error connecting", ex); } finally { if (messageIn != null) { try { messageIn.close(); } catch (Exception e) { } } if (fastConnection != null) { try { fastConnection.close(); } catch (Exception e) { } } } if (wasConnected) { if (work) { LOGGER.warn("disconnected"); } else { LOGGER.info("disconnected"); } } } LOGGER.info("stopped"); }
diff --git a/src/main/java/com/google/gwtexpui/globalkey/client/KeyHelpPopup.java b/src/main/java/com/google/gwtexpui/globalkey/client/KeyHelpPopup.java index 26fefbe65..7bd023396 100644 --- a/src/main/java/com/google/gwtexpui/globalkey/client/KeyHelpPopup.java +++ b/src/main/java/com/google/gwtexpui/globalkey/client/KeyHelpPopup.java @@ -1,227 +1,228 @@ // 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.gwtexpui.globalkey.client; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.KeyPressEvent; import com.google.gwt.event.dom.client.KeyPressHandler; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.ui.Anchor; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.FocusPanel; import com.google.gwt.user.client.ui.Grid; import com.google.gwt.user.client.ui.HasHorizontalAlignment; import com.google.gwt.user.client.ui.HTMLTable.CellFormatter; import com.google.gwtexpui.safehtml.client.SafeHtml; import com.google.gwtexpui.safehtml.client.SafeHtmlBuilder; import com.google.gwtexpui.user.client.PluginSafePopupPanel; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.List; public class KeyHelpPopup extends PluginSafePopupPanel implements KeyPressHandler { private final FocusPanel focus; public KeyHelpPopup() { super(true/* autohide */, true/* modal */); setStyleName(KeyResources.I.css().helpPopup()); final Anchor closer = new Anchor(KeyConstants.I.closeButton()); closer.addClickHandler(new ClickHandler() { @Override public void onClick(final ClickEvent event) { hide(); } }); final Grid header = new Grid(1, 3); header.setStyleName(KeyResources.I.css().helpHeader()); header.setText(0, 0, KeyConstants.I.keyboardShortcuts()); header.setWidget(0, 2, closer); final CellFormatter fmt = header.getCellFormatter(); fmt.addStyleName(0, 1, KeyResources.I.css().helpHeaderGlue()); fmt.setHorizontalAlignment(0, 2, HasHorizontalAlignment.ALIGN_RIGHT); final Grid lists = new Grid(0, 7); lists.setStyleName(KeyResources.I.css().helpTable()); populate(lists); lists.getCellFormatter().addStyleName(0, 3, KeyResources.I.css().helpTableGlue()); final FlowPanel body = new FlowPanel(); body.add(header); DOM.appendChild(body.getElement(), DOM.createElement("hr")); body.add(lists); focus = new FocusPanel(body); DOM.setStyleAttribute(focus.getElement(), "outline", "0px"); DOM.setElementAttribute(focus.getElement(), "hideFocus", "true"); focus.addKeyPressHandler(this); add(focus); } @Override public void setVisible(final boolean show) { super.setVisible(show); if (show) { focus.setFocus(true); } } @Override public void onKeyPress(final KeyPressEvent event) { if (KeyCommandSet.toMask(event) == ShowHelpCommand.INSTANCE.keyMask) { // Block the '?' key from triggering us to show right after // we just hide ourselves. // event.stopPropagation(); event.preventDefault(); } hide(); } private void populate(final Grid lists) { int end[] = new int[5]; int column = 0; for (final KeyCommandSet set : combinedSetsByName()) { int row = end[column]; row = formatGroup(lists, row, column, set); end[column] = row; if (column == 0) { column = 4; } else { column = 0; } } } /** * @return an ordered collection of KeyCommandSet, combining sets which share * the same name, so that each set name appears at most once. */ private static Collection<KeyCommandSet> combinedSetsByName() { final LinkedHashMap<String, KeyCommandSet> byName = new LinkedHashMap<String, KeyCommandSet>(); for (final KeyCommandSet set : GlobalKey.active.all.getSets()) { KeyCommandSet v = byName.get(set.getName()); if (v == null) { v = new KeyCommandSet(set.getName()); byName.put(v.getName(), v); } v.add(set); } return byName.values(); } private int formatGroup(final Grid lists, int row, final int col, final KeyCommandSet set) { if (set.isEmpty()) { return row; } if (lists.getRowCount() < row + 1) { lists.resizeRows(row + 1); } lists.setText(row, col + 2, set.getName()); lists.getCellFormatter().addStyleName(row, col + 2, KeyResources.I.css().helpGroup()); row++; return formatKeys(lists, row, col, set, null); } private int formatKeys(final Grid lists, int row, final int col, final KeyCommandSet set, final SafeHtml prefix) { final CellFormatter fmt = lists.getCellFormatter(); final int initialRow = row; final List<KeyCommand> keys = sort(set); if (lists.getRowCount() < row + keys.size()) { lists.resizeRows(row + keys.size()); } FORMAT_KEYS: for (int i = 0; i < keys.size(); i++) { final KeyCommand k = keys.get(i); if (k instanceof CompoundKeyCommand) { final SafeHtmlBuilder b = new SafeHtmlBuilder(); b.append(k.describeKeyStroke()); row = formatKeys(lists, row, col, ((CompoundKeyCommand) k).getSet(), b); continue; } - for (int prior = 0, r = initialRow; prior < i; prior++) { + for (int prior = 0; prior < i; prior++) { if (KeyCommand.same(keys.get(prior), k)) { + final int r = initialRow + prior; final SafeHtmlBuilder b = new SafeHtmlBuilder(); b.append(SafeHtml.get(lists, r, col + 0)); b.append(" "); b.append(KeyConstants.I.orOtherKey()); b.append(" "); if (prefix != null) { b.append(prefix); b.append(" "); b.append(KeyConstants.I.thenOtherKey()); b.append(" "); } b.append(k.describeKeyStroke()); SafeHtml.set(lists, r, col + 0, b); continue FORMAT_KEYS; } } if (prefix != null) { final SafeHtmlBuilder b = new SafeHtmlBuilder(); b.append(prefix); b.append(" "); b.append(KeyConstants.I.thenOtherKey()); b.append(" "); b.append(k.describeKeyStroke()); SafeHtml.set(lists, row, col + 0, b); } else { SafeHtml.set(lists, row, col + 0, k.describeKeyStroke()); } lists.setText(row, col + 1, ":"); lists.setText(row, col + 2, k.getHelpText()); fmt.addStyleName(row, col + 0, KeyResources.I.css().helpKeyStroke()); fmt.addStyleName(row, col + 1, KeyResources.I.css().helpSeparator()); row++; } return row; } private List<KeyCommand> sort(final KeyCommandSet set) { final List<KeyCommand> keys = new ArrayList<KeyCommand>(set.getKeys()); Collections.sort(keys, new Comparator<KeyCommand>() { @Override public int compare(KeyCommand arg0, KeyCommand arg1) { if (arg0.keyMask < arg1.keyMask) { return -1; } else if (arg0.keyMask > arg1.keyMask) { return 1; } return 0; } }); return keys; } }
false
true
private int formatKeys(final Grid lists, int row, final int col, final KeyCommandSet set, final SafeHtml prefix) { final CellFormatter fmt = lists.getCellFormatter(); final int initialRow = row; final List<KeyCommand> keys = sort(set); if (lists.getRowCount() < row + keys.size()) { lists.resizeRows(row + keys.size()); } FORMAT_KEYS: for (int i = 0; i < keys.size(); i++) { final KeyCommand k = keys.get(i); if (k instanceof CompoundKeyCommand) { final SafeHtmlBuilder b = new SafeHtmlBuilder(); b.append(k.describeKeyStroke()); row = formatKeys(lists, row, col, ((CompoundKeyCommand) k).getSet(), b); continue; } for (int prior = 0, r = initialRow; prior < i; prior++) { if (KeyCommand.same(keys.get(prior), k)) { final SafeHtmlBuilder b = new SafeHtmlBuilder(); b.append(SafeHtml.get(lists, r, col + 0)); b.append(" "); b.append(KeyConstants.I.orOtherKey()); b.append(" "); if (prefix != null) { b.append(prefix); b.append(" "); b.append(KeyConstants.I.thenOtherKey()); b.append(" "); } b.append(k.describeKeyStroke()); SafeHtml.set(lists, r, col + 0, b); continue FORMAT_KEYS; } } if (prefix != null) { final SafeHtmlBuilder b = new SafeHtmlBuilder(); b.append(prefix); b.append(" "); b.append(KeyConstants.I.thenOtherKey()); b.append(" "); b.append(k.describeKeyStroke()); SafeHtml.set(lists, row, col + 0, b); } else { SafeHtml.set(lists, row, col + 0, k.describeKeyStroke()); } lists.setText(row, col + 1, ":"); lists.setText(row, col + 2, k.getHelpText()); fmt.addStyleName(row, col + 0, KeyResources.I.css().helpKeyStroke()); fmt.addStyleName(row, col + 1, KeyResources.I.css().helpSeparator()); row++; } return row; }
private int formatKeys(final Grid lists, int row, final int col, final KeyCommandSet set, final SafeHtml prefix) { final CellFormatter fmt = lists.getCellFormatter(); final int initialRow = row; final List<KeyCommand> keys = sort(set); if (lists.getRowCount() < row + keys.size()) { lists.resizeRows(row + keys.size()); } FORMAT_KEYS: for (int i = 0; i < keys.size(); i++) { final KeyCommand k = keys.get(i); if (k instanceof CompoundKeyCommand) { final SafeHtmlBuilder b = new SafeHtmlBuilder(); b.append(k.describeKeyStroke()); row = formatKeys(lists, row, col, ((CompoundKeyCommand) k).getSet(), b); continue; } for (int prior = 0; prior < i; prior++) { if (KeyCommand.same(keys.get(prior), k)) { final int r = initialRow + prior; final SafeHtmlBuilder b = new SafeHtmlBuilder(); b.append(SafeHtml.get(lists, r, col + 0)); b.append(" "); b.append(KeyConstants.I.orOtherKey()); b.append(" "); if (prefix != null) { b.append(prefix); b.append(" "); b.append(KeyConstants.I.thenOtherKey()); b.append(" "); } b.append(k.describeKeyStroke()); SafeHtml.set(lists, r, col + 0, b); continue FORMAT_KEYS; } } if (prefix != null) { final SafeHtmlBuilder b = new SafeHtmlBuilder(); b.append(prefix); b.append(" "); b.append(KeyConstants.I.thenOtherKey()); b.append(" "); b.append(k.describeKeyStroke()); SafeHtml.set(lists, row, col + 0, b); } else { SafeHtml.set(lists, row, col + 0, k.describeKeyStroke()); } lists.setText(row, col + 1, ":"); lists.setText(row, col + 2, k.getHelpText()); fmt.addStyleName(row, col + 0, KeyResources.I.css().helpKeyStroke()); fmt.addStyleName(row, col + 1, KeyResources.I.css().helpSeparator()); row++; } return row; }
diff --git a/javasrc/src/org/ccnx/ccn/test/protocol/LatestVersionTest.java b/javasrc/src/org/ccnx/ccn/test/protocol/LatestVersionTest.java index e3db6a6c2..8bf5a316d 100644 --- a/javasrc/src/org/ccnx/ccn/test/protocol/LatestVersionTest.java +++ b/javasrc/src/org/ccnx/ccn/test/protocol/LatestVersionTest.java @@ -1,701 +1,701 @@ /* * A CCNx library test. * * Copyright (C) 2008, 2009, 2010, 2011 Palo Alto Research Center, Inc. * * This work 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 work 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 org.ccnx.ccn.test.protocol; import java.io.IOException; import java.util.ArrayList; import java.util.logging.Level; import org.ccnx.ccn.CCNFilterListener; import org.ccnx.ccn.CCNHandle; import org.ccnx.ccn.ContentVerifier; import org.ccnx.ccn.config.SystemConfiguration; import org.ccnx.ccn.impl.support.Log; import org.ccnx.ccn.profiles.SegmentationProfile; import org.ccnx.ccn.profiles.VersionMissingException; import org.ccnx.ccn.profiles.VersioningProfile; import org.ccnx.ccn.protocol.CCNTime; import org.ccnx.ccn.protocol.ContentName; import org.ccnx.ccn.protocol.ContentObject; import org.ccnx.ccn.protocol.Interest; import org.ccnx.ccn.test.AssertionCCNHandle; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; /** * This test checks if we can actually get the latest version using the getLatestVersion * method in VersioningProfile. * * The current implementation of getLatestVersion does not loop to try and find the latest version. * It reports the latest available with a single interest. The second part of this test is commented out * due to this limitation. This will be activated when an alternate to getLatestVersion is supplied in * the implementation or getLatestVersion is modified. getLatestVersion currently does not loop looking * for newer version to avoid suffering timeouts when there is not an newer version available. */ public class LatestVersionTest { static final long WAIT_TIME = 500; static CCNHandle getHandle; static CCNHandle responderHandle; ContentName baseName; public static ContentObject lastVersionPublished = null; public static ContentName pingResponder = null; public static ArrayList<ContentObject> responseObjects = null; public static ContentObject failVerify = null; public static ContentObject failVerify1 = null; public static ContentObject failVerify2 = null; public static ContentObject failVerify4 = null; Responder responder; /** * @throws java.lang.Exception */ @Before public void setUp() throws Exception { Log.setDefaultLevel(Level.FINEST); getHandle = CCNHandle.open(); baseName = ContentName.fromURI("/ccnx.org/test/latestVersionTest/"+(new CCNTime()).toShortString()); responder = new Responder(); } @After public void tearDown() { getHandle.close(); responderHandle.close(); } /** * Test to check if the getLatestVersion method in VersioningProfile gets the latest version with a ccnd involved. * @throws Error * @throws InterruptedException */ @Test public void getLatestVersion() throws InterruptedException, Error { ContentName one = null; ContentName two = null; ContentName three = null; ContentName four = null; ContentName skipSegment = null; ContentName skipSegment0 = null; ContentName skipSegment2 = null; ContentObject obj1 = null; ContentObject obj2 = null; ContentObject obj3 = null; ContentObject obj4 = null; ContentObject objSkip = null; ContentObject objSkip0 = null; ContentObject objSkip2 = null; ContentObject object = null; responseObjects = new ArrayList<ContentObject>(); checkResponder(); CCNTime t1; CCNTime t2; CCNTime t3; CCNTime t4; CCNTime skipTime; CCNTime skipTime2; long timeout = 5000; t1 = new CCNTime(); one = SegmentationProfile.segmentName(VersioningProfile.addVersion(baseName, t1), 0); obj1 = ContentObject.buildContentObject(one, "here is version 1".getBytes(), null, null, SegmentationProfile.getSegmentNumberNameComponent(0)); t2 = (CCNTime)t1.clone(); t2.increment(1); two = SegmentationProfile.segmentName(VersioningProfile.addVersion(baseName, t2), 0); obj2 = ContentObject.buildContentObject(two, "here is version 2".getBytes(), null, null, SegmentationProfile.getSegmentNumberNameComponent(0)); t3 = (CCNTime) t1.clone(); t3.increment(2); three = SegmentationProfile.segmentName(VersioningProfile.addVersion(baseName, t3), 0); obj3 = ContentObject.buildContentObject(three, "here is version 3".getBytes(), null, null, SegmentationProfile.getSegmentNumberNameComponent(0)); t4 = (CCNTime)t1.clone(); t4.increment(3); four = SegmentationProfile.segmentName(VersioningProfile.addVersion(baseName, t4), 0); obj4 = ContentObject.buildContentObject(four, "here is version 4".getBytes(), null, null, SegmentationProfile.getSegmentNumberNameComponent(0)); skipTime = (CCNTime)t1.clone(); skipTime.increment(4); skipSegment = SegmentationProfile.segmentName(VersioningProfile.addVersion(baseName, skipTime), 5); objSkip = ContentObject.buildContentObject(skipSegment, "here is skip".getBytes(), null, null, SegmentationProfile.getSegmentNumberNameComponent(5)); skipSegment0 = SegmentationProfile.segmentName(VersioningProfile.addVersion(baseName, skipTime), 0); objSkip0 = ContentObject.buildContentObject(skipSegment0, "here is skip".getBytes(), null, null, SegmentationProfile.getSegmentNumberNameComponent(5)); skipTime2 = (CCNTime)t1.clone(); skipTime2.increment(5); skipSegment2 = SegmentationProfile.segmentName(VersioningProfile.addVersion(baseName, skipTime2), 5); objSkip2 = ContentObject.buildContentObject(skipSegment2, "here is skip 2".getBytes(), null, null, SegmentationProfile.getSegmentNumberNameComponent(5)); System.out.println("made versions: "+one +" "+two+" "+three+" "+four+" "+skipTime+" "+skipTime2); Assert.assertTrue(t1.before(t2)); Assert.assertTrue(t2.before(t3)); Assert.assertTrue(t3.before(t4)); Assert.assertTrue(t4.before(skipTime)); Assert.assertTrue(skipTime.before(skipTime2)); try { responderHandle.put(obj1); responderHandle.put(obj2); object = VersioningProfile.getLatestVersion(baseName, null, timeout, getHandle.defaultVerifier(), getHandle); responder.checkError(); Assert.assertNotNull(object); Assert.assertTrue(VersioningProfile.getLastVersionAsLong(object.name()) == VersioningProfile.getLastVersionAsLong(two)); System.out.println("passed test for getLatestVersion with 2 versions available"); object = VersioningProfile.getFirstBlockOfLatestVersion(baseName, null, null, timeout, getHandle.defaultVerifier(), getHandle); responder.checkError(); Assert.assertNotNull(object); Assert.assertTrue(VersioningProfile.getLastVersionAsLong(object.name()) == VersioningProfile.getLastVersionAsLong(two)); System.out.println("passed test for getFirstBlockOfLatestVersion with 2 versions available"); Assert.assertTrue(responseObjects.size() == 0); } catch (IOException e) { Assert.fail("Failed to get latest version: "+e.getMessage()); } catch (VersionMissingException e) { Assert.fail("Failed to get version from object: "+e.getMessage()); } responder.checkError(); responseObjects.add(obj3); System.out.println("added: "+obj3.name()); //now put third version try { System.out.println("calling gLV at: "+System.currentTimeMillis()); object = VersioningProfile.getLatestVersion(baseName, null, timeout, getHandle.defaultVerifier(), getHandle); responder.checkError(); Assert.assertNotNull(object); System.out.println("got: "+object.name()); System.out.println("expecting to get: "+three); Assert.assertTrue(VersioningProfile.getLastVersionAsLong(object.name()) == VersioningProfile.getLastVersionAsLong(three)); System.out.println("passed test for getLatestVersion with 3 versions available"); object = VersioningProfile.getFirstBlockOfLatestVersion(baseName, null, null, timeout, getHandle.defaultVerifier(), getHandle); responder.checkError(); Assert.assertNotNull(object); Assert.assertTrue(VersioningProfile.getLastVersionAsLong(object.name()) == VersioningProfile.getLastVersionAsLong(three)); System.out.println("passed test for getFirstBlockOfLatestVersion with 3 versions available"); Assert.assertTrue(responseObjects.size() == 0); } catch (VersionMissingException e) { Assert.fail("Failed to get version from object: "+e.getMessage()); } catch (IOException e) { Assert.fail("Failed to get latest version: "+e.getMessage()); } //now make sure we can get the latest version with an explicit request for //something after version 2 try { object = VersioningProfile.getLatestVersion(two, null, timeout, getHandle.defaultVerifier(), getHandle); responder.checkError(); Assert.assertTrue(VersioningProfile.getLastVersionAsLong(object.name()) == VersioningProfile.getLastVersionAsLong(three)); Assert.assertTrue(responseObjects.size() == 0); } catch (IOException e) { Assert.fail("Failed to get latest version: "+e.getMessage()); } catch (VersionMissingException e) { Assert.fail("Failed to get version from object: "+e.getMessage()); } //now check to make sure when we ask for a later version (that does not exist) that we don't wait too long. //first wait for 5 seconds, then 200ms try { long doneTime; long checkTime = System.currentTimeMillis(); object = VersioningProfile.getFirstBlockOfLatestVersion(three, null, null, 5000, getHandle.defaultVerifier(), getHandle); - responder.checkError(); doneTime = System.currentTimeMillis(); System.out.println("took us "+(doneTime - checkTime)+"ms to get nothing back "+" check: "+checkTime+" done: "+doneTime); + responder.checkError(); Assert.assertNull(object); Assert.assertTrue((doneTime - checkTime) < 5500 && (doneTime - checkTime) >= 5000); System.out.println("passed test for waiting 5 seconds"); checkTime = System.currentTimeMillis(); object = VersioningProfile.getFirstBlockOfLatestVersion(three, null, null, 200, getHandle.defaultVerifier(), getHandle); - responder.checkError(); checkTime = System.currentTimeMillis() - checkTime; + responder.checkError(); System.out.println("took us "+checkTime+"ms to get nothing back"); Assert.assertNull(object); Assert.assertTrue(checkTime >= 200 && checkTime < 300); System.out.println("passed test for waiting 200ms"); Assert.assertTrue(responseObjects.size() == 0); } catch (IOException e) { Assert.fail("failed to test with different timeouts: "+e.getMessage()); } responseObjects.add(obj4); //add a fourth responder and make sure we don't get it back. try { lastVersionPublished = obj4; object = VersioningProfile.getFirstBlockOfLatestVersion(baseName, null, null, 0, getHandle.defaultVerifier(), getHandle); responder.checkError(); Assert.assertNotNull(object); Assert.assertTrue(VersioningProfile.getLastVersionAsLong(object.name()) == VersioningProfile.getLastVersionAsLong(three)); System.out.println("passed test for timeout 0 test"); object = VersioningProfile.getFirstBlockOfLatestVersion(baseName, null, null, 0, getHandle.defaultVerifier(), getHandle); responder.checkError(); Assert.assertNotNull(object); Assert.assertTrue(VersioningProfile.getLastVersionAsLong(object.name()) == VersioningProfile.getLastVersionAsLong(three)); System.out.println("passed test for timeout 0 test"); } catch (IOException e) { Assert.fail("failed to test with timeout of 0: "+e.getMessage()); } catch (VersionMissingException e) { Assert.fail("failed to test with timeout of 0: "+e.getMessage()); } //need to clear out segment 4 from our responder //now make sure we can get the latest version with an explicit request for //something after version 2 try { object = VersioningProfile.getLatestVersion(two, null, timeout, getHandle.defaultVerifier(), getHandle); responder.checkError(); Assert.assertNotNull(object); Assert.assertTrue(VersioningProfile.getLastVersionAsLong(object.name()) == VersioningProfile.getLastVersionAsLong(four)); Assert.assertTrue(responseObjects.size() == 0); } catch (IOException e) { Assert.fail("Failed to get latest version: "+e.getMessage()); } catch (VersionMissingException e) { Assert.fail("Failed to get version from object: "+e.getMessage()); } //test for getting the first segment of a version that does not have a first segment //put a later segment of a later version and make sure it comes back with null or an earlier version try { System.out.println("=========testing skip segment!"); responderHandle.put(objSkip); object = VersioningProfile.getLatestVersion(baseName, null, timeout, getHandle.defaultVerifier(), getHandle); responder.checkError(); Assert.assertNotNull(object); Assert.assertTrue(VersioningProfile.getLastVersionAsLong(object.name()) == VersioningProfile.getLastVersionAsLong(skipSegment)); System.out.println("passed test for getLatestVersion with skipped segment available"); System.out.println("adding: "+objSkip0.name()); responseObjects.add(objSkip0); System.out.println("adding: "+objSkip2.name()); responseObjects.add(objSkip2); object = VersioningProfile.getFirstBlockOfLatestVersion(baseName, null, null, timeout, getHandle.defaultVerifier(), getHandle); responder.checkError(); Assert.assertNotNull(object); Assert.assertTrue(VersioningProfile.getLastVersionAsLong(object.name()) == VersioningProfile.getLastVersionAsLong(skipSegment0)); System.out.println("passed test for getFirstBlockOfLatestVersion with skipped segment available"); Assert.assertTrue(responseObjects.size() == 0); } catch (IOException e) { Assert.fail("Failed to get latest version: "+e.getMessage()); } catch (VersionMissingException e) { Assert.fail("Failed to get version from object: "+e.getMessage()); } //now put 15 responses in.... CCNTime versionToAdd = new CCNTime(); for(int i = 0; i < SystemConfiguration.GET_LATEST_VERSION_ATTEMPTS + 5; i++) { versionToAdd.increment(1); responseObjects.add(ContentObject.buildContentObject(SegmentationProfile.segmentName(VersioningProfile.addVersion(baseName, versionToAdd), 0), "here is version generated".getBytes(), null, null, SegmentationProfile.getSegmentNumberNameComponent(0))); System.out.println("created version with time: "+versionToAdd+" object name: "+responseObjects.get(i).fullName()); } lastVersionPublished = responseObjects.get(responseObjects.size()-1); //test for sending in a null timeout try { object = VersioningProfile.getLatestVersion(baseName, null, SystemConfiguration.NO_TIMEOUT, getHandle.defaultVerifier(), getHandle); responder.checkError(); Assert.assertNotNull(object); System.out.println("got back :"+object.name()); Assert.assertTrue(object.name().equals(lastVersionPublished.name())); System.out.println("passed test for no timeout"); for(int i =0; i < SystemConfiguration.GET_LATEST_VERSION_ATTEMPTS; i++) { versionToAdd.increment(1); responseObjects.add(ContentObject.buildContentObject(SegmentationProfile.segmentName(VersioningProfile.addVersion(baseName, versionToAdd), 0), "here is version generated".getBytes(), null, null, SegmentationProfile.getSegmentNumberNameComponent(0))); System.out.println("created version with time: "+versionToAdd+" object name: "+responseObjects.get(i).fullName()); } lastVersionPublished = responseObjects.get(responseObjects.size()-1); object = VersioningProfile.getFirstBlockOfLatestVersion(baseName, null, null, SystemConfiguration.NO_TIMEOUT, getHandle.defaultVerifier(), getHandle); responder.checkError(); Assert.assertNotNull(object); Assert.assertTrue(object.name().equals(lastVersionPublished.name())); System.out.println("passed test for no timeout"); Assert.assertTrue(responseObjects.size() == 0); } catch (IOException e) { Assert.fail("failed to test with no timeout: "+e.getMessage()); } // Note by paul r. I'm not sure why we need to have a "responder" here in the first place - as opposed to just simply // putting the test objects to ccnd. But once we have a verifier, there's a potential race between the verifier and responder i.e. // we can call the verifier before the responder or vice-versa so we can't guarantee what's actually going to show up in the // verifier because the objects we expect to see may not have been output by the responder yet. I've fixed this (I hope!) by // doing an explicit get of the objects in question before we try the test so that the responder has definitely done a put // of the objects we are trying to test ContentVerifier ver = new TestVerifier(); //have the verifier fail the newest object make sure we get back the most recent verified version versionToAdd.increment(1); failVerify = ContentObject.buildContentObject(SegmentationProfile.segmentName(VersioningProfile.addVersion(baseName, versionToAdd), 0), "here is failVerify".getBytes(), null, null, SegmentationProfile.getSegmentNumberNameComponent(0)); responseObjects.add(failVerify); try { getHandle.get(failVerify.fullName(), timeout); responder.checkError(); } catch (IOException e1) { Assert.fail("Failed get: "+e1.getMessage()); } //now put a unverifiable version try { object = VersioningProfile.getLatestVersion(baseName, null, timeout, ver, getHandle); responder.checkError(); Assert.assertNotNull(object); System.out.println("got: "+object.name()); System.out.println("expecting to get: "+lastVersionPublished.name()); Assert.assertTrue(VersioningProfile.getLastVersionAsLong(object.name()) == VersioningProfile.getLastVersionAsLong(lastVersionPublished.name())); System.out.println("passed test for failed verification"); object = VersioningProfile.getFirstBlockOfLatestVersion(baseName, null, null, timeout, ver, getHandle); responder.checkError(); System.out.println("expecting to get: "+lastVersionPublished.name()); Assert.assertNotNull(object); System.out.println("got: "+object.name()); Assert.assertTrue(VersioningProfile.getLastVersionAsLong(object.name()) == VersioningProfile.getLastVersionAsLong(lastVersionPublished.name())); System.out.println("passed test for getFirstBlockOfLatestVersion failed verification"); Assert.assertTrue(responseObjects.size() == 0); } catch (VersionMissingException e) { Assert.fail("Failed to get version from object: "+e.getMessage()); } catch (IOException e) { Assert.fail("Failed to get latest version: "+e.getMessage()); } //then call again and make sure we have a newer version that passes //have the verifier fail the newest object make sure we get back the most recent verified version versionToAdd.increment(1); ContentObject verify = ContentObject.buildContentObject(SegmentationProfile.segmentName(VersioningProfile.addVersion(baseName, versionToAdd), 0), "here is verify".getBytes(), null, null, SegmentationProfile.getSegmentNumberNameComponent(0)); responseObjects.add(verify); try { getHandle.get(verify.fullName(), timeout); responder.checkError(); } catch (IOException e1) { Assert.fail("Failed get: "+e1.getMessage()); } //now put a verifiable version try { object = VersioningProfile.getLatestVersion(baseName, null, timeout, ver, getHandle); responder.checkError(); Assert.assertNotNull(object); System.out.println("got: "+object.name()); System.out.println("expecting to get: "+verify.name()); Assert.assertTrue(VersioningProfile.getLastVersionAsLong(object.name()) == VersioningProfile.getLastVersionAsLong(verify.name())); System.out.println("passed test for failed verification with newer version available"); object = VersioningProfile.getFirstBlockOfLatestVersion(baseName, null, null, timeout, ver, getHandle); responder.checkError(); Assert.assertNotNull(object); Assert.assertTrue(VersioningProfile.getLastVersionAsLong(object.name()) == VersioningProfile.getLastVersionAsLong(verify.name())); System.out.println("passed test for getFirstBlockOfLatestVersion failed verification with newer version available"); Assert.assertTrue(responseObjects.size() == 0); } catch (VersionMissingException e) { Assert.fail("Failed to get version from object: "+e.getMessage()); } catch (IOException e) { Assert.fail("Failed to get latest version: "+e.getMessage()); } //test that also has a content object that fails to verify (maybe do 2) //and then also add one that does verify - same version. make sure we get the verifiable one back versionToAdd.increment(1); failVerify1 = ContentObject.buildContentObject(SegmentationProfile.segmentName(VersioningProfile.addVersion(baseName, versionToAdd), 0), "here is failVerify".getBytes(), null, null, SegmentationProfile.getSegmentNumberNameComponent(0)); responseObjects.add(failVerify1); failVerify2 = ContentObject.buildContentObject(SegmentationProfile.segmentName(VersioningProfile.addVersion(baseName, versionToAdd), 0), "here is a second failVerify".getBytes(), null, null, SegmentationProfile.getSegmentNumberNameComponent(0)); responseObjects.add(failVerify2); ContentObject failVerify3 = ContentObject.buildContentObject(SegmentationProfile.segmentName(VersioningProfile.addVersion(baseName, versionToAdd), 0), "here is a third, but it should pass".getBytes(), null, null, SegmentationProfile.getSegmentNumberNameComponent(0)); responseObjects.add(failVerify3); try { getHandle.get(failVerify1.fullName(), timeout); responder.checkError(); getHandle.get(failVerify2.fullName(), timeout); responder.checkError(); getHandle.get(failVerify3.fullName(), timeout); responder.checkError(); } catch (IOException e1) { Assert.fail("Failed get: "+e1.getMessage()); } System.out.println("failVerify1*: "+failVerify1.fullName()); System.out.println("failVerify2*: "+failVerify2.fullName()); System.out.println("failVerify3: "+failVerify3.fullName()); try { object = VersioningProfile.getLatestVersion(baseName, null, timeout, ver, getHandle); responder.checkError(); Assert.assertNotNull(object); System.out.println("got: "+object.fullName()); System.out.println("expecting to get: "+failVerify3.fullName()); Assert.assertTrue(VersioningProfile.getLastVersionAsLong(object.fullName()) == VersioningProfile.getLastVersionAsLong(failVerify3.fullName())); System.out.println("passed test for failed verification with multiple failures and a success"); object = VersioningProfile.getFirstBlockOfLatestVersion(baseName, null, null, timeout, ver, getHandle); responder.checkError(); Assert.assertNotNull(object); System.out.println("got: "+object.fullName()); System.out.println("expecting to get: "+failVerify3.fullName()); Assert.assertTrue(VersioningProfile.getLastVersionAsLong(object.fullName()) == VersioningProfile.getLastVersionAsLong(failVerify3.fullName())); System.out.println("passed test for getFirstBlockOfLatestVersion failed verification with multiple failures and a success"); Assert.assertTrue(responseObjects.size() == 0); } catch (VersionMissingException e) { Assert.fail("Failed to get version from object: "+e.getMessage()); } catch (IOException e) { Assert.fail("Failed to get latest version: "+e.getMessage()); } //test that checks a combo of a version without a first segment with a failed verification //after it. should return the non 0 segment for the first part, and the last published first segment //for the second part of the test responseObjects.clear(); versionToAdd.increment(1); ContentObject objSkip3 = ContentObject.buildContentObject(SegmentationProfile.segmentName(VersioningProfile.addVersion(baseName, versionToAdd), 5), "here is skip 3".getBytes(), null, null, SegmentationProfile.getSegmentNumberNameComponent(5)); responseObjects.add(objSkip3); versionToAdd.increment(1); failVerify4 = ContentObject.buildContentObject(SegmentationProfile.segmentName(VersioningProfile.addVersion(baseName, versionToAdd), 0), "here is a fourth verify, it should fail".getBytes(), null, null, SegmentationProfile.getSegmentNumberNameComponent(0)); responseObjects.add(failVerify4); try { getHandle.get(objSkip3.fullName(), timeout); responder.checkError(); getHandle.get(failVerify4.fullName(), timeout); responder.checkError(); } catch (IOException e1) { Assert.fail("Failed get: "+e1.getMessage()); } System.out.println("objSkip3: "+ objSkip3.fullName()); System.out.println("failVerify4*: "+failVerify4.fullName()); try { object = VersioningProfile.getLatestVersion(baseName, null, timeout, ver, getHandle); responder.checkError(); Assert.assertNotNull(object); System.out.println("got: "+object.fullName()); System.out.println("expecting to get: "+objSkip3.fullName()); Assert.assertTrue(VersioningProfile.getLastVersionAsLong(object.fullName()) == VersioningProfile.getLastVersionAsLong(objSkip3.fullName())); System.out.println("passed test for missing first segment + failed verification"); object = VersioningProfile.getFirstBlockOfLatestVersion(baseName, null, null, timeout, ver, getHandle); responder.checkError(); Assert.assertNotNull(object); System.out.println("got: "+object.fullName()); System.out.println("expecting to get: "+failVerify3.fullName()); Assert.assertTrue(VersioningProfile.getLastVersionAsLong(object.fullName()) == VersioningProfile.getLastVersionAsLong(failVerify3.fullName())); System.out.println("passed test for missing first segment + failed verification"); Assert.assertTrue(responseObjects.size() == 0); } catch (VersionMissingException e) { Assert.fail("Failed to get version from object: "+e.getMessage()); } catch (IOException e) { Assert.fail("Failed to get latest version: "+e.getMessage()); } responder.checkError(); } private void checkResponder() throws InterruptedException, Error { try { ContentName test = ContentName.fromNative(baseName, "testResponder"); ContentObject co = ContentObject.buildContentObject(SegmentationProfile.segmentName(VersioningProfile.addVersion(test), 0), "test content responder".getBytes(), null, null, SegmentationProfile.getSegmentNumberNameComponent(0)); responseObjects.add(co); Interest i = new Interest(co.name()); ContentObject co2 = getHandle.get(i, 5000 ); responder.checkError(); if (co2 == null) { System.out.println("test responder object is null, failed to start responder in 5 seconds"); Assert.fail("test responder did not start up in 5 seconds."); } Assert.assertTrue(co2.fullName().equals(co.fullName())); System.out.println("Responder is up and ready!"); } catch (IOException e) { Assert.fail("could not get test responder object: "+e.getMessage()); } } /** * Runnable class for the single ContentObject responder. */ class Responder implements CCNFilterListener { AssertionCCNHandle handle; public Responder() throws IOException { try { handle = AssertionCCNHandle.open(); LatestVersionTest.responderHandle = handle; } catch (Exception e) { Assert.fail("could not create handle for responder: " + e.getMessage()); } handle.registerFilter(baseName, this); } public boolean handleInterest(Interest interest) { System.out.println(System.currentTimeMillis()+ " handling interest "+ interest.name()); System.out.println("current objects: "); for(ContentObject o: responseObjects) System.out.println(o.fullName()); if(responseObjects.size() == 0) { System.out.println("responseObjects size == 0"); return false; } if (interest.matches(responseObjects.get(0))) { try { System.out.println("returning: "+ responseObjects.get(0).fullName()); handle.put(responseObjects.remove(0)); return true; } catch (IOException e) { Assert.fail("could not put object in responder"); return false; } } else { System.out.println("didn't have a match with: "+responseObjects.get(0).fullName()); System.out.println("full interest: "+interest.toString()); return false; } } public void checkError() throws Error, InterruptedException { handle.checkError(WAIT_TIME); } } class TestVerifier implements ContentVerifier{ public boolean verify(ContentObject content) { System.out.println("VERIFIER: "+content.fullName()); ContentName contentName = content.fullName(); if ( failVerify != null ) { if (contentName.equals(failVerify.fullName())) return false; } else System.out.println("failVerify was null"); if ( failVerify2 != null ) { System.out.println("failVerify1*: "+failVerify1.fullName()); System.out.println("failVerify2*: "+failVerify2.fullName()); System.out.println("contentName: "+content.fullName()); if (contentName.equals(failVerify1.fullName()) || contentName.equals(failVerify2.fullName())) return false; } else System.out.println("failVerify2 was null"); if ( failVerify4 != null ) { if (contentName.equals(failVerify4.fullName())) return false; } else System.out.println("failVerify4 was null"); System.out.println("resorting to default verifier"); return LatestVersionTest.getHandle.defaultVerifier().verify(content); } } }
false
true
public void getLatestVersion() throws InterruptedException, Error { ContentName one = null; ContentName two = null; ContentName three = null; ContentName four = null; ContentName skipSegment = null; ContentName skipSegment0 = null; ContentName skipSegment2 = null; ContentObject obj1 = null; ContentObject obj2 = null; ContentObject obj3 = null; ContentObject obj4 = null; ContentObject objSkip = null; ContentObject objSkip0 = null; ContentObject objSkip2 = null; ContentObject object = null; responseObjects = new ArrayList<ContentObject>(); checkResponder(); CCNTime t1; CCNTime t2; CCNTime t3; CCNTime t4; CCNTime skipTime; CCNTime skipTime2; long timeout = 5000; t1 = new CCNTime(); one = SegmentationProfile.segmentName(VersioningProfile.addVersion(baseName, t1), 0); obj1 = ContentObject.buildContentObject(one, "here is version 1".getBytes(), null, null, SegmentationProfile.getSegmentNumberNameComponent(0)); t2 = (CCNTime)t1.clone(); t2.increment(1); two = SegmentationProfile.segmentName(VersioningProfile.addVersion(baseName, t2), 0); obj2 = ContentObject.buildContentObject(two, "here is version 2".getBytes(), null, null, SegmentationProfile.getSegmentNumberNameComponent(0)); t3 = (CCNTime) t1.clone(); t3.increment(2); three = SegmentationProfile.segmentName(VersioningProfile.addVersion(baseName, t3), 0); obj3 = ContentObject.buildContentObject(three, "here is version 3".getBytes(), null, null, SegmentationProfile.getSegmentNumberNameComponent(0)); t4 = (CCNTime)t1.clone(); t4.increment(3); four = SegmentationProfile.segmentName(VersioningProfile.addVersion(baseName, t4), 0); obj4 = ContentObject.buildContentObject(four, "here is version 4".getBytes(), null, null, SegmentationProfile.getSegmentNumberNameComponent(0)); skipTime = (CCNTime)t1.clone(); skipTime.increment(4); skipSegment = SegmentationProfile.segmentName(VersioningProfile.addVersion(baseName, skipTime), 5); objSkip = ContentObject.buildContentObject(skipSegment, "here is skip".getBytes(), null, null, SegmentationProfile.getSegmentNumberNameComponent(5)); skipSegment0 = SegmentationProfile.segmentName(VersioningProfile.addVersion(baseName, skipTime), 0); objSkip0 = ContentObject.buildContentObject(skipSegment0, "here is skip".getBytes(), null, null, SegmentationProfile.getSegmentNumberNameComponent(5)); skipTime2 = (CCNTime)t1.clone(); skipTime2.increment(5); skipSegment2 = SegmentationProfile.segmentName(VersioningProfile.addVersion(baseName, skipTime2), 5); objSkip2 = ContentObject.buildContentObject(skipSegment2, "here is skip 2".getBytes(), null, null, SegmentationProfile.getSegmentNumberNameComponent(5)); System.out.println("made versions: "+one +" "+two+" "+three+" "+four+" "+skipTime+" "+skipTime2); Assert.assertTrue(t1.before(t2)); Assert.assertTrue(t2.before(t3)); Assert.assertTrue(t3.before(t4)); Assert.assertTrue(t4.before(skipTime)); Assert.assertTrue(skipTime.before(skipTime2)); try { responderHandle.put(obj1); responderHandle.put(obj2); object = VersioningProfile.getLatestVersion(baseName, null, timeout, getHandle.defaultVerifier(), getHandle); responder.checkError(); Assert.assertNotNull(object); Assert.assertTrue(VersioningProfile.getLastVersionAsLong(object.name()) == VersioningProfile.getLastVersionAsLong(two)); System.out.println("passed test for getLatestVersion with 2 versions available"); object = VersioningProfile.getFirstBlockOfLatestVersion(baseName, null, null, timeout, getHandle.defaultVerifier(), getHandle); responder.checkError(); Assert.assertNotNull(object); Assert.assertTrue(VersioningProfile.getLastVersionAsLong(object.name()) == VersioningProfile.getLastVersionAsLong(two)); System.out.println("passed test for getFirstBlockOfLatestVersion with 2 versions available"); Assert.assertTrue(responseObjects.size() == 0); } catch (IOException e) { Assert.fail("Failed to get latest version: "+e.getMessage()); } catch (VersionMissingException e) { Assert.fail("Failed to get version from object: "+e.getMessage()); } responder.checkError(); responseObjects.add(obj3); System.out.println("added: "+obj3.name()); //now put third version try { System.out.println("calling gLV at: "+System.currentTimeMillis()); object = VersioningProfile.getLatestVersion(baseName, null, timeout, getHandle.defaultVerifier(), getHandle); responder.checkError(); Assert.assertNotNull(object); System.out.println("got: "+object.name()); System.out.println("expecting to get: "+three); Assert.assertTrue(VersioningProfile.getLastVersionAsLong(object.name()) == VersioningProfile.getLastVersionAsLong(three)); System.out.println("passed test for getLatestVersion with 3 versions available"); object = VersioningProfile.getFirstBlockOfLatestVersion(baseName, null, null, timeout, getHandle.defaultVerifier(), getHandle); responder.checkError(); Assert.assertNotNull(object); Assert.assertTrue(VersioningProfile.getLastVersionAsLong(object.name()) == VersioningProfile.getLastVersionAsLong(three)); System.out.println("passed test for getFirstBlockOfLatestVersion with 3 versions available"); Assert.assertTrue(responseObjects.size() == 0); } catch (VersionMissingException e) { Assert.fail("Failed to get version from object: "+e.getMessage()); } catch (IOException e) { Assert.fail("Failed to get latest version: "+e.getMessage()); } //now make sure we can get the latest version with an explicit request for //something after version 2 try { object = VersioningProfile.getLatestVersion(two, null, timeout, getHandle.defaultVerifier(), getHandle); responder.checkError(); Assert.assertTrue(VersioningProfile.getLastVersionAsLong(object.name()) == VersioningProfile.getLastVersionAsLong(three)); Assert.assertTrue(responseObjects.size() == 0); } catch (IOException e) { Assert.fail("Failed to get latest version: "+e.getMessage()); } catch (VersionMissingException e) { Assert.fail("Failed to get version from object: "+e.getMessage()); } //now check to make sure when we ask for a later version (that does not exist) that we don't wait too long. //first wait for 5 seconds, then 200ms try { long doneTime; long checkTime = System.currentTimeMillis(); object = VersioningProfile.getFirstBlockOfLatestVersion(three, null, null, 5000, getHandle.defaultVerifier(), getHandle); responder.checkError(); doneTime = System.currentTimeMillis(); System.out.println("took us "+(doneTime - checkTime)+"ms to get nothing back "+" check: "+checkTime+" done: "+doneTime); Assert.assertNull(object); Assert.assertTrue((doneTime - checkTime) < 5500 && (doneTime - checkTime) >= 5000); System.out.println("passed test for waiting 5 seconds"); checkTime = System.currentTimeMillis(); object = VersioningProfile.getFirstBlockOfLatestVersion(three, null, null, 200, getHandle.defaultVerifier(), getHandle); responder.checkError(); checkTime = System.currentTimeMillis() - checkTime; System.out.println("took us "+checkTime+"ms to get nothing back"); Assert.assertNull(object); Assert.assertTrue(checkTime >= 200 && checkTime < 300); System.out.println("passed test for waiting 200ms"); Assert.assertTrue(responseObjects.size() == 0); } catch (IOException e) { Assert.fail("failed to test with different timeouts: "+e.getMessage()); } responseObjects.add(obj4); //add a fourth responder and make sure we don't get it back. try { lastVersionPublished = obj4; object = VersioningProfile.getFirstBlockOfLatestVersion(baseName, null, null, 0, getHandle.defaultVerifier(), getHandle); responder.checkError(); Assert.assertNotNull(object); Assert.assertTrue(VersioningProfile.getLastVersionAsLong(object.name()) == VersioningProfile.getLastVersionAsLong(three)); System.out.println("passed test for timeout 0 test"); object = VersioningProfile.getFirstBlockOfLatestVersion(baseName, null, null, 0, getHandle.defaultVerifier(), getHandle); responder.checkError(); Assert.assertNotNull(object); Assert.assertTrue(VersioningProfile.getLastVersionAsLong(object.name()) == VersioningProfile.getLastVersionAsLong(three)); System.out.println("passed test for timeout 0 test"); } catch (IOException e) { Assert.fail("failed to test with timeout of 0: "+e.getMessage()); } catch (VersionMissingException e) { Assert.fail("failed to test with timeout of 0: "+e.getMessage()); } //need to clear out segment 4 from our responder //now make sure we can get the latest version with an explicit request for //something after version 2 try { object = VersioningProfile.getLatestVersion(two, null, timeout, getHandle.defaultVerifier(), getHandle); responder.checkError(); Assert.assertNotNull(object); Assert.assertTrue(VersioningProfile.getLastVersionAsLong(object.name()) == VersioningProfile.getLastVersionAsLong(four)); Assert.assertTrue(responseObjects.size() == 0); } catch (IOException e) { Assert.fail("Failed to get latest version: "+e.getMessage()); } catch (VersionMissingException e) { Assert.fail("Failed to get version from object: "+e.getMessage()); } //test for getting the first segment of a version that does not have a first segment //put a later segment of a later version and make sure it comes back with null or an earlier version try { System.out.println("=========testing skip segment!"); responderHandle.put(objSkip); object = VersioningProfile.getLatestVersion(baseName, null, timeout, getHandle.defaultVerifier(), getHandle); responder.checkError(); Assert.assertNotNull(object); Assert.assertTrue(VersioningProfile.getLastVersionAsLong(object.name()) == VersioningProfile.getLastVersionAsLong(skipSegment)); System.out.println("passed test for getLatestVersion with skipped segment available"); System.out.println("adding: "+objSkip0.name()); responseObjects.add(objSkip0); System.out.println("adding: "+objSkip2.name()); responseObjects.add(objSkip2); object = VersioningProfile.getFirstBlockOfLatestVersion(baseName, null, null, timeout, getHandle.defaultVerifier(), getHandle); responder.checkError(); Assert.assertNotNull(object); Assert.assertTrue(VersioningProfile.getLastVersionAsLong(object.name()) == VersioningProfile.getLastVersionAsLong(skipSegment0)); System.out.println("passed test for getFirstBlockOfLatestVersion with skipped segment available"); Assert.assertTrue(responseObjects.size() == 0); } catch (IOException e) { Assert.fail("Failed to get latest version: "+e.getMessage()); } catch (VersionMissingException e) { Assert.fail("Failed to get version from object: "+e.getMessage()); } //now put 15 responses in.... CCNTime versionToAdd = new CCNTime(); for(int i = 0; i < SystemConfiguration.GET_LATEST_VERSION_ATTEMPTS + 5; i++) { versionToAdd.increment(1); responseObjects.add(ContentObject.buildContentObject(SegmentationProfile.segmentName(VersioningProfile.addVersion(baseName, versionToAdd), 0), "here is version generated".getBytes(), null, null, SegmentationProfile.getSegmentNumberNameComponent(0))); System.out.println("created version with time: "+versionToAdd+" object name: "+responseObjects.get(i).fullName()); } lastVersionPublished = responseObjects.get(responseObjects.size()-1); //test for sending in a null timeout try { object = VersioningProfile.getLatestVersion(baseName, null, SystemConfiguration.NO_TIMEOUT, getHandle.defaultVerifier(), getHandle); responder.checkError(); Assert.assertNotNull(object); System.out.println("got back :"+object.name()); Assert.assertTrue(object.name().equals(lastVersionPublished.name())); System.out.println("passed test for no timeout"); for(int i =0; i < SystemConfiguration.GET_LATEST_VERSION_ATTEMPTS; i++) { versionToAdd.increment(1); responseObjects.add(ContentObject.buildContentObject(SegmentationProfile.segmentName(VersioningProfile.addVersion(baseName, versionToAdd), 0), "here is version generated".getBytes(), null, null, SegmentationProfile.getSegmentNumberNameComponent(0))); System.out.println("created version with time: "+versionToAdd+" object name: "+responseObjects.get(i).fullName()); } lastVersionPublished = responseObjects.get(responseObjects.size()-1); object = VersioningProfile.getFirstBlockOfLatestVersion(baseName, null, null, SystemConfiguration.NO_TIMEOUT, getHandle.defaultVerifier(), getHandle); responder.checkError(); Assert.assertNotNull(object); Assert.assertTrue(object.name().equals(lastVersionPublished.name())); System.out.println("passed test for no timeout"); Assert.assertTrue(responseObjects.size() == 0); } catch (IOException e) { Assert.fail("failed to test with no timeout: "+e.getMessage()); } // Note by paul r. I'm not sure why we need to have a "responder" here in the first place - as opposed to just simply // putting the test objects to ccnd. But once we have a verifier, there's a potential race between the verifier and responder i.e. // we can call the verifier before the responder or vice-versa so we can't guarantee what's actually going to show up in the // verifier because the objects we expect to see may not have been output by the responder yet. I've fixed this (I hope!) by // doing an explicit get of the objects in question before we try the test so that the responder has definitely done a put // of the objects we are trying to test ContentVerifier ver = new TestVerifier(); //have the verifier fail the newest object make sure we get back the most recent verified version versionToAdd.increment(1); failVerify = ContentObject.buildContentObject(SegmentationProfile.segmentName(VersioningProfile.addVersion(baseName, versionToAdd), 0), "here is failVerify".getBytes(), null, null, SegmentationProfile.getSegmentNumberNameComponent(0)); responseObjects.add(failVerify); try { getHandle.get(failVerify.fullName(), timeout); responder.checkError(); } catch (IOException e1) { Assert.fail("Failed get: "+e1.getMessage()); } //now put a unverifiable version try { object = VersioningProfile.getLatestVersion(baseName, null, timeout, ver, getHandle); responder.checkError(); Assert.assertNotNull(object); System.out.println("got: "+object.name()); System.out.println("expecting to get: "+lastVersionPublished.name()); Assert.assertTrue(VersioningProfile.getLastVersionAsLong(object.name()) == VersioningProfile.getLastVersionAsLong(lastVersionPublished.name())); System.out.println("passed test for failed verification"); object = VersioningProfile.getFirstBlockOfLatestVersion(baseName, null, null, timeout, ver, getHandle); responder.checkError(); System.out.println("expecting to get: "+lastVersionPublished.name()); Assert.assertNotNull(object); System.out.println("got: "+object.name()); Assert.assertTrue(VersioningProfile.getLastVersionAsLong(object.name()) == VersioningProfile.getLastVersionAsLong(lastVersionPublished.name())); System.out.println("passed test for getFirstBlockOfLatestVersion failed verification"); Assert.assertTrue(responseObjects.size() == 0); } catch (VersionMissingException e) { Assert.fail("Failed to get version from object: "+e.getMessage()); } catch (IOException e) { Assert.fail("Failed to get latest version: "+e.getMessage()); } //then call again and make sure we have a newer version that passes //have the verifier fail the newest object make sure we get back the most recent verified version versionToAdd.increment(1); ContentObject verify = ContentObject.buildContentObject(SegmentationProfile.segmentName(VersioningProfile.addVersion(baseName, versionToAdd), 0), "here is verify".getBytes(), null, null, SegmentationProfile.getSegmentNumberNameComponent(0)); responseObjects.add(verify); try { getHandle.get(verify.fullName(), timeout); responder.checkError(); } catch (IOException e1) { Assert.fail("Failed get: "+e1.getMessage()); } //now put a verifiable version try { object = VersioningProfile.getLatestVersion(baseName, null, timeout, ver, getHandle); responder.checkError(); Assert.assertNotNull(object); System.out.println("got: "+object.name()); System.out.println("expecting to get: "+verify.name()); Assert.assertTrue(VersioningProfile.getLastVersionAsLong(object.name()) == VersioningProfile.getLastVersionAsLong(verify.name())); System.out.println("passed test for failed verification with newer version available"); object = VersioningProfile.getFirstBlockOfLatestVersion(baseName, null, null, timeout, ver, getHandle); responder.checkError(); Assert.assertNotNull(object); Assert.assertTrue(VersioningProfile.getLastVersionAsLong(object.name()) == VersioningProfile.getLastVersionAsLong(verify.name())); System.out.println("passed test for getFirstBlockOfLatestVersion failed verification with newer version available"); Assert.assertTrue(responseObjects.size() == 0); } catch (VersionMissingException e) { Assert.fail("Failed to get version from object: "+e.getMessage()); } catch (IOException e) { Assert.fail("Failed to get latest version: "+e.getMessage()); } //test that also has a content object that fails to verify (maybe do 2) //and then also add one that does verify - same version. make sure we get the verifiable one back versionToAdd.increment(1); failVerify1 = ContentObject.buildContentObject(SegmentationProfile.segmentName(VersioningProfile.addVersion(baseName, versionToAdd), 0), "here is failVerify".getBytes(), null, null, SegmentationProfile.getSegmentNumberNameComponent(0)); responseObjects.add(failVerify1); failVerify2 = ContentObject.buildContentObject(SegmentationProfile.segmentName(VersioningProfile.addVersion(baseName, versionToAdd), 0), "here is a second failVerify".getBytes(), null, null, SegmentationProfile.getSegmentNumberNameComponent(0)); responseObjects.add(failVerify2); ContentObject failVerify3 = ContentObject.buildContentObject(SegmentationProfile.segmentName(VersioningProfile.addVersion(baseName, versionToAdd), 0), "here is a third, but it should pass".getBytes(), null, null, SegmentationProfile.getSegmentNumberNameComponent(0)); responseObjects.add(failVerify3); try { getHandle.get(failVerify1.fullName(), timeout); responder.checkError(); getHandle.get(failVerify2.fullName(), timeout); responder.checkError(); getHandle.get(failVerify3.fullName(), timeout); responder.checkError(); } catch (IOException e1) { Assert.fail("Failed get: "+e1.getMessage()); } System.out.println("failVerify1*: "+failVerify1.fullName()); System.out.println("failVerify2*: "+failVerify2.fullName()); System.out.println("failVerify3: "+failVerify3.fullName()); try { object = VersioningProfile.getLatestVersion(baseName, null, timeout, ver, getHandle); responder.checkError(); Assert.assertNotNull(object); System.out.println("got: "+object.fullName()); System.out.println("expecting to get: "+failVerify3.fullName()); Assert.assertTrue(VersioningProfile.getLastVersionAsLong(object.fullName()) == VersioningProfile.getLastVersionAsLong(failVerify3.fullName())); System.out.println("passed test for failed verification with multiple failures and a success"); object = VersioningProfile.getFirstBlockOfLatestVersion(baseName, null, null, timeout, ver, getHandle); responder.checkError(); Assert.assertNotNull(object); System.out.println("got: "+object.fullName()); System.out.println("expecting to get: "+failVerify3.fullName()); Assert.assertTrue(VersioningProfile.getLastVersionAsLong(object.fullName()) == VersioningProfile.getLastVersionAsLong(failVerify3.fullName())); System.out.println("passed test for getFirstBlockOfLatestVersion failed verification with multiple failures and a success"); Assert.assertTrue(responseObjects.size() == 0); } catch (VersionMissingException e) { Assert.fail("Failed to get version from object: "+e.getMessage()); } catch (IOException e) { Assert.fail("Failed to get latest version: "+e.getMessage()); } //test that checks a combo of a version without a first segment with a failed verification //after it. should return the non 0 segment for the first part, and the last published first segment //for the second part of the test responseObjects.clear(); versionToAdd.increment(1); ContentObject objSkip3 = ContentObject.buildContentObject(SegmentationProfile.segmentName(VersioningProfile.addVersion(baseName, versionToAdd), 5), "here is skip 3".getBytes(), null, null, SegmentationProfile.getSegmentNumberNameComponent(5)); responseObjects.add(objSkip3); versionToAdd.increment(1); failVerify4 = ContentObject.buildContentObject(SegmentationProfile.segmentName(VersioningProfile.addVersion(baseName, versionToAdd), 0), "here is a fourth verify, it should fail".getBytes(), null, null, SegmentationProfile.getSegmentNumberNameComponent(0)); responseObjects.add(failVerify4); try { getHandle.get(objSkip3.fullName(), timeout); responder.checkError(); getHandle.get(failVerify4.fullName(), timeout); responder.checkError(); } catch (IOException e1) { Assert.fail("Failed get: "+e1.getMessage()); } System.out.println("objSkip3: "+ objSkip3.fullName()); System.out.println("failVerify4*: "+failVerify4.fullName()); try { object = VersioningProfile.getLatestVersion(baseName, null, timeout, ver, getHandle); responder.checkError(); Assert.assertNotNull(object); System.out.println("got: "+object.fullName()); System.out.println("expecting to get: "+objSkip3.fullName()); Assert.assertTrue(VersioningProfile.getLastVersionAsLong(object.fullName()) == VersioningProfile.getLastVersionAsLong(objSkip3.fullName())); System.out.println("passed test for missing first segment + failed verification"); object = VersioningProfile.getFirstBlockOfLatestVersion(baseName, null, null, timeout, ver, getHandle); responder.checkError(); Assert.assertNotNull(object); System.out.println("got: "+object.fullName()); System.out.println("expecting to get: "+failVerify3.fullName()); Assert.assertTrue(VersioningProfile.getLastVersionAsLong(object.fullName()) == VersioningProfile.getLastVersionAsLong(failVerify3.fullName())); System.out.println("passed test for missing first segment + failed verification"); Assert.assertTrue(responseObjects.size() == 0); } catch (VersionMissingException e) { Assert.fail("Failed to get version from object: "+e.getMessage()); } catch (IOException e) { Assert.fail("Failed to get latest version: "+e.getMessage()); } responder.checkError(); }
public void getLatestVersion() throws InterruptedException, Error { ContentName one = null; ContentName two = null; ContentName three = null; ContentName four = null; ContentName skipSegment = null; ContentName skipSegment0 = null; ContentName skipSegment2 = null; ContentObject obj1 = null; ContentObject obj2 = null; ContentObject obj3 = null; ContentObject obj4 = null; ContentObject objSkip = null; ContentObject objSkip0 = null; ContentObject objSkip2 = null; ContentObject object = null; responseObjects = new ArrayList<ContentObject>(); checkResponder(); CCNTime t1; CCNTime t2; CCNTime t3; CCNTime t4; CCNTime skipTime; CCNTime skipTime2; long timeout = 5000; t1 = new CCNTime(); one = SegmentationProfile.segmentName(VersioningProfile.addVersion(baseName, t1), 0); obj1 = ContentObject.buildContentObject(one, "here is version 1".getBytes(), null, null, SegmentationProfile.getSegmentNumberNameComponent(0)); t2 = (CCNTime)t1.clone(); t2.increment(1); two = SegmentationProfile.segmentName(VersioningProfile.addVersion(baseName, t2), 0); obj2 = ContentObject.buildContentObject(two, "here is version 2".getBytes(), null, null, SegmentationProfile.getSegmentNumberNameComponent(0)); t3 = (CCNTime) t1.clone(); t3.increment(2); three = SegmentationProfile.segmentName(VersioningProfile.addVersion(baseName, t3), 0); obj3 = ContentObject.buildContentObject(three, "here is version 3".getBytes(), null, null, SegmentationProfile.getSegmentNumberNameComponent(0)); t4 = (CCNTime)t1.clone(); t4.increment(3); four = SegmentationProfile.segmentName(VersioningProfile.addVersion(baseName, t4), 0); obj4 = ContentObject.buildContentObject(four, "here is version 4".getBytes(), null, null, SegmentationProfile.getSegmentNumberNameComponent(0)); skipTime = (CCNTime)t1.clone(); skipTime.increment(4); skipSegment = SegmentationProfile.segmentName(VersioningProfile.addVersion(baseName, skipTime), 5); objSkip = ContentObject.buildContentObject(skipSegment, "here is skip".getBytes(), null, null, SegmentationProfile.getSegmentNumberNameComponent(5)); skipSegment0 = SegmentationProfile.segmentName(VersioningProfile.addVersion(baseName, skipTime), 0); objSkip0 = ContentObject.buildContentObject(skipSegment0, "here is skip".getBytes(), null, null, SegmentationProfile.getSegmentNumberNameComponent(5)); skipTime2 = (CCNTime)t1.clone(); skipTime2.increment(5); skipSegment2 = SegmentationProfile.segmentName(VersioningProfile.addVersion(baseName, skipTime2), 5); objSkip2 = ContentObject.buildContentObject(skipSegment2, "here is skip 2".getBytes(), null, null, SegmentationProfile.getSegmentNumberNameComponent(5)); System.out.println("made versions: "+one +" "+two+" "+three+" "+four+" "+skipTime+" "+skipTime2); Assert.assertTrue(t1.before(t2)); Assert.assertTrue(t2.before(t3)); Assert.assertTrue(t3.before(t4)); Assert.assertTrue(t4.before(skipTime)); Assert.assertTrue(skipTime.before(skipTime2)); try { responderHandle.put(obj1); responderHandle.put(obj2); object = VersioningProfile.getLatestVersion(baseName, null, timeout, getHandle.defaultVerifier(), getHandle); responder.checkError(); Assert.assertNotNull(object); Assert.assertTrue(VersioningProfile.getLastVersionAsLong(object.name()) == VersioningProfile.getLastVersionAsLong(two)); System.out.println("passed test for getLatestVersion with 2 versions available"); object = VersioningProfile.getFirstBlockOfLatestVersion(baseName, null, null, timeout, getHandle.defaultVerifier(), getHandle); responder.checkError(); Assert.assertNotNull(object); Assert.assertTrue(VersioningProfile.getLastVersionAsLong(object.name()) == VersioningProfile.getLastVersionAsLong(two)); System.out.println("passed test for getFirstBlockOfLatestVersion with 2 versions available"); Assert.assertTrue(responseObjects.size() == 0); } catch (IOException e) { Assert.fail("Failed to get latest version: "+e.getMessage()); } catch (VersionMissingException e) { Assert.fail("Failed to get version from object: "+e.getMessage()); } responder.checkError(); responseObjects.add(obj3); System.out.println("added: "+obj3.name()); //now put third version try { System.out.println("calling gLV at: "+System.currentTimeMillis()); object = VersioningProfile.getLatestVersion(baseName, null, timeout, getHandle.defaultVerifier(), getHandle); responder.checkError(); Assert.assertNotNull(object); System.out.println("got: "+object.name()); System.out.println("expecting to get: "+three); Assert.assertTrue(VersioningProfile.getLastVersionAsLong(object.name()) == VersioningProfile.getLastVersionAsLong(three)); System.out.println("passed test for getLatestVersion with 3 versions available"); object = VersioningProfile.getFirstBlockOfLatestVersion(baseName, null, null, timeout, getHandle.defaultVerifier(), getHandle); responder.checkError(); Assert.assertNotNull(object); Assert.assertTrue(VersioningProfile.getLastVersionAsLong(object.name()) == VersioningProfile.getLastVersionAsLong(three)); System.out.println("passed test for getFirstBlockOfLatestVersion with 3 versions available"); Assert.assertTrue(responseObjects.size() == 0); } catch (VersionMissingException e) { Assert.fail("Failed to get version from object: "+e.getMessage()); } catch (IOException e) { Assert.fail("Failed to get latest version: "+e.getMessage()); } //now make sure we can get the latest version with an explicit request for //something after version 2 try { object = VersioningProfile.getLatestVersion(two, null, timeout, getHandle.defaultVerifier(), getHandle); responder.checkError(); Assert.assertTrue(VersioningProfile.getLastVersionAsLong(object.name()) == VersioningProfile.getLastVersionAsLong(three)); Assert.assertTrue(responseObjects.size() == 0); } catch (IOException e) { Assert.fail("Failed to get latest version: "+e.getMessage()); } catch (VersionMissingException e) { Assert.fail("Failed to get version from object: "+e.getMessage()); } //now check to make sure when we ask for a later version (that does not exist) that we don't wait too long. //first wait for 5 seconds, then 200ms try { long doneTime; long checkTime = System.currentTimeMillis(); object = VersioningProfile.getFirstBlockOfLatestVersion(three, null, null, 5000, getHandle.defaultVerifier(), getHandle); doneTime = System.currentTimeMillis(); System.out.println("took us "+(doneTime - checkTime)+"ms to get nothing back "+" check: "+checkTime+" done: "+doneTime); responder.checkError(); Assert.assertNull(object); Assert.assertTrue((doneTime - checkTime) < 5500 && (doneTime - checkTime) >= 5000); System.out.println("passed test for waiting 5 seconds"); checkTime = System.currentTimeMillis(); object = VersioningProfile.getFirstBlockOfLatestVersion(three, null, null, 200, getHandle.defaultVerifier(), getHandle); checkTime = System.currentTimeMillis() - checkTime; responder.checkError(); System.out.println("took us "+checkTime+"ms to get nothing back"); Assert.assertNull(object); Assert.assertTrue(checkTime >= 200 && checkTime < 300); System.out.println("passed test for waiting 200ms"); Assert.assertTrue(responseObjects.size() == 0); } catch (IOException e) { Assert.fail("failed to test with different timeouts: "+e.getMessage()); } responseObjects.add(obj4); //add a fourth responder and make sure we don't get it back. try { lastVersionPublished = obj4; object = VersioningProfile.getFirstBlockOfLatestVersion(baseName, null, null, 0, getHandle.defaultVerifier(), getHandle); responder.checkError(); Assert.assertNotNull(object); Assert.assertTrue(VersioningProfile.getLastVersionAsLong(object.name()) == VersioningProfile.getLastVersionAsLong(three)); System.out.println("passed test for timeout 0 test"); object = VersioningProfile.getFirstBlockOfLatestVersion(baseName, null, null, 0, getHandle.defaultVerifier(), getHandle); responder.checkError(); Assert.assertNotNull(object); Assert.assertTrue(VersioningProfile.getLastVersionAsLong(object.name()) == VersioningProfile.getLastVersionAsLong(three)); System.out.println("passed test for timeout 0 test"); } catch (IOException e) { Assert.fail("failed to test with timeout of 0: "+e.getMessage()); } catch (VersionMissingException e) { Assert.fail("failed to test with timeout of 0: "+e.getMessage()); } //need to clear out segment 4 from our responder //now make sure we can get the latest version with an explicit request for //something after version 2 try { object = VersioningProfile.getLatestVersion(two, null, timeout, getHandle.defaultVerifier(), getHandle); responder.checkError(); Assert.assertNotNull(object); Assert.assertTrue(VersioningProfile.getLastVersionAsLong(object.name()) == VersioningProfile.getLastVersionAsLong(four)); Assert.assertTrue(responseObjects.size() == 0); } catch (IOException e) { Assert.fail("Failed to get latest version: "+e.getMessage()); } catch (VersionMissingException e) { Assert.fail("Failed to get version from object: "+e.getMessage()); } //test for getting the first segment of a version that does not have a first segment //put a later segment of a later version and make sure it comes back with null or an earlier version try { System.out.println("=========testing skip segment!"); responderHandle.put(objSkip); object = VersioningProfile.getLatestVersion(baseName, null, timeout, getHandle.defaultVerifier(), getHandle); responder.checkError(); Assert.assertNotNull(object); Assert.assertTrue(VersioningProfile.getLastVersionAsLong(object.name()) == VersioningProfile.getLastVersionAsLong(skipSegment)); System.out.println("passed test for getLatestVersion with skipped segment available"); System.out.println("adding: "+objSkip0.name()); responseObjects.add(objSkip0); System.out.println("adding: "+objSkip2.name()); responseObjects.add(objSkip2); object = VersioningProfile.getFirstBlockOfLatestVersion(baseName, null, null, timeout, getHandle.defaultVerifier(), getHandle); responder.checkError(); Assert.assertNotNull(object); Assert.assertTrue(VersioningProfile.getLastVersionAsLong(object.name()) == VersioningProfile.getLastVersionAsLong(skipSegment0)); System.out.println("passed test for getFirstBlockOfLatestVersion with skipped segment available"); Assert.assertTrue(responseObjects.size() == 0); } catch (IOException e) { Assert.fail("Failed to get latest version: "+e.getMessage()); } catch (VersionMissingException e) { Assert.fail("Failed to get version from object: "+e.getMessage()); } //now put 15 responses in.... CCNTime versionToAdd = new CCNTime(); for(int i = 0; i < SystemConfiguration.GET_LATEST_VERSION_ATTEMPTS + 5; i++) { versionToAdd.increment(1); responseObjects.add(ContentObject.buildContentObject(SegmentationProfile.segmentName(VersioningProfile.addVersion(baseName, versionToAdd), 0), "here is version generated".getBytes(), null, null, SegmentationProfile.getSegmentNumberNameComponent(0))); System.out.println("created version with time: "+versionToAdd+" object name: "+responseObjects.get(i).fullName()); } lastVersionPublished = responseObjects.get(responseObjects.size()-1); //test for sending in a null timeout try { object = VersioningProfile.getLatestVersion(baseName, null, SystemConfiguration.NO_TIMEOUT, getHandle.defaultVerifier(), getHandle); responder.checkError(); Assert.assertNotNull(object); System.out.println("got back :"+object.name()); Assert.assertTrue(object.name().equals(lastVersionPublished.name())); System.out.println("passed test for no timeout"); for(int i =0; i < SystemConfiguration.GET_LATEST_VERSION_ATTEMPTS; i++) { versionToAdd.increment(1); responseObjects.add(ContentObject.buildContentObject(SegmentationProfile.segmentName(VersioningProfile.addVersion(baseName, versionToAdd), 0), "here is version generated".getBytes(), null, null, SegmentationProfile.getSegmentNumberNameComponent(0))); System.out.println("created version with time: "+versionToAdd+" object name: "+responseObjects.get(i).fullName()); } lastVersionPublished = responseObjects.get(responseObjects.size()-1); object = VersioningProfile.getFirstBlockOfLatestVersion(baseName, null, null, SystemConfiguration.NO_TIMEOUT, getHandle.defaultVerifier(), getHandle); responder.checkError(); Assert.assertNotNull(object); Assert.assertTrue(object.name().equals(lastVersionPublished.name())); System.out.println("passed test for no timeout"); Assert.assertTrue(responseObjects.size() == 0); } catch (IOException e) { Assert.fail("failed to test with no timeout: "+e.getMessage()); } // Note by paul r. I'm not sure why we need to have a "responder" here in the first place - as opposed to just simply // putting the test objects to ccnd. But once we have a verifier, there's a potential race between the verifier and responder i.e. // we can call the verifier before the responder or vice-versa so we can't guarantee what's actually going to show up in the // verifier because the objects we expect to see may not have been output by the responder yet. I've fixed this (I hope!) by // doing an explicit get of the objects in question before we try the test so that the responder has definitely done a put // of the objects we are trying to test ContentVerifier ver = new TestVerifier(); //have the verifier fail the newest object make sure we get back the most recent verified version versionToAdd.increment(1); failVerify = ContentObject.buildContentObject(SegmentationProfile.segmentName(VersioningProfile.addVersion(baseName, versionToAdd), 0), "here is failVerify".getBytes(), null, null, SegmentationProfile.getSegmentNumberNameComponent(0)); responseObjects.add(failVerify); try { getHandle.get(failVerify.fullName(), timeout); responder.checkError(); } catch (IOException e1) { Assert.fail("Failed get: "+e1.getMessage()); } //now put a unverifiable version try { object = VersioningProfile.getLatestVersion(baseName, null, timeout, ver, getHandle); responder.checkError(); Assert.assertNotNull(object); System.out.println("got: "+object.name()); System.out.println("expecting to get: "+lastVersionPublished.name()); Assert.assertTrue(VersioningProfile.getLastVersionAsLong(object.name()) == VersioningProfile.getLastVersionAsLong(lastVersionPublished.name())); System.out.println("passed test for failed verification"); object = VersioningProfile.getFirstBlockOfLatestVersion(baseName, null, null, timeout, ver, getHandle); responder.checkError(); System.out.println("expecting to get: "+lastVersionPublished.name()); Assert.assertNotNull(object); System.out.println("got: "+object.name()); Assert.assertTrue(VersioningProfile.getLastVersionAsLong(object.name()) == VersioningProfile.getLastVersionAsLong(lastVersionPublished.name())); System.out.println("passed test for getFirstBlockOfLatestVersion failed verification"); Assert.assertTrue(responseObjects.size() == 0); } catch (VersionMissingException e) { Assert.fail("Failed to get version from object: "+e.getMessage()); } catch (IOException e) { Assert.fail("Failed to get latest version: "+e.getMessage()); } //then call again and make sure we have a newer version that passes //have the verifier fail the newest object make sure we get back the most recent verified version versionToAdd.increment(1); ContentObject verify = ContentObject.buildContentObject(SegmentationProfile.segmentName(VersioningProfile.addVersion(baseName, versionToAdd), 0), "here is verify".getBytes(), null, null, SegmentationProfile.getSegmentNumberNameComponent(0)); responseObjects.add(verify); try { getHandle.get(verify.fullName(), timeout); responder.checkError(); } catch (IOException e1) { Assert.fail("Failed get: "+e1.getMessage()); } //now put a verifiable version try { object = VersioningProfile.getLatestVersion(baseName, null, timeout, ver, getHandle); responder.checkError(); Assert.assertNotNull(object); System.out.println("got: "+object.name()); System.out.println("expecting to get: "+verify.name()); Assert.assertTrue(VersioningProfile.getLastVersionAsLong(object.name()) == VersioningProfile.getLastVersionAsLong(verify.name())); System.out.println("passed test for failed verification with newer version available"); object = VersioningProfile.getFirstBlockOfLatestVersion(baseName, null, null, timeout, ver, getHandle); responder.checkError(); Assert.assertNotNull(object); Assert.assertTrue(VersioningProfile.getLastVersionAsLong(object.name()) == VersioningProfile.getLastVersionAsLong(verify.name())); System.out.println("passed test for getFirstBlockOfLatestVersion failed verification with newer version available"); Assert.assertTrue(responseObjects.size() == 0); } catch (VersionMissingException e) { Assert.fail("Failed to get version from object: "+e.getMessage()); } catch (IOException e) { Assert.fail("Failed to get latest version: "+e.getMessage()); } //test that also has a content object that fails to verify (maybe do 2) //and then also add one that does verify - same version. make sure we get the verifiable one back versionToAdd.increment(1); failVerify1 = ContentObject.buildContentObject(SegmentationProfile.segmentName(VersioningProfile.addVersion(baseName, versionToAdd), 0), "here is failVerify".getBytes(), null, null, SegmentationProfile.getSegmentNumberNameComponent(0)); responseObjects.add(failVerify1); failVerify2 = ContentObject.buildContentObject(SegmentationProfile.segmentName(VersioningProfile.addVersion(baseName, versionToAdd), 0), "here is a second failVerify".getBytes(), null, null, SegmentationProfile.getSegmentNumberNameComponent(0)); responseObjects.add(failVerify2); ContentObject failVerify3 = ContentObject.buildContentObject(SegmentationProfile.segmentName(VersioningProfile.addVersion(baseName, versionToAdd), 0), "here is a third, but it should pass".getBytes(), null, null, SegmentationProfile.getSegmentNumberNameComponent(0)); responseObjects.add(failVerify3); try { getHandle.get(failVerify1.fullName(), timeout); responder.checkError(); getHandle.get(failVerify2.fullName(), timeout); responder.checkError(); getHandle.get(failVerify3.fullName(), timeout); responder.checkError(); } catch (IOException e1) { Assert.fail("Failed get: "+e1.getMessage()); } System.out.println("failVerify1*: "+failVerify1.fullName()); System.out.println("failVerify2*: "+failVerify2.fullName()); System.out.println("failVerify3: "+failVerify3.fullName()); try { object = VersioningProfile.getLatestVersion(baseName, null, timeout, ver, getHandle); responder.checkError(); Assert.assertNotNull(object); System.out.println("got: "+object.fullName()); System.out.println("expecting to get: "+failVerify3.fullName()); Assert.assertTrue(VersioningProfile.getLastVersionAsLong(object.fullName()) == VersioningProfile.getLastVersionAsLong(failVerify3.fullName())); System.out.println("passed test for failed verification with multiple failures and a success"); object = VersioningProfile.getFirstBlockOfLatestVersion(baseName, null, null, timeout, ver, getHandle); responder.checkError(); Assert.assertNotNull(object); System.out.println("got: "+object.fullName()); System.out.println("expecting to get: "+failVerify3.fullName()); Assert.assertTrue(VersioningProfile.getLastVersionAsLong(object.fullName()) == VersioningProfile.getLastVersionAsLong(failVerify3.fullName())); System.out.println("passed test for getFirstBlockOfLatestVersion failed verification with multiple failures and a success"); Assert.assertTrue(responseObjects.size() == 0); } catch (VersionMissingException e) { Assert.fail("Failed to get version from object: "+e.getMessage()); } catch (IOException e) { Assert.fail("Failed to get latest version: "+e.getMessage()); } //test that checks a combo of a version without a first segment with a failed verification //after it. should return the non 0 segment for the first part, and the last published first segment //for the second part of the test responseObjects.clear(); versionToAdd.increment(1); ContentObject objSkip3 = ContentObject.buildContentObject(SegmentationProfile.segmentName(VersioningProfile.addVersion(baseName, versionToAdd), 5), "here is skip 3".getBytes(), null, null, SegmentationProfile.getSegmentNumberNameComponent(5)); responseObjects.add(objSkip3); versionToAdd.increment(1); failVerify4 = ContentObject.buildContentObject(SegmentationProfile.segmentName(VersioningProfile.addVersion(baseName, versionToAdd), 0), "here is a fourth verify, it should fail".getBytes(), null, null, SegmentationProfile.getSegmentNumberNameComponent(0)); responseObjects.add(failVerify4); try { getHandle.get(objSkip3.fullName(), timeout); responder.checkError(); getHandle.get(failVerify4.fullName(), timeout); responder.checkError(); } catch (IOException e1) { Assert.fail("Failed get: "+e1.getMessage()); } System.out.println("objSkip3: "+ objSkip3.fullName()); System.out.println("failVerify4*: "+failVerify4.fullName()); try { object = VersioningProfile.getLatestVersion(baseName, null, timeout, ver, getHandle); responder.checkError(); Assert.assertNotNull(object); System.out.println("got: "+object.fullName()); System.out.println("expecting to get: "+objSkip3.fullName()); Assert.assertTrue(VersioningProfile.getLastVersionAsLong(object.fullName()) == VersioningProfile.getLastVersionAsLong(objSkip3.fullName())); System.out.println("passed test for missing first segment + failed verification"); object = VersioningProfile.getFirstBlockOfLatestVersion(baseName, null, null, timeout, ver, getHandle); responder.checkError(); Assert.assertNotNull(object); System.out.println("got: "+object.fullName()); System.out.println("expecting to get: "+failVerify3.fullName()); Assert.assertTrue(VersioningProfile.getLastVersionAsLong(object.fullName()) == VersioningProfile.getLastVersionAsLong(failVerify3.fullName())); System.out.println("passed test for missing first segment + failed verification"); Assert.assertTrue(responseObjects.size() == 0); } catch (VersionMissingException e) { Assert.fail("Failed to get version from object: "+e.getMessage()); } catch (IOException e) { Assert.fail("Failed to get latest version: "+e.getMessage()); } responder.checkError(); }
diff --git a/org.eclipse.riena.ui.ridgets.swt/src/org/eclipse/riena/internal/ui/ridgets/swt/ColumnUtils.java b/org.eclipse.riena.ui.ridgets.swt/src/org/eclipse/riena/internal/ui/ridgets/swt/ColumnUtils.java index 4f87595d0..c32a1acf0 100644 --- a/org.eclipse.riena.ui.ridgets.swt/src/org/eclipse/riena/internal/ui/ridgets/swt/ColumnUtils.java +++ b/org.eclipse.riena.ui.ridgets.swt/src/org/eclipse/riena/internal/ui/ridgets/swt/ColumnUtils.java @@ -1,272 +1,266 @@ /******************************************************************************* * Copyright (c) 2007, 2009 compeople AG 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: * compeople AG - initial API and implementation *******************************************************************************/ package org.eclipse.riena.internal.ui.ridgets.swt; import org.eclipse.jface.layout.TableColumnLayout; import org.eclipse.jface.layout.TreeColumnLayout; import org.eclipse.jface.util.Util; import org.eclipse.jface.viewers.ColumnLayoutData; import org.eclipse.jface.viewers.ColumnPixelData; import org.eclipse.jface.viewers.ColumnWeightData; import org.eclipse.jface.viewers.TableLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.TreeColumn; import org.eclipse.swt.widgets.Widget; /** * Helper class for layouting columns in a Table or Tree. */ public final class ColumnUtils { /** * Adjust the column widths of the given {@link Table}, according to the * provided {@link ColumnLayoutData} array. The layout managers supported by * this method are: TableLayout, TableColumnLayout, other. * <p> * If the number of entries in {@code columnWidths} does not match the * number of columns in the widget, the available width will be distributed * equally to all columns. The same will happen if {@code columnWidths} is * null. Future width changes are not taken into account. * <p> * If the control has a TableLayout, the ColumnLayoutData will be used * directy. Future width changes are not taken into account. * <p> * If the control's parent has a TableColumnLayout, the ColumnLayoutData * will be used directly. If control and the parent have no layout, and * parent only contains the control, then a TableColumnLayout is used as * well. Future width changes ARE taken into account. * <p> * In any other case: the available table width <i>at the time when this * meethod is invoked</i> is distributed directly to the columns (via * setWidth(...)). Future width changes are not taken into account. * * @param control * a Table instance; never null * @param columnWidths * an Array with width information, one instance per column. The * array may be null, in that case the available width is * distributed equally to all columns */ public static void applyColumnWidths(Table control, ColumnLayoutData[] columnWidths) { applyColumnWidths(control, columnWidths, control.getColumnCount()); } /** * Adjust the column widths of the given {@link Tree}, according to the * provided {@link ColumnLayoutData} array. The layout managers supported by * this method are: TableLayout, TableColumnLayout, other. * <p> * If the number of entries in {@code columnWidths} does not match the * number of columns in the widget, the available width will be distributed * equally to all columns. The same will happen if {@code columnWidths} is * null. Future width changes are not taken into account. * <p> * If the control has a TableLayout, the ColumnLayoutData will be used * directy. Future width changes are not taken into account. * <p> * If the control's parent has a TreeColumnLayout, the ColumnLayoutData will * be used directly. If control and the parent have no layout, and parent * only contains the control, then a TreeColumnLayout is used as well. * Future width changes ARE taken into account. * <p> * In any other case: the available table width <i>at the time when this * meethod is invoked</i> is distributed directly to the columns (via * setWidth(...)). Future width changes are not taken into account. * * @param control * a Tree instance; never null * @param columnWidths * an Array with width information, one instance per column. The * array may be null, in that case the available width is * distributed equally to all columns */ public static void applyColumnWidths(Tree control, ColumnLayoutData[] columnWidths) { applyColumnWidths(control, columnWidths, control.getColumnCount()); } /** * Deep copy an array of {@link ColumnLayoutData} instances. * * @param source * an Array; may be null * @return a deep copy of the array or null (if {@code source} is null) * @throws RuntimeException * if the array contains types other than subclasses of * {@link ColumnLayoutData} */ public static ColumnLayoutData[] copyWidths(Object[] source) { ColumnLayoutData[] result = null; if (source != null) { result = new ColumnLayoutData[source.length]; for (int i = 0; i < source.length; i++) { if (source[i] instanceof ColumnPixelData) { ColumnPixelData data = (ColumnPixelData) source[i]; result[i] = new ColumnPixelData(data.width, data.resizable, data.addTrim); } else if (source[i] instanceof ColumnWeightData) { ColumnWeightData data = (ColumnWeightData) source[i]; result[i] = new ColumnWeightData(data.weight, data.minimumWidth, data.resizable); } else { String msg = String.format("Unsupported type in column #%d: %s", i, source[i]); //$NON-NLS-1$ throw new IllegalArgumentException(msg); } } } return result; } // helping methods ////////////////// private static void applyColumnWidths(Composite control, ColumnLayoutData[] columnWidths, final int expectedCols) { final ColumnLayoutData[] columnData; if (columnWidths == null || columnWidths.length != expectedCols) { columnData = new ColumnLayoutData[expectedCols]; for (int i = 0; i < expectedCols; i++) { columnData[i] = new ColumnWeightData(1, true); } } else { columnData = columnWidths; } Composite parent = control.getParent(); if (control.getLayout() instanceof TableLayout) { // TableLayout: use columnData instance for each column, apply to control TableLayout layout = new TableLayout(); for (int index = 0; index < expectedCols; index++) { layout.addColumnData(columnData[index]); } control.setLayout(layout); - if (parent.isVisible()) { - parent.layout(true, true); - } + parent.layout(true, true); } else if ((control instanceof Tree && control.getLayout() == null && parent.getLayout() == null && parent .getChildren().length == 1) || parent.getLayout() instanceof TreeColumnLayout) { // TreeColumnLayout: use columnData instance for each column, apply to parent TreeColumnLayout layout = getOrCreateTreeColumnLayout(parent); for (int index = 0; index < expectedCols; index++) { Widget column = getColumn(control, index); layout.setColumnData(column, columnData[index]); } parent.setLayout(layout); - if (parent.isVisible()) { - parent.layout(); - } + parent.layout(); } else if ((control instanceof Table && control.getLayout() == null && parent.getLayout() == null && parent .getChildren().length == 1) || parent.getLayout() instanceof TableColumnLayout) { // TableColumnLayout: use columnData instance for each column, apply to parent TableColumnLayout layout = getOrCreateTableColumnLayout(parent); for (int index = 0; index < expectedCols; index++) { Widget column = getColumn(control, index); layout.setColumnData(column, columnData[index]); } parent.setLayout(layout); - if (parent.isVisible()) { - parent.layout(); - } + parent.layout(); } else { // Other: manually compute width for each columnm, apply to TableColumn // 1. absolute widths: apply absolute widths first // 2. relative widths: // compute remaining width and total weight; for each column: apply // the largest value of either the relative width or the minimum width int widthRemaining = control.getClientArea().width; int totalWeights = 0; for (int index = 0; index < expectedCols; index++) { ColumnLayoutData data = columnData[index]; if (data instanceof ColumnPixelData) { ColumnPixelData pixelData = (ColumnPixelData) data; int width = pixelData.width; if (pixelData.addTrim) { width = width + getColumnTrim(); } configureColumn(control, index, width, data.resizable); widthRemaining = widthRemaining - width; } else if (data instanceof ColumnWeightData) { totalWeights = totalWeights + ((ColumnWeightData) data).weight; } } int slice = totalWeights > 0 ? Math.max(0, widthRemaining / totalWeights) : 0; for (int index = 0; index < expectedCols; index++) { if (columnData[index] instanceof ColumnWeightData) { ColumnWeightData data = (ColumnWeightData) columnData[index]; int width = Math.max(data.minimumWidth, data.weight * slice); configureColumn(control, index, width, data.resizable); } } } } private static void configureColumn(Control control, int index, int width, boolean resizable) { Widget column = getColumn(control, index); if (column instanceof TreeColumn) { ((TreeColumn) column).setWidth(width); ((TreeColumn) column).setResizable(resizable); } else if (column instanceof TableColumn) { ((TableColumn) column).setWidth(width); ((TableColumn) column).setResizable(resizable); } } private static Widget getColumn(Control control, int index) { if (control instanceof Table) { return ((Table) control).getColumn(index); } if (control instanceof Tree) { return ((Tree) control).getColumn(index); } throw new IllegalArgumentException("unsupported type: " + control); //$NON-NLS-1$ } private static int getColumnTrim() { int result = 3; if (Util.isWindows()) { result = 4; } else if (Util.isMac()) { result = 24; } return result; } /* * Workaround for Bug 295404 - reusing existing TableColumnLayout */ private static TableColumnLayout getOrCreateTableColumnLayout(Composite parent) { TableColumnLayout result; if (parent.getLayout() instanceof TableColumnLayout) { result = (TableColumnLayout) parent.getLayout(); } else { result = new TableColumnLayout(); } return result; } /* * Workaround for Bug 295404 - reusing existing TreeColumnLayout */ private static TreeColumnLayout getOrCreateTreeColumnLayout(Composite parent) { TreeColumnLayout result; if (parent.getLayout() instanceof TreeColumnLayout) { result = (TreeColumnLayout) parent.getLayout(); } else { result = new TreeColumnLayout(); } return result; } private ColumnUtils() { // utility class } }
false
true
private static void applyColumnWidths(Composite control, ColumnLayoutData[] columnWidths, final int expectedCols) { final ColumnLayoutData[] columnData; if (columnWidths == null || columnWidths.length != expectedCols) { columnData = new ColumnLayoutData[expectedCols]; for (int i = 0; i < expectedCols; i++) { columnData[i] = new ColumnWeightData(1, true); } } else { columnData = columnWidths; } Composite parent = control.getParent(); if (control.getLayout() instanceof TableLayout) { // TableLayout: use columnData instance for each column, apply to control TableLayout layout = new TableLayout(); for (int index = 0; index < expectedCols; index++) { layout.addColumnData(columnData[index]); } control.setLayout(layout); if (parent.isVisible()) { parent.layout(true, true); } } else if ((control instanceof Tree && control.getLayout() == null && parent.getLayout() == null && parent .getChildren().length == 1) || parent.getLayout() instanceof TreeColumnLayout) { // TreeColumnLayout: use columnData instance for each column, apply to parent TreeColumnLayout layout = getOrCreateTreeColumnLayout(parent); for (int index = 0; index < expectedCols; index++) { Widget column = getColumn(control, index); layout.setColumnData(column, columnData[index]); } parent.setLayout(layout); if (parent.isVisible()) { parent.layout(); } } else if ((control instanceof Table && control.getLayout() == null && parent.getLayout() == null && parent .getChildren().length == 1) || parent.getLayout() instanceof TableColumnLayout) { // TableColumnLayout: use columnData instance for each column, apply to parent TableColumnLayout layout = getOrCreateTableColumnLayout(parent); for (int index = 0; index < expectedCols; index++) { Widget column = getColumn(control, index); layout.setColumnData(column, columnData[index]); } parent.setLayout(layout); if (parent.isVisible()) { parent.layout(); } } else { // Other: manually compute width for each columnm, apply to TableColumn // 1. absolute widths: apply absolute widths first // 2. relative widths: // compute remaining width and total weight; for each column: apply // the largest value of either the relative width or the minimum width int widthRemaining = control.getClientArea().width; int totalWeights = 0; for (int index = 0; index < expectedCols; index++) { ColumnLayoutData data = columnData[index]; if (data instanceof ColumnPixelData) { ColumnPixelData pixelData = (ColumnPixelData) data; int width = pixelData.width; if (pixelData.addTrim) { width = width + getColumnTrim(); } configureColumn(control, index, width, data.resizable); widthRemaining = widthRemaining - width; } else if (data instanceof ColumnWeightData) { totalWeights = totalWeights + ((ColumnWeightData) data).weight; } } int slice = totalWeights > 0 ? Math.max(0, widthRemaining / totalWeights) : 0; for (int index = 0; index < expectedCols; index++) { if (columnData[index] instanceof ColumnWeightData) { ColumnWeightData data = (ColumnWeightData) columnData[index]; int width = Math.max(data.minimumWidth, data.weight * slice); configureColumn(control, index, width, data.resizable); } } } }
private static void applyColumnWidths(Composite control, ColumnLayoutData[] columnWidths, final int expectedCols) { final ColumnLayoutData[] columnData; if (columnWidths == null || columnWidths.length != expectedCols) { columnData = new ColumnLayoutData[expectedCols]; for (int i = 0; i < expectedCols; i++) { columnData[i] = new ColumnWeightData(1, true); } } else { columnData = columnWidths; } Composite parent = control.getParent(); if (control.getLayout() instanceof TableLayout) { // TableLayout: use columnData instance for each column, apply to control TableLayout layout = new TableLayout(); for (int index = 0; index < expectedCols; index++) { layout.addColumnData(columnData[index]); } control.setLayout(layout); parent.layout(true, true); } else if ((control instanceof Tree && control.getLayout() == null && parent.getLayout() == null && parent .getChildren().length == 1) || parent.getLayout() instanceof TreeColumnLayout) { // TreeColumnLayout: use columnData instance for each column, apply to parent TreeColumnLayout layout = getOrCreateTreeColumnLayout(parent); for (int index = 0; index < expectedCols; index++) { Widget column = getColumn(control, index); layout.setColumnData(column, columnData[index]); } parent.setLayout(layout); parent.layout(); } else if ((control instanceof Table && control.getLayout() == null && parent.getLayout() == null && parent .getChildren().length == 1) || parent.getLayout() instanceof TableColumnLayout) { // TableColumnLayout: use columnData instance for each column, apply to parent TableColumnLayout layout = getOrCreateTableColumnLayout(parent); for (int index = 0; index < expectedCols; index++) { Widget column = getColumn(control, index); layout.setColumnData(column, columnData[index]); } parent.setLayout(layout); parent.layout(); } else { // Other: manually compute width for each columnm, apply to TableColumn // 1. absolute widths: apply absolute widths first // 2. relative widths: // compute remaining width and total weight; for each column: apply // the largest value of either the relative width or the minimum width int widthRemaining = control.getClientArea().width; int totalWeights = 0; for (int index = 0; index < expectedCols; index++) { ColumnLayoutData data = columnData[index]; if (data instanceof ColumnPixelData) { ColumnPixelData pixelData = (ColumnPixelData) data; int width = pixelData.width; if (pixelData.addTrim) { width = width + getColumnTrim(); } configureColumn(control, index, width, data.resizable); widthRemaining = widthRemaining - width; } else if (data instanceof ColumnWeightData) { totalWeights = totalWeights + ((ColumnWeightData) data).weight; } } int slice = totalWeights > 0 ? Math.max(0, widthRemaining / totalWeights) : 0; for (int index = 0; index < expectedCols; index++) { if (columnData[index] instanceof ColumnWeightData) { ColumnWeightData data = (ColumnWeightData) columnData[index]; int width = Math.max(data.minimumWidth, data.weight * slice); configureColumn(control, index, width, data.resizable); } } } }
diff --git a/spring/src/main/java/org/xbean/spring/context/impl/QNameHelper.java b/spring/src/main/java/org/xbean/spring/context/impl/QNameHelper.java index 5dfa9157..710ebbf9 100644 --- a/spring/src/main/java/org/xbean/spring/context/impl/QNameHelper.java +++ b/spring/src/main/java/org/xbean/spring/context/impl/QNameHelper.java @@ -1,121 +1,125 @@ /** * * Copyright 2005 LogicBlaze, Inc. http://www.logicblaze.com * * 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.xbean.spring.context.impl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.MutablePropertyValues; import org.springframework.beans.PropertyValue; import org.springframework.beans.factory.support.AbstractBeanDefinition; import org.springframework.beans.factory.support.ManagedList; import org.w3c.dom.Element; import org.w3c.dom.Node; import javax.xml.namespace.QName; import java.beans.PropertyDescriptor; import java.util.Iterator; import java.util.List; /** * * @version $Revision: 1.1 $ */ public class QNameHelper { private static final Log log = LogFactory.getLog(QNameHelper.class); public static QName createQName(Element element, String qualifiedName) { int index = qualifiedName.indexOf(':'); if (index >= 0) { String prefix = qualifiedName.substring(0, index); String localName = qualifiedName.substring(index + 1); String uri = recursiveGetAttributeValue(element, "xmlns:" + prefix); return new QName(uri, localName, prefix); } else { String uri = recursiveGetAttributeValue(element, "xmlns"); if (uri != null) { return new QName(uri, qualifiedName); } return new QName(qualifiedName); } } /** * Recursive method to find a given attribute value */ public static String recursiveGetAttributeValue(Element element, String attributeName) { String answer = null; try { answer = element.getAttribute(attributeName); } catch (Exception e) { if (log.isTraceEnabled()) { log.trace("Caught exception looking up attribute: " + attributeName + " on element: " + element + ". Cause: " + e, e); } } if (answer == null || answer.length() == 0) { Node parentNode = element.getParentNode(); if (parentNode instanceof Element) { return recursiveGetAttributeValue((Element) parentNode, attributeName); } } return answer; } public static void coerceQNamePropertyValues(QNameReflectionParams params) { coerceNamespaceAwarePropertyValues(params.getBeanDefinition(), params.getElement(), params.getDescriptors(), params.getIndex()); } public static void coerceNamespaceAwarePropertyValues(AbstractBeanDefinition bd, Element element, PropertyDescriptor[] descriptors, int i) { PropertyDescriptor descriptor = descriptors[i]; + // When the property is an indexed property, the getPropertyType can return null. + if (descriptor.getPropertyType() == null) { + return; + } if (descriptor.getPropertyType().isAssignableFrom(QName.class)) { String name = descriptor.getName(); MutablePropertyValues propertyValues = bd.getPropertyValues(); PropertyValue propertyValue = propertyValues.getPropertyValue(name); if (propertyValue != null) { Object value = propertyValue.getValue(); if (value instanceof String) { propertyValues.removePropertyValue(propertyValue); propertyValues.addPropertyValue(name, createQName(element, (String) value)); } } } else if (descriptor.getPropertyType().isAssignableFrom(QName[].class)) { String name = descriptor.getName(); MutablePropertyValues propertyValues = bd.getPropertyValues(); PropertyValue propertyValue = propertyValues.getPropertyValue(name); if (propertyValue != null) { Object value = propertyValue.getValue(); if (value instanceof List) { List values = (List) value; List newValues = new ManagedList(); for (Iterator iter = values.iterator(); iter.hasNext();) { Object v = iter.next(); if (v instanceof String) { newValues.add(createQName(element, (String) v)); } else { newValues.add(v); } } propertyValues.removePropertyValue(propertyValue); propertyValues.addPropertyValue(name, newValues); } } } } }
true
true
public static void coerceNamespaceAwarePropertyValues(AbstractBeanDefinition bd, Element element, PropertyDescriptor[] descriptors, int i) { PropertyDescriptor descriptor = descriptors[i]; if (descriptor.getPropertyType().isAssignableFrom(QName.class)) { String name = descriptor.getName(); MutablePropertyValues propertyValues = bd.getPropertyValues(); PropertyValue propertyValue = propertyValues.getPropertyValue(name); if (propertyValue != null) { Object value = propertyValue.getValue(); if (value instanceof String) { propertyValues.removePropertyValue(propertyValue); propertyValues.addPropertyValue(name, createQName(element, (String) value)); } } } else if (descriptor.getPropertyType().isAssignableFrom(QName[].class)) { String name = descriptor.getName(); MutablePropertyValues propertyValues = bd.getPropertyValues(); PropertyValue propertyValue = propertyValues.getPropertyValue(name); if (propertyValue != null) { Object value = propertyValue.getValue(); if (value instanceof List) { List values = (List) value; List newValues = new ManagedList(); for (Iterator iter = values.iterator(); iter.hasNext();) { Object v = iter.next(); if (v instanceof String) { newValues.add(createQName(element, (String) v)); } else { newValues.add(v); } } propertyValues.removePropertyValue(propertyValue); propertyValues.addPropertyValue(name, newValues); } } } }
public static void coerceNamespaceAwarePropertyValues(AbstractBeanDefinition bd, Element element, PropertyDescriptor[] descriptors, int i) { PropertyDescriptor descriptor = descriptors[i]; // When the property is an indexed property, the getPropertyType can return null. if (descriptor.getPropertyType() == null) { return; } if (descriptor.getPropertyType().isAssignableFrom(QName.class)) { String name = descriptor.getName(); MutablePropertyValues propertyValues = bd.getPropertyValues(); PropertyValue propertyValue = propertyValues.getPropertyValue(name); if (propertyValue != null) { Object value = propertyValue.getValue(); if (value instanceof String) { propertyValues.removePropertyValue(propertyValue); propertyValues.addPropertyValue(name, createQName(element, (String) value)); } } } else if (descriptor.getPropertyType().isAssignableFrom(QName[].class)) { String name = descriptor.getName(); MutablePropertyValues propertyValues = bd.getPropertyValues(); PropertyValue propertyValue = propertyValues.getPropertyValue(name); if (propertyValue != null) { Object value = propertyValue.getValue(); if (value instanceof List) { List values = (List) value; List newValues = new ManagedList(); for (Iterator iter = values.iterator(); iter.hasNext();) { Object v = iter.next(); if (v instanceof String) { newValues.add(createQName(element, (String) v)); } else { newValues.add(v); } } propertyValues.removePropertyValue(propertyValue); propertyValues.addPropertyValue(name, newValues); } } } }
diff --git a/src/husacct/analyse/domain/famix/FamixDependencyConnector.java b/src/husacct/analyse/domain/famix/FamixDependencyConnector.java index 202af833..30ee1e12 100644 --- a/src/husacct/analyse/domain/famix/FamixDependencyConnector.java +++ b/src/husacct/analyse/domain/famix/FamixDependencyConnector.java @@ -1,228 +1,229 @@ package husacct.analyse.domain.famix; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map.Entry; import javax.naming.directory.InvalidAttributesException; import org.apache.log4j.Logger; class FamixDependencyConnector { private FamixModel theModel; private Logger logger = Logger.getLogger(FamixDependencyConnector.class); public FamixDependencyConnector(){ theModel = FamixModel.getInstance(); } void connectStructuralDependecies() { for(FamixStructuralEntity entity : theModel.waitingStructuralEntitys){ try{ String theClass = entity.belongsToClass; if(!isCompleteTypeDeclaration(entity.declareType)){ String classFoundInImports = findClassInImports(theClass, entity.declareType); if(!classFoundInImports.equals("")){ entity.declareType = classFoundInImports; }else{ String belongsToPackage = getPackageFromUniqueClassName(entity.belongsToClass); String to = findClassInPackage(entity.declareType, belongsToPackage); if(!to.equals("")){ entity.declareType = to; } } } addToModel(entity); } catch(Exception e){ } } } void connectAssociationDependencies() { for(FamixAssociation association : theModel.waitingAssociations){ try{ boolean connected = false; String theClass = association.from; if(!isCompleteTypeDeclaration(association.to)){ String classFoundInImports = findClassInImports(theClass, association.to); if(!classFoundInImports.equals("")){ association.to = classFoundInImports; connected = true; } else { String belongsToPackage = getPackageFromUniqueClassName(association.from); String to = findClassInPackage(association.to, belongsToPackage); if(!to.equals("")){ association.to = to; connected = true; } } if(!connected){ if(isInvocation(association)){ FamixInvocation theInvocation = (FamixInvocation) association; if (theInvocation.belongsToMethod.equals("")){ //Then it is an attribute theInvocation.to =getClassForAttribute (theInvocation.from, theInvocation.nameOfInstance); } else{ //checking order now: 1) parameter, 2) localVariable, 3) attribute theInvocation.to = getClassForParameter(theInvocation.from, theInvocation.belongsToMethod, theInvocation.nameOfInstance); if (theInvocation.to.equals("")){ //checking if it's a localVariable theInvocation.to = getClassForLocalVariable(theInvocation.from, theInvocation.belongsToMethod, theInvocation.nameOfInstance); } if(theInvocation.to.equals("")){ //now it is an attribute theInvocation.to =getClassForAttribute (theInvocation.from, theInvocation.nameOfInstance); } } } } } if(association.to.equals("") || association.to == null){ - logger.info("couldn't connect " + association.from + " to the right entity. Linenumber " + association.lineNumber + ". Please inform us with classe where we fail on."); + logger.info("Couldn't analyse dependency from " + association.from + ". Reason: External Libraries not implemented yet"); +// logger.info("couldn't connect " + association.from + " to the right entity. Linenumber " + association.lineNumber + "."); } else { addToModel(association); } } catch(Exception e){ } } } private String getClassForAttribute(String delcareClass, String attributeName){ for(FamixAttribute famixAttribute: theModel.getAttributes()){ if(famixAttribute.belongsToClass.equals(delcareClass)){ if(famixAttribute.name.equals(attributeName)){ return famixAttribute.declareType; } } } return ""; } private String getClassForParameter(String declareClass, String declareMethod, String attributeName){ for(FamixFormalParameter parameter: theModel.getParametersForClass(declareClass)){ if(parameter.belongsToMethod.equals(declareMethod)){ if(parameter.name.equals(attributeName)){ return parameter.declareType; } } } return ""; } private String getClassForLocalVariable(String declareClass, String belongsToMethod, String nameOfInstance) { for(String s : theModel.structuralEntities.keySet()){ if(s.startsWith(declareClass)){ FamixStructuralEntity entity = (FamixStructuralEntity) theModel.structuralEntities.get(s); if (entity instanceof FamixLocalVariable){ FamixLocalVariable variable = (FamixLocalVariable) entity; if(variable.belongsToMethod.equals(belongsToMethod)){ if(variable.name.equals(nameOfInstance)){ return variable.declareType; } } } } } return ""; } private boolean isInvocation(FamixAssociation association){ return association instanceof FamixInvocation; } // // // private List<FamixInvocation> getAllInvocationsFromClass(String from, String invocationName) { // List<FamixInvocation> foundInvocations = new ArrayList<FamixInvocation>(); // for (FamixAssociation assocation : theModel.associations){ // if(assocation instanceof FamixInvocation){ // FamixInvocation theInvocation = (FamixInvocation) assocation; // if(theInvocation.belongsToMethod.equals(from) && theInvocation.nameOfInstance.equals(invocationName)){ // foundInvocations.add(theInvocation); // } // } // } // return foundInvocations; // } private String findClassInImports(String importingClass, String typeDeclaration){ List<FamixImport> imports = theModel.getImportsInClass(importingClass); for(FamixImport fImport: imports){ if(!fImport.importsCompletePackage){ if(fImport.to.endsWith(typeDeclaration)){ return fImport.to; } }else{ for(String uniqueClassName: getModulesInPackage(fImport.to)){ if(uniqueClassName.endsWith(typeDeclaration)){ return uniqueClassName; } } } } return ""; } private boolean isCompleteTypeDeclaration(String typeDeclaration){ return typeDeclaration.contains("."); } private String findClassInPackage(String className, String uniquePackageName){ for(String uniqueName : getModulesInPackage(uniquePackageName)){ if(uniqueName.endsWith(className)) return uniqueName; } return ""; } private String getPackageFromUniqueClassName(String completeImportString) { List<FamixClass> classes = theModel.getClasses(); for (FamixClass fclass : classes){ if (fclass.uniqueName.equals(completeImportString)){ return fclass.belongsToPackage; } } return ""; } private List<String> getModulesInPackage(String packageUniqueName){ List<String> result = new ArrayList<String>(); Iterator<Entry<String, FamixClass>> classIterator = theModel.classes.entrySet().iterator(); while(classIterator.hasNext()){ Entry<String, FamixClass> entry = (Entry<String, FamixClass>)classIterator.next(); FamixClass currentClass = entry.getValue(); if(currentClass.belongsToPackage.equals(packageUniqueName)){ result.add(currentClass.uniqueName); } } Iterator<Entry<String, FamixInterface>> interfaceIterator = theModel.interfaces.entrySet().iterator(); while(interfaceIterator.hasNext()){ Entry<String, FamixInterface> entry = (Entry<String, FamixInterface>)interfaceIterator.next(); FamixInterface currentInterface = entry.getValue(); if(currentInterface.belongsToPackage.equals(packageUniqueName)){ result.add(currentInterface.uniqueName); } } return result; } private boolean addToModel(FamixObject newObject){ try { theModel.addObject(newObject); return true; } catch (InvalidAttributesException e) { return false; } } }
true
true
void connectAssociationDependencies() { for(FamixAssociation association : theModel.waitingAssociations){ try{ boolean connected = false; String theClass = association.from; if(!isCompleteTypeDeclaration(association.to)){ String classFoundInImports = findClassInImports(theClass, association.to); if(!classFoundInImports.equals("")){ association.to = classFoundInImports; connected = true; } else { String belongsToPackage = getPackageFromUniqueClassName(association.from); String to = findClassInPackage(association.to, belongsToPackage); if(!to.equals("")){ association.to = to; connected = true; } } if(!connected){ if(isInvocation(association)){ FamixInvocation theInvocation = (FamixInvocation) association; if (theInvocation.belongsToMethod.equals("")){ //Then it is an attribute theInvocation.to =getClassForAttribute (theInvocation.from, theInvocation.nameOfInstance); } else{ //checking order now: 1) parameter, 2) localVariable, 3) attribute theInvocation.to = getClassForParameter(theInvocation.from, theInvocation.belongsToMethod, theInvocation.nameOfInstance); if (theInvocation.to.equals("")){ //checking if it's a localVariable theInvocation.to = getClassForLocalVariable(theInvocation.from, theInvocation.belongsToMethod, theInvocation.nameOfInstance); } if(theInvocation.to.equals("")){ //now it is an attribute theInvocation.to =getClassForAttribute (theInvocation.from, theInvocation.nameOfInstance); } } } } } if(association.to.equals("") || association.to == null){ logger.info("couldn't connect " + association.from + " to the right entity. Linenumber " + association.lineNumber + ". Please inform us with classe where we fail on."); } else { addToModel(association); } } catch(Exception e){ } } }
void connectAssociationDependencies() { for(FamixAssociation association : theModel.waitingAssociations){ try{ boolean connected = false; String theClass = association.from; if(!isCompleteTypeDeclaration(association.to)){ String classFoundInImports = findClassInImports(theClass, association.to); if(!classFoundInImports.equals("")){ association.to = classFoundInImports; connected = true; } else { String belongsToPackage = getPackageFromUniqueClassName(association.from); String to = findClassInPackage(association.to, belongsToPackage); if(!to.equals("")){ association.to = to; connected = true; } } if(!connected){ if(isInvocation(association)){ FamixInvocation theInvocation = (FamixInvocation) association; if (theInvocation.belongsToMethod.equals("")){ //Then it is an attribute theInvocation.to =getClassForAttribute (theInvocation.from, theInvocation.nameOfInstance); } else{ //checking order now: 1) parameter, 2) localVariable, 3) attribute theInvocation.to = getClassForParameter(theInvocation.from, theInvocation.belongsToMethod, theInvocation.nameOfInstance); if (theInvocation.to.equals("")){ //checking if it's a localVariable theInvocation.to = getClassForLocalVariable(theInvocation.from, theInvocation.belongsToMethod, theInvocation.nameOfInstance); } if(theInvocation.to.equals("")){ //now it is an attribute theInvocation.to =getClassForAttribute (theInvocation.from, theInvocation.nameOfInstance); } } } } } if(association.to.equals("") || association.to == null){ logger.info("Couldn't analyse dependency from " + association.from + ". Reason: External Libraries not implemented yet"); // logger.info("couldn't connect " + association.from + " to the right entity. Linenumber " + association.lineNumber + "."); } else { addToModel(association); } } catch(Exception e){ } } }
diff --git a/openejb/itests/failover/src/test/java/org/apache/openejb/itest/failover/RandomConnectionStrategyTest.java b/openejb/itests/failover/src/test/java/org/apache/openejb/itest/failover/RandomConnectionStrategyTest.java index 75cf1a7f2..0ab827113 100644 --- a/openejb/itests/failover/src/test/java/org/apache/openejb/itest/failover/RandomConnectionStrategyTest.java +++ b/openejb/itests/failover/src/test/java/org/apache/openejb/itest/failover/RandomConnectionStrategyTest.java @@ -1,330 +1,330 @@ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.openejb.itest.failover; import org.apache.openejb.client.Client; import org.apache.openejb.client.RemoteInitialContextFactory; import org.apache.openejb.client.event.ClusterMetaDataUpdated; import org.apache.openejb.client.event.Observes; import org.apache.openejb.itest.failover.ejb.Calculator; import org.apache.openejb.loader.Files; import org.apache.openejb.loader.IO; import org.apache.openejb.loader.Zips; import org.apache.openejb.server.control.StandaloneServer; import org.junit.Assert; import org.junit.Test; import javax.ejb.EJBException; import javax.naming.Context; import javax.naming.InitialContext; import java.io.File; import java.net.URI; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; import java.util.logging.ConsoleHandler; import java.util.logging.Level; import java.util.logging.Logger; import static org.apache.openejb.util.NetworkUtil.getNextAvailablePort; public class RandomConnectionStrategyTest { static final Logger logger = Logger.getLogger("org.apache.openejb.client"); static { final ConsoleHandler consoleHandler = new ConsoleHandler(); consoleHandler.setLevel(Level.FINER); logger.addHandler(consoleHandler); logger.setLevel(Level.FINER); logger.setUseParentHandlers(false); } @Test public void test() throws Exception { // To run in an IDE, uncomment and update this line // System.setProperty("version", "4.0.0-beta-3-SNAPSHOT"); System.setProperty("openejb.client.connection.strategy", "roundrobin"); final File zip = Repository.getArtifact("org.apache.openejb", "openejb-standalone", "zip"); final File app = Repository.getArtifact("org.apache.openejb.itests", "failover-ejb", "jar"); final File dir = Files.tmpdir(); final StandaloneServer root; { final String name = "root"; final File home = new File(dir, name); Files.mkdir(home); Zips.unzip(zip, home, true); root = new StandaloneServer(home, home); root.killOnExit(); root.ignoreOut(); root.setProperty("name", name); root.setProperty("openejb.extract.configuration", "false"); final StandaloneServer.ServerService multipoint = root.getServerService("multipoint"); multipoint.setBind("localhost"); multipoint.setPort(getNextAvailablePort()); multipoint.setDisabled(false); multipoint.set("discoveryName", name); logger.info("Starting Root server"); root.start(); } final Services services = new Services(); Client.addEventObserver(services); final Map<String, StandaloneServer> servers = new HashMap<String, StandaloneServer>(); for (final String name : new String[]{"red", "green", "blue"}) { final File home = new File(dir, name); Files.mkdir(home); Zips.unzip(zip, home, true); final StandaloneServer server = new StandaloneServer(home, home); server.killOnExit(); server.ignoreOut(); server.setProperty("name", name); server.setProperty("openejb.extract.configuration", "false"); IO.copy(app, Files.path(home, "apps", "itest.jar")); IO.copy(IO.read("<openejb><Deployments dir=\"apps/\"/></openejb>"), Files.path(home, "conf", "openejb.xml")); final StandaloneServer.ServerService ejbd = server.getServerService("ejbd"); ejbd.setBind("localhost"); ejbd.setDisabled(false); ejbd.setPort(getNextAvailablePort()); ejbd.setThreads(5); final URI uri = URI.create(String.format("ejbd://%s:%s/%s", ejbd.getBind(), ejbd.getPort(), name)); ejbd.set("discovery", "ejb:" + uri); services.add(uri); server.getContext().set(URI.class, uri); final StandaloneServer.ServerService multipoint = server.getServerService("multipoint"); multipoint.setPort(getNextAvailablePort()); multipoint.setDisabled(false); multipoint.set("discoveryName", name); multipoint.set("initialServers", "localhost:" + root.getServerService("multipoint").getPort()); servers.put(name, server); logger.info(String.format("Starting %s server", name)); server.start(1, TimeUnit.MINUTES); } System.setProperty("openejb.client.requestretry", "true"); System.setProperty("openejb.client.connection.strategy", "random"); logger.info("Beginning Test"); final Properties environment = new Properties(); environment.put(Context.INITIAL_CONTEXT_FACTORY, RemoteInitialContextFactory.class.getName()); environment.put(Context.PROVIDER_URL, "ejbd://localhost:" + servers.values().iterator().next().getServerService("ejbd").getPort() + "/provider"); final InitialContext context = new InitialContext(environment); final Calculator bean = (Calculator) context.lookup("CalculatorBeanRemote"); for (final Map.Entry<String, StandaloneServer> entry : servers.entrySet()) { final String name = entry.getKey(); final StandaloneServer server = entry.getValue(); final URI serverURI = server.getContext().get(URI.class); logger.info("Waiting for updated list"); - services.assertServices(10, TimeUnit.SECONDS, new CalculatorCallable(bean), 500); + services.assertServices(30, TimeUnit.SECONDS, new CalculatorCallable(bean), 500); logger.info("Asserting balance"); assertBalance(bean, services.get().size()); logger.info("Shutting down " + name); server.kill(); services.remove(serverURI); } logger.info("All Servers Shutdown"); try { logger.info("Making one last request, expecting complete failover"); final String name = bean.name(); Assert.fail("Server should be destroyed: " + name); } catch (EJBException e) { logger.info(String.format("Pass. Request resulted in %s: %s", e.getCause().getClass().getSimpleName(), e.getMessage())); // good } for (final Map.Entry<String, StandaloneServer> entry : servers.entrySet()) { final String name = entry.getKey(); final StandaloneServer server = entry.getValue(); final URI serverURI = server.getContext().get(URI.class); logger.info(String.format("Starting %s server", name)); server.start(1, TimeUnit.MINUTES); services.add(serverURI); logger.info("Waiting for updated list"); - services.assertServices(10, TimeUnit.SECONDS, new CalculatorCallable(bean), 500); + services.assertServices(30, TimeUnit.SECONDS, new CalculatorCallable(bean), 500); logger.info("Asserting balance"); assertBalance(bean, services.get().size()); } } private void assertBalance(final Calculator bean, final int size) { final int expectedInvocations = 1000; final double percent = 0.10; final int totalInvocations = size * expectedInvocations; // Verify the work reached all servers final Set<Map.Entry<String, AtomicInteger>> entries = invoke(bean, totalInvocations).entrySet(); Assert.assertEquals(size, entries.size()); // And each server got a minimum of %10 percent of the traffic for (final Map.Entry<String, AtomicInteger> entry : entries) { final int actualInvocations = entry.getValue().get(); Assert.assertTrue(String.format("%s out of %s is too low", actualInvocations, expectedInvocations), actualInvocations > expectedInvocations * percent); } } private Map<String, AtomicInteger> invoke(final Calculator bean, final int max) { final Map<String, AtomicInteger> invocations = new HashMap<String, AtomicInteger>(); for (int i = 0; i < max; i++) { final String name = bean.name(); if (!invocations.containsKey(name)) { invocations.put(name, new AtomicInteger()); } invocations.get(name).incrementAndGet(); } for (final Map.Entry<String, AtomicInteger> entry : invocations.entrySet()) { logger.info(String.format("Server %s invoked %s times", entry.getKey(), entry.getValue())); } return invocations; } public static class Services { static final Logger logger = Logger.getLogger(Services.class.getName()); private final ReentrantLock lock = new ReentrantLock(); private final Condition condition = lock.newCondition(); private final Set<URI> expected = new HashSet<URI>(); public Services() { } public Set<URI> get() { return expected; } public boolean add(final URI uri) { return expected.add(uri); } public boolean remove(final URI o) { return expected.remove(o); } public void observe(@Observes final ClusterMetaDataUpdated updated) { final URI[] locations = updated.getClusterMetaData().getLocations(); final Set<URI> found = new HashSet<URI>(Arrays.asList(locations)); if (expected.equals(found)) { lock.lock(); try { condition.signal(); } finally { lock.unlock(); } } } public Set<URI> diff(final Set<URI> a, final Set<URI> b) { final Set<URI> diffs = new HashSet<URI>(); for (final URI uri : b) { if (!a.contains(uri)) diffs.add(uri); } return diffs; } public void assertServices(final long timeout, final TimeUnit unit, final Callable callable) { assertServices(timeout, unit, callable, 10); } public void assertServices(final long timeout, final TimeUnit unit, final Callable callable, final int delay) { final ClientThread client = new ClientThread(callable); client.delay(delay); client.start(); try { Assert.assertTrue(String.format("services failed to come online: waited %s %s", timeout, unit), await(timeout, unit)); } catch (InterruptedException e) { Thread.interrupted(); Assert.fail("Interrupted"); } finally { client.stop(); } } public boolean await(final long timeout, final TimeUnit unit) throws InterruptedException { lock.lock(); try { return condition.await(timeout, unit); } finally { lock.unlock(); } } } private static class CalculatorCallable implements Callable { private final Calculator bean; public CalculatorCallable(final Calculator bean) { this.bean = bean; } @Override public Object call() throws Exception { return bean.name(); } } }
false
true
public void test() throws Exception { // To run in an IDE, uncomment and update this line // System.setProperty("version", "4.0.0-beta-3-SNAPSHOT"); System.setProperty("openejb.client.connection.strategy", "roundrobin"); final File zip = Repository.getArtifact("org.apache.openejb", "openejb-standalone", "zip"); final File app = Repository.getArtifact("org.apache.openejb.itests", "failover-ejb", "jar"); final File dir = Files.tmpdir(); final StandaloneServer root; { final String name = "root"; final File home = new File(dir, name); Files.mkdir(home); Zips.unzip(zip, home, true); root = new StandaloneServer(home, home); root.killOnExit(); root.ignoreOut(); root.setProperty("name", name); root.setProperty("openejb.extract.configuration", "false"); final StandaloneServer.ServerService multipoint = root.getServerService("multipoint"); multipoint.setBind("localhost"); multipoint.setPort(getNextAvailablePort()); multipoint.setDisabled(false); multipoint.set("discoveryName", name); logger.info("Starting Root server"); root.start(); } final Services services = new Services(); Client.addEventObserver(services); final Map<String, StandaloneServer> servers = new HashMap<String, StandaloneServer>(); for (final String name : new String[]{"red", "green", "blue"}) { final File home = new File(dir, name); Files.mkdir(home); Zips.unzip(zip, home, true); final StandaloneServer server = new StandaloneServer(home, home); server.killOnExit(); server.ignoreOut(); server.setProperty("name", name); server.setProperty("openejb.extract.configuration", "false"); IO.copy(app, Files.path(home, "apps", "itest.jar")); IO.copy(IO.read("<openejb><Deployments dir=\"apps/\"/></openejb>"), Files.path(home, "conf", "openejb.xml")); final StandaloneServer.ServerService ejbd = server.getServerService("ejbd"); ejbd.setBind("localhost"); ejbd.setDisabled(false); ejbd.setPort(getNextAvailablePort()); ejbd.setThreads(5); final URI uri = URI.create(String.format("ejbd://%s:%s/%s", ejbd.getBind(), ejbd.getPort(), name)); ejbd.set("discovery", "ejb:" + uri); services.add(uri); server.getContext().set(URI.class, uri); final StandaloneServer.ServerService multipoint = server.getServerService("multipoint"); multipoint.setPort(getNextAvailablePort()); multipoint.setDisabled(false); multipoint.set("discoveryName", name); multipoint.set("initialServers", "localhost:" + root.getServerService("multipoint").getPort()); servers.put(name, server); logger.info(String.format("Starting %s server", name)); server.start(1, TimeUnit.MINUTES); } System.setProperty("openejb.client.requestretry", "true"); System.setProperty("openejb.client.connection.strategy", "random"); logger.info("Beginning Test"); final Properties environment = new Properties(); environment.put(Context.INITIAL_CONTEXT_FACTORY, RemoteInitialContextFactory.class.getName()); environment.put(Context.PROVIDER_URL, "ejbd://localhost:" + servers.values().iterator().next().getServerService("ejbd").getPort() + "/provider"); final InitialContext context = new InitialContext(environment); final Calculator bean = (Calculator) context.lookup("CalculatorBeanRemote"); for (final Map.Entry<String, StandaloneServer> entry : servers.entrySet()) { final String name = entry.getKey(); final StandaloneServer server = entry.getValue(); final URI serverURI = server.getContext().get(URI.class); logger.info("Waiting for updated list"); services.assertServices(10, TimeUnit.SECONDS, new CalculatorCallable(bean), 500); logger.info("Asserting balance"); assertBalance(bean, services.get().size()); logger.info("Shutting down " + name); server.kill(); services.remove(serverURI); } logger.info("All Servers Shutdown"); try { logger.info("Making one last request, expecting complete failover"); final String name = bean.name(); Assert.fail("Server should be destroyed: " + name); } catch (EJBException e) { logger.info(String.format("Pass. Request resulted in %s: %s", e.getCause().getClass().getSimpleName(), e.getMessage())); // good } for (final Map.Entry<String, StandaloneServer> entry : servers.entrySet()) { final String name = entry.getKey(); final StandaloneServer server = entry.getValue(); final URI serverURI = server.getContext().get(URI.class); logger.info(String.format("Starting %s server", name)); server.start(1, TimeUnit.MINUTES); services.add(serverURI); logger.info("Waiting for updated list"); services.assertServices(10, TimeUnit.SECONDS, new CalculatorCallable(bean), 500); logger.info("Asserting balance"); assertBalance(bean, services.get().size()); } }
public void test() throws Exception { // To run in an IDE, uncomment and update this line // System.setProperty("version", "4.0.0-beta-3-SNAPSHOT"); System.setProperty("openejb.client.connection.strategy", "roundrobin"); final File zip = Repository.getArtifact("org.apache.openejb", "openejb-standalone", "zip"); final File app = Repository.getArtifact("org.apache.openejb.itests", "failover-ejb", "jar"); final File dir = Files.tmpdir(); final StandaloneServer root; { final String name = "root"; final File home = new File(dir, name); Files.mkdir(home); Zips.unzip(zip, home, true); root = new StandaloneServer(home, home); root.killOnExit(); root.ignoreOut(); root.setProperty("name", name); root.setProperty("openejb.extract.configuration", "false"); final StandaloneServer.ServerService multipoint = root.getServerService("multipoint"); multipoint.setBind("localhost"); multipoint.setPort(getNextAvailablePort()); multipoint.setDisabled(false); multipoint.set("discoveryName", name); logger.info("Starting Root server"); root.start(); } final Services services = new Services(); Client.addEventObserver(services); final Map<String, StandaloneServer> servers = new HashMap<String, StandaloneServer>(); for (final String name : new String[]{"red", "green", "blue"}) { final File home = new File(dir, name); Files.mkdir(home); Zips.unzip(zip, home, true); final StandaloneServer server = new StandaloneServer(home, home); server.killOnExit(); server.ignoreOut(); server.setProperty("name", name); server.setProperty("openejb.extract.configuration", "false"); IO.copy(app, Files.path(home, "apps", "itest.jar")); IO.copy(IO.read("<openejb><Deployments dir=\"apps/\"/></openejb>"), Files.path(home, "conf", "openejb.xml")); final StandaloneServer.ServerService ejbd = server.getServerService("ejbd"); ejbd.setBind("localhost"); ejbd.setDisabled(false); ejbd.setPort(getNextAvailablePort()); ejbd.setThreads(5); final URI uri = URI.create(String.format("ejbd://%s:%s/%s", ejbd.getBind(), ejbd.getPort(), name)); ejbd.set("discovery", "ejb:" + uri); services.add(uri); server.getContext().set(URI.class, uri); final StandaloneServer.ServerService multipoint = server.getServerService("multipoint"); multipoint.setPort(getNextAvailablePort()); multipoint.setDisabled(false); multipoint.set("discoveryName", name); multipoint.set("initialServers", "localhost:" + root.getServerService("multipoint").getPort()); servers.put(name, server); logger.info(String.format("Starting %s server", name)); server.start(1, TimeUnit.MINUTES); } System.setProperty("openejb.client.requestretry", "true"); System.setProperty("openejb.client.connection.strategy", "random"); logger.info("Beginning Test"); final Properties environment = new Properties(); environment.put(Context.INITIAL_CONTEXT_FACTORY, RemoteInitialContextFactory.class.getName()); environment.put(Context.PROVIDER_URL, "ejbd://localhost:" + servers.values().iterator().next().getServerService("ejbd").getPort() + "/provider"); final InitialContext context = new InitialContext(environment); final Calculator bean = (Calculator) context.lookup("CalculatorBeanRemote"); for (final Map.Entry<String, StandaloneServer> entry : servers.entrySet()) { final String name = entry.getKey(); final StandaloneServer server = entry.getValue(); final URI serverURI = server.getContext().get(URI.class); logger.info("Waiting for updated list"); services.assertServices(30, TimeUnit.SECONDS, new CalculatorCallable(bean), 500); logger.info("Asserting balance"); assertBalance(bean, services.get().size()); logger.info("Shutting down " + name); server.kill(); services.remove(serverURI); } logger.info("All Servers Shutdown"); try { logger.info("Making one last request, expecting complete failover"); final String name = bean.name(); Assert.fail("Server should be destroyed: " + name); } catch (EJBException e) { logger.info(String.format("Pass. Request resulted in %s: %s", e.getCause().getClass().getSimpleName(), e.getMessage())); // good } for (final Map.Entry<String, StandaloneServer> entry : servers.entrySet()) { final String name = entry.getKey(); final StandaloneServer server = entry.getValue(); final URI serverURI = server.getContext().get(URI.class); logger.info(String.format("Starting %s server", name)); server.start(1, TimeUnit.MINUTES); services.add(serverURI); logger.info("Waiting for updated list"); services.assertServices(30, TimeUnit.SECONDS, new CalculatorCallable(bean), 500); logger.info("Asserting balance"); assertBalance(bean, services.get().size()); } }
diff --git a/deegree-tests/deegree-wmts-tests/src/test/java/org/deegree/services/wmts/WmtsIT.java b/deegree-tests/deegree-wmts-tests/src/test/java/org/deegree/services/wmts/WmtsIT.java index 2ce778709e..ec29c8d19d 100644 --- a/deegree-tests/deegree-wmts-tests/src/test/java/org/deegree/services/wmts/WmtsIT.java +++ b/deegree-tests/deegree-wmts-tests/src/test/java/org/deegree/services/wmts/WmtsIT.java @@ -1,194 +1,195 @@ //$HeadURL$ /*---------------------------------------------------------------------------- This file is part of deegree, http://deegree.org/ Copyright (C) 2001-2012 by: - Department of Geography, University of Bonn - and - lat/lon GmbH - This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact information: lat/lon GmbH Aennchenstr. 19, 53177 Bonn Germany http://lat-lon.de/ Department of Geography, University of Bonn Prof. Dr. Klaus Greve Postfach 1147, 53001 Bonn Germany http://www.geographie.uni-bonn.de/deegree/ e-mail: [email protected] ----------------------------------------------------------------------------*/ package org.deegree.services.wmts; import static javax.xml.stream.XMLStreamConstants.START_ELEMENT; import static org.deegree.commons.xml.CommonNamespaces.OWS_11_NS; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.util.List; import javax.xml.namespace.QName; import javax.xml.stream.FactoryConfigurationError; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import org.deegree.commons.ows.metadata.operation.Operation; import org.deegree.commons.utils.net.DURL; import org.deegree.commons.xml.CommonNamespaces; import org.deegree.commons.xml.schema.SchemaValidator; import org.deegree.commons.xml.stax.XMLStreamUtils; import org.deegree.protocol.wfs.WFSConstants; import org.deegree.protocol.wmts.client.Layer; import org.deegree.protocol.wmts.client.WMTSClient; import org.junit.Assert; import org.junit.Test; /** * Various integration tests for the WMTS. * * @author <a href="mailto:[email protected]">Markus Schneider</a> * @author last edited by: $Author: schneider $ * * @version $Revision: $, $Date: $ */ public class WmtsIT { private static final String ENDPOINT_BASE_URL = "http://localhost:" + System.getProperty( "portnumber" ) + "/deegree-wmts-tests/services?"; private static final String ENDPOINT_URL = "http://localhost:" + System.getProperty( "portnumber" ) + "/deegree-wmts-tests/services?" + "service=WMTS&request=GetCapabilities&version=1.0.0"; @Test public void testCapabilitiesOperationGetFeatureInfoListed() throws XMLStreamException { WMTSClient client = initClient(); Operation operation = client.getOperations().getOperation( "GetFeatureInfo" ); assertNotNull( operation ); } @Test public void testCapabilitiesPyramidLayerNoFeatureInfoFormats() throws XMLStreamException { WMTSClient client = initClient(); Layer pyramidLayer = client.getLayer( "pyramid" ); assertNotNull( pyramidLayer ); assertEquals( 0, pyramidLayer.getInfoFormats().size() ); } @Test public void testCapabilitiesRemoteWmsLayerHasFeatureInfoFormats() throws XMLStreamException { WMTSClient client = initClient(); Layer pyramidLayer = client.getLayer( "remotewms" ); assertNotNull( pyramidLayer ); Assert.assertNotSame( 0, pyramidLayer.getInfoFormats().size() ); } @Test public void testGetFeatureInfoNonGfiLayer() throws MalformedURLException, IOException, XMLStreamException, FactoryConfigurationError { InputStream response = doGetFeatureInfo( "pyramid", "utah", "57142.857142857145", "text/html" ); XMLStreamReader xmlStream = XMLInputFactory.newInstance().createXMLStreamReader( response ); XMLStreamUtils.skipStartDocument( xmlStream ); Assert.assertEquals( new QName( CommonNamespaces.OWS_11_NS, "ExceptionReport" ), xmlStream.getName() ); } @Test public void testGetFeatureInfoRemoteWmsGmlOutputValid() throws MalformedURLException, IOException { InputStream response = doGetFeatureInfo( "remotewms_dominant_vegetation", "utah", "57142.857142857145", "application/gml+xml; version=3.1" ); String[] schemaUrls = new String[2]; schemaUrls[0] = WFSConstants.WFS_110_SCHEMA_URL; schemaUrls[1] = WmtsIT.class.getResource( "dominant_vegetation.xsd" ).toExternalForm(); List<String> errors = SchemaValidator.validate( response, schemaUrls ); + System.out.println(errors); Assert.assertEquals( 0, errors.size() ); } @Test public void testGetFeatureInfoRemoteWmsCachedGmlOutputValid() throws MalformedURLException, IOException { InputStream response = doGetFeatureInfo( "remotewms_dominant_vegetation_cached", "utah", "57142.857142857145", "application/gml+xml; version=3.1" ); String[] schemaUrls = new String[2]; schemaUrls[0] = WFSConstants.WFS_110_SCHEMA_URL; schemaUrls[1] = WmtsIT.class.getResource( "dominant_vegetation.xsd" ).toExternalForm(); List<String> errors = SchemaValidator.validate( response, schemaUrls ); Assert.assertEquals( 0, errors.size() ); } @Test public void testGetTileFaultyLayer() throws MalformedURLException, IOException, XMLStreamException { String req = "SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=faulty&STYLE=default&TILEMATRIXSET=utah&" + "TILEMATRIX=28571.428571428572&TILEROW=1&TILECOL=1&FORMAT=image%2Fpng"; checkException( req ); } @Test public void testGetFeatureInfoFaultyLayer() throws MalformedURLException, IOException, XMLStreamException { String req = "SERVICE=WMTS&REQUEST=GetFeatureInfo&VERSION=1.0.0&LAYER=faulty&STYLE=default&TILEMATRIXSET=utah&" + "TILEMATRIX=28571.428571428572&TILEROW=1&TILECOL=1&FORMAT=image%2Fpng&" + "infoformat=text/html&i=10&j=10"; checkException( req ); } private void checkException( String req ) throws MalformedURLException, IOException, XMLStreamException { InputStream ins = performGetRequest( req ); XMLInputFactory fac = XMLInputFactory.newInstance(); XMLStreamReader in = fac.createXMLStreamReader( ins ); XMLStreamUtils.skipStartDocument( in ); in.require( START_ELEMENT, OWS_11_NS, "ExceptionReport" ); in.nextTag(); in.require( START_ELEMENT, OWS_11_NS, "Exception" ); } private InputStream doGetFeatureInfo( String layer, String tileMatrixSet, String tileMatrixId, String infoFormat ) throws MalformedURLException, IOException { String request = "service=WMTS&version=1.0.0&request=GetFeatureInfo&style=default&tilerow=1&tilecol=1&i=1&j=1"; request += "&layer=" + URLEncoder.encode( layer, "UTF-8" ); request += "&tilematrixset=" + URLEncoder.encode( tileMatrixSet, "UTF-8" ); request += "&tilematrix=" + URLEncoder.encode( tileMatrixId, "UTF-8" ); request += "&infoformat=" + URLEncoder.encode( infoFormat, "UTF-8" ); return performGetRequest( request ); } private InputStream performGetRequest( String request ) throws MalformedURLException, IOException { return new DURL( ENDPOINT_BASE_URL + request ).openStream(); } private WMTSClient initClient() { try { return new WMTSClient( new URL( ENDPOINT_URL ), null ); } catch ( Throwable t ) { throw new RuntimeException( "Unable to initialize WMTSClient: " + t.getMessage(), t ); } } }
true
true
public void testGetFeatureInfoRemoteWmsGmlOutputValid() throws MalformedURLException, IOException { InputStream response = doGetFeatureInfo( "remotewms_dominant_vegetation", "utah", "57142.857142857145", "application/gml+xml; version=3.1" ); String[] schemaUrls = new String[2]; schemaUrls[0] = WFSConstants.WFS_110_SCHEMA_URL; schemaUrls[1] = WmtsIT.class.getResource( "dominant_vegetation.xsd" ).toExternalForm(); List<String> errors = SchemaValidator.validate( response, schemaUrls ); Assert.assertEquals( 0, errors.size() ); }
public void testGetFeatureInfoRemoteWmsGmlOutputValid() throws MalformedURLException, IOException { InputStream response = doGetFeatureInfo( "remotewms_dominant_vegetation", "utah", "57142.857142857145", "application/gml+xml; version=3.1" ); String[] schemaUrls = new String[2]; schemaUrls[0] = WFSConstants.WFS_110_SCHEMA_URL; schemaUrls[1] = WmtsIT.class.getResource( "dominant_vegetation.xsd" ).toExternalForm(); List<String> errors = SchemaValidator.validate( response, schemaUrls ); System.out.println(errors); Assert.assertEquals( 0, errors.size() ); }
diff --git a/Compiler/MAlice/src/malice_grammar/MaliceParser.java b/Compiler/MAlice/src/malice_grammar/MaliceParser.java index 87b90f9..364e87b 100644 --- a/Compiler/MAlice/src/malice_grammar/MaliceParser.java +++ b/Compiler/MAlice/src/malice_grammar/MaliceParser.java @@ -1,76 +1,77 @@ package malice_grammar; import org.antlr.runtime.ANTLRStringStream; import org.antlr.runtime.CharStream; import org.antlr.runtime.CommonTokenStream; import org.antlr.runtime.RecognitionException; import org.antlr.runtime.TokenStream; public class MaliceParser { public static void main(String[] args) throws RecognitionException { String[] programs = { "x was a number of 3. " + '\n' + "The looking-glass hatta() " + '\n' + "opened " + '\n' + "The room private() contained a letter " + '\n' + "opened " + '\n' + "Alice found 1. " + '\n' + "closed" + '\n' + "x became 'y'. " + '\n' + "closed " + '\n' + "The room abs(number b) contained a letter " + '\n' + "opened " + '\n' + "b spoke. " + '\n' + "closed " + '\n' , "x was a letter of 'c'. \n" + "The looking-glass hatta() " + '\n' + "opened " + '\n' + "The room private() contained a letter " + '\n' + "opened " + '\n' + "Alice found abs(x) and " + '\n' + "abs(y) spoke. " + '\n' + "closed" + '\n' + "x became 'y'. " + '\n' + "closed " + '\n' + "The room abs(number b) contained a letter " + '\n' + "opened " + '\n' + "b spoke. " + '\n' + "closed " + '\n' , "x was a letter of 'c'. \n" + "The looking-glass hatta() " + '\n' + "opened " + '\n' + "perhaps (x<2) so \n" + "c spoke. \n" + "maybe (x<1) so \n" + "y spoke. \n" + "or \n" + "c spoke. \n"+ "because Alice was unsure which. \n" + "eventually(i==0) because \n" + "opened \n" + "c said Alice. \n" + "closed \n" + "enough times. \n" + "closed " + '\n' + "The room abs(number b) contained a letter " + '\n' + "opened " + '\n' + "b spoke. " + '\n' + "closed " + '\n' }; //System.out.println(programs[2].toString()); int i = 0 ; for (String p: programs) { i++; CharStream input = new ANTLRStringStream(p); malice_grammarLexer lexer = new malice_grammarLexer(input ); TokenStream tokens = new CommonTokenStream(lexer); malice_grammarParser parser = new malice_grammarParser(tokens ) ; - parser.program() ; + malice_grammarParser.program_return tree = parser.program() ; + System.out.println(tree.toString()); System.out.println("done program " + i + "..."); } } }
true
true
public static void main(String[] args) throws RecognitionException { String[] programs = { "x was a number of 3. " + '\n' + "The looking-glass hatta() " + '\n' + "opened " + '\n' + "The room private() contained a letter " + '\n' + "opened " + '\n' + "Alice found 1. " + '\n' + "closed" + '\n' + "x became 'y'. " + '\n' + "closed " + '\n' + "The room abs(number b) contained a letter " + '\n' + "opened " + '\n' + "b spoke. " + '\n' + "closed " + '\n' , "x was a letter of 'c'. \n" + "The looking-glass hatta() " + '\n' + "opened " + '\n' + "The room private() contained a letter " + '\n' + "opened " + '\n' + "Alice found abs(x) and " + '\n' + "abs(y) spoke. " + '\n' + "closed" + '\n' + "x became 'y'. " + '\n' + "closed " + '\n' + "The room abs(number b) contained a letter " + '\n' + "opened " + '\n' + "b spoke. " + '\n' + "closed " + '\n' , "x was a letter of 'c'. \n" + "The looking-glass hatta() " + '\n' + "opened " + '\n' + "perhaps (x<2) so \n" + "c spoke. \n" + "maybe (x<1) so \n" + "y spoke. \n" + "or \n" + "c spoke. \n"+ "because Alice was unsure which. \n" + "eventually(i==0) because \n" + "opened \n" + "c said Alice. \n" + "closed \n" + "enough times. \n" + "closed " + '\n' + "The room abs(number b) contained a letter " + '\n' + "opened " + '\n' + "b spoke. " + '\n' + "closed " + '\n' }; //System.out.println(programs[2].toString()); int i = 0 ; for (String p: programs) { i++; CharStream input = new ANTLRStringStream(p); malice_grammarLexer lexer = new malice_grammarLexer(input ); TokenStream tokens = new CommonTokenStream(lexer); malice_grammarParser parser = new malice_grammarParser(tokens ) ; parser.program() ; System.out.println("done program " + i + "..."); } }
public static void main(String[] args) throws RecognitionException { String[] programs = { "x was a number of 3. " + '\n' + "The looking-glass hatta() " + '\n' + "opened " + '\n' + "The room private() contained a letter " + '\n' + "opened " + '\n' + "Alice found 1. " + '\n' + "closed" + '\n' + "x became 'y'. " + '\n' + "closed " + '\n' + "The room abs(number b) contained a letter " + '\n' + "opened " + '\n' + "b spoke. " + '\n' + "closed " + '\n' , "x was a letter of 'c'. \n" + "The looking-glass hatta() " + '\n' + "opened " + '\n' + "The room private() contained a letter " + '\n' + "opened " + '\n' + "Alice found abs(x) and " + '\n' + "abs(y) spoke. " + '\n' + "closed" + '\n' + "x became 'y'. " + '\n' + "closed " + '\n' + "The room abs(number b) contained a letter " + '\n' + "opened " + '\n' + "b spoke. " + '\n' + "closed " + '\n' , "x was a letter of 'c'. \n" + "The looking-glass hatta() " + '\n' + "opened " + '\n' + "perhaps (x<2) so \n" + "c spoke. \n" + "maybe (x<1) so \n" + "y spoke. \n" + "or \n" + "c spoke. \n"+ "because Alice was unsure which. \n" + "eventually(i==0) because \n" + "opened \n" + "c said Alice. \n" + "closed \n" + "enough times. \n" + "closed " + '\n' + "The room abs(number b) contained a letter " + '\n' + "opened " + '\n' + "b spoke. " + '\n' + "closed " + '\n' }; //System.out.println(programs[2].toString()); int i = 0 ; for (String p: programs) { i++; CharStream input = new ANTLRStringStream(p); malice_grammarLexer lexer = new malice_grammarLexer(input ); TokenStream tokens = new CommonTokenStream(lexer); malice_grammarParser parser = new malice_grammarParser(tokens ) ; malice_grammarParser.program_return tree = parser.program() ; System.out.println(tree.toString()); System.out.println("done program " + i + "..."); } }
diff --git a/programs/slammer/gui/ResultsPanel.java b/programs/slammer/gui/ResultsPanel.java index b56faa06..3737bffd 100644 --- a/programs/slammer/gui/ResultsPanel.java +++ b/programs/slammer/gui/ResultsPanel.java @@ -1,1267 +1,1267 @@ /* This file is in the public domain. */ package slammer.gui; import javax.swing.*; import javax.swing.event.*; import javax.swing.table.*; import java.awt.*; import java.awt.event.*; import javax.swing.border.*; import org.jfree.data.xy.*; import org.jfree.data.statistics.HistogramDataset; import org.jfree.chart.*; import org.jfree.chart.axis.*; import java.text.DecimalFormat; import java.util.*; import java.util.concurrent.*; import java.io.*; import slammer.*; import slammer.analysis.*; class ResultsPanel extends JPanel implements ActionListener { public class ResultsRenderer extends DefaultTableCellRenderer { // from JTableHeader.java public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if (table != null) { JTableHeader header = table.getTableHeader(); if (header != null) { setForeground(header.getForeground()); setBackground(header.getBackground()); setFont(header.getFont()); } } setText((value == null) ? "" : value.toString()); setBorder(UIManager.getBorder("TableHeader.cellBorder")); setPreferredSize(new Dimension(table.getColumnModel().getTotalColumnWidth(), 32)); setHorizontalAlignment(JLabel.CENTER); return this; } } public class ResultThread implements Runnable { private boolean finished = false; int idx; int row; int analysis; int orientation; String eq, record; double[] ain; double result; XYSeries graphData; double _kmax, _vs, _damp; double scale, scaleRB; double di; double thrust, uwgt, height, vs, damp, refstrain, vr, g; double[][] ca; boolean paramDualslope, dv3; SynchronizedProgressFrame pm; // RigidBlock ResultThread(String eq, String record, int idx, int row, int analysis, int orientation, double[] ain, double di, double[][] ca, double scale, boolean paramDualslope, double thrust, double scaleRB, SynchronizedProgressFrame pm) { this.eq = eq; this.record = record; this.idx = idx; this.row = row; this.analysis = analysis; this.orientation = orientation; this.ain = ain; this.di = di; this.ca = ca; this.scale = scale; this.paramDualslope = paramDualslope; this.thrust = thrust; this.scaleRB = scaleRB; this.pm = pm; } // Decoupled ResultThread(String eq, String record, int idx, int row, int analysis, int orientation, double[] ain, double uwgt, double height, double vs, double damp, double refstrain, double di, double scale, double g, double vr, double[][] ca, boolean dv3, SynchronizedProgressFrame pm) { this.eq = eq; this.record = record; this.idx = idx; this.row = row; this.analysis = analysis; this.orientation = orientation; this.ain = ain; this.uwgt = uwgt; this.height = height; this.vs = vs; this.damp = damp; this.refstrain = refstrain; this.di = di; this.scale = scale; this.g = g; this.vr = vr; this.ca = ca; this.dv3 = dv3; this.pm = pm; } public void run() { Analysis a; if(analysis == RB) { a = new RigidBlock(); result = a.SlammerRigorous(ain, di, ca, scale, paramDualslope, thrust, scaleRB); } else if(analysis == DC) { a = new Decoupled(); result = a.Decoupled(ain, uwgt, height, vs, damp, refstrain, di, scale, g, vr, ca, dv3); _kmax = Math.abs(a._kmax); _vs = Math.abs(a._vs); _damp = Math.abs(a._damp); } else if(analysis == CP) { a = new Coupled(); result = a.Coupled(ain, uwgt, height, vs, damp, refstrain, di, scale, g, vr, ca, dv3); _kmax = Math.abs(a._kmax); _vs = Math.abs(a._vs); _damp = Math.abs(a._damp); } else a = null; graphData = a.graphData; finished = true; pm.incr(eq + " - " + record); } public boolean finished() { return finished; } } public class SynchronizedProgressFrame extends ProgressFrame { private int i; public SynchronizedProgressFrame(int i) { super(i); this.i = i; } public synchronized void incr(String s) { i++; if(!isCanceled()) update(i, s); } } // array indexes public final static int RB = 0; // rigid block public final static int DC = 1; // decoupled public final static int CP = 2; // coupled public final static int ANALYSIS_TYPES = 3; public final static int AVG = 2; // average public final static int NOR = 0; // normal public final static int INV = 1; // inverse public final static int ORIENTATION_TYPES = 3; // table column indicies public final static int[][] tableCols = { // N RB N DC N CP N DY LEN { 2, 3, 6, 7, 10, 11, 0, 0, 14 }, // no dynamic { 2, 3, 6, 7, 10, 11, 14, 15, 18 }, // with dynamic }; public final static int N_RB = 0; public final static int I_RB = 1; public final static int N_DC = 2; public final static int I_DC = 3; public final static int N_CP = 4; public final static int I_CP = 5; public final static int N_DY = 6; public final static int I_DY = 7; public final static int LEN = 8; public final static int NO_DYN = 0; public final static int WITH_DYN = 1; public static int NUM_CORES; java.util.Vector<ResultThread> resultVec; ExecutorService pool; String polarityName[] = { "Normal", "Inverse", "Average" }; SlammerTabbedPane parent; JTextField decimalsTF = new JTextField("1", 2); JButton Analyze = new JButton("Perform analyses"); JCheckBox dynamicRespParams = new JCheckBox("Display dynamic response parameters"); JButton ClearOutput = new JButton("Clear output"); DefaultTableModel outputTableModel = new DefaultTableModel(); JTable outputTable = new JTable(outputTableModel); JScrollPane outputTablePane = new JScrollPane(outputTable); JButton saveResultsOutput = new JButton("Save results table"); JFileChooser fc = new JFileChooser(); JButton plotHistogram = new JButton("Plot histogram of displacements"); JButton plotDisplacement = new JButton("Plot displacements versus time"); JCheckBox plotDisplacementLegend = new JCheckBox("Display legend", false); JTextField outputBins = new JTextField("10", 2); JRadioButton polarityNorDisp = new JRadioButton(polarityName[NOR], true); JRadioButton polarityInvDisp = new JRadioButton(polarityName[INV]); ButtonGroup polarityGroupDisp = new ButtonGroup(); JRadioButton polarityAvgHist = new JRadioButton(polarityName[AVG], true); JRadioButton polarityNorHist = new JRadioButton(polarityName[NOR]); JRadioButton polarityInvHist = new JRadioButton(polarityName[INV]); ButtonGroup polarityGroupHist = new ButtonGroup(); JCheckBox analysisDisp[] = new JCheckBox[ANALYSIS_TYPES]; JRadioButton analysisHist[] = new JRadioButton[ANALYSIS_TYPES]; String analysisTitle[] = new String[ANALYSIS_TYPES]; ButtonGroup analysisHistGroup = new ButtonGroup(); ArrayList results; XYSeries xys[][][]; JRadioButton outputDelTab = new JRadioButton("Tab delimited", true); JRadioButton outputDelSpace = new JRadioButton("Space delimited"); JRadioButton outputDelComma = new JRadioButton("Comma delimited"); ButtonGroup outputDelGroup = new ButtonGroup(); boolean paramUnit = false; String unitDisplacement = ""; DecimalFormat unitFmt; ArrayList dataVect[][]; XYSeriesCollection xycol; String parameters; public ResultsPanel(SlammerTabbedPane parent) throws Exception { this.parent = parent; Analyze.setActionCommand("analyze"); Analyze.addActionListener(this); ClearOutput.setActionCommand("clearOutput"); ClearOutput.addActionListener(this); saveResultsOutput.setActionCommand("saveResultsOutput"); saveResultsOutput.addActionListener(this); plotHistogram.setActionCommand("plotHistogram"); plotHistogram.addActionListener(this); plotDisplacement.setActionCommand("plotDisplacement"); plotDisplacement.addActionListener(this); plotDisplacementLegend.setActionCommand("plotDisplacementLegend"); plotDisplacementLegend.addActionListener(this); outputDelGroup.add(outputDelTab); outputDelGroup.add(outputDelSpace); outputDelGroup.add(outputDelComma); polarityGroupDisp.add(polarityNorDisp); polarityGroupDisp.add(polarityInvDisp); polarityGroupHist.add(polarityAvgHist); polarityGroupHist.add(polarityNorHist); polarityGroupHist.add(polarityInvHist); analysisDisp[RB] = new JCheckBox(ParametersPanel.stringRB); analysisDisp[DC] = new JCheckBox(ParametersPanel.stringDC); analysisDisp[CP] = new JCheckBox(ParametersPanel.stringCP); analysisHist[RB] = new JRadioButton(ParametersPanel.stringRB); analysisHist[DC] = new JRadioButton(ParametersPanel.stringDC); analysisHist[CP] = new JRadioButton(ParametersPanel.stringCP); analysisHistGroup.add(analysisHist[RB]); analysisHistGroup.add(analysisHist[DC]); analysisHistGroup.add(analysisHist[CP]); analysisTitle[RB] = "Rigid-Block"; analysisTitle[DC] = "Decoupled"; analysisTitle[CP] = "Coupled"; setLayout(new BorderLayout()); add(BorderLayout.NORTH, createHeader()); add(BorderLayout.CENTER, createTable()); add(BorderLayout.SOUTH, createGraphs()); clearOutput(); } public void actionPerformed(java.awt.event.ActionEvent e) { try { String command = e.getActionCommand(); if(command.equals("analyze")) { final SwingWorker worker = new SwingWorker() { SynchronizedProgressFrame pm = new SynchronizedProgressFrame(0); public Object construct() { try { clearOutput(); paramUnit = parent.Parameters.unitMetric.isSelected(); final double g = paramUnit ? Analysis.Gcmss : Analysis.Ginss; int dyn = dynamicRespParams.isSelected() ? WITH_DYN : NO_DYN; unitDisplacement = paramUnit ? "(cm)" : "(in.)"; String h_rb = "<html><center>" + ParametersPanel.stringRB + " " + unitDisplacement + "<p>"; String h_dc = "<html><center>" + ParametersPanel.stringDC + " " + unitDisplacement + "<p>"; String h_cp = "<html><center>" + ParametersPanel.stringCP + " " + unitDisplacement + "<p>"; String h_km = "<html><center>k<sub>max</sub> (g)<p>"; String h_damp = "<html><center>damp<p>"; String h_vs = "<html><center>"; if(parent.Parameters.paramSoilModel.getSelectedIndex() == 1) h_vs += "EQL "; h_vs += "V<sub>s</sub> (m/s)<p>"; if(dyn == NO_DYN) outputTableModel.setColumnIdentifiers(new Object[] {"Earthquake", "Record", "", h_rb + polarityName[NOR], h_rb + polarityName[INV], h_rb + polarityName[AVG], "", h_dc + polarityName[NOR], h_dc + polarityName[INV], h_dc + polarityName[AVG], "", h_cp + polarityName[NOR], h_cp + polarityName[INV], h_cp + polarityName[AVG] }); else outputTableModel.setColumnIdentifiers(new Object[] {"Earthquake", "Record", "", h_rb + polarityName[NOR], h_rb + polarityName[INV], h_rb + polarityName[AVG], "", h_dc + polarityName[NOR], h_dc + polarityName[INV], h_dc + polarityName[AVG], "", h_cp + polarityName[NOR], h_cp + polarityName[INV], h_cp + polarityName[AVG], "", h_km, h_vs, h_damp }); outputTable.getTableHeader().setDefaultRenderer(new ResultsRenderer()); outputTable.getColumnModel().getColumn(tableCols[dyn][N_RB]).setMinWidth(0); outputTable.getColumnModel().getColumn(tableCols[dyn][N_DC]).setMinWidth(0); outputTable.getColumnModel().getColumn(tableCols[dyn][N_CP]).setMinWidth(0); outputTable.getColumnModel().getColumn(tableCols[dyn][N_RB]).setPreferredWidth(5); outputTable.getColumnModel().getColumn(tableCols[dyn][N_DC]).setPreferredWidth(5); outputTable.getColumnModel().getColumn(tableCols[dyn][N_CP]).setPreferredWidth(5); outputTable.getColumnModel().getColumn(tableCols[dyn][N_RB]).setMaxWidth(5); outputTable.getColumnModel().getColumn(tableCols[dyn][N_DC]).setMaxWidth(5); outputTable.getColumnModel().getColumn(tableCols[dyn][N_CP]).setMaxWidth(5); if(dyn == WITH_DYN) { outputTable.getColumnModel().getColumn(tableCols[dyn][N_DY]).setMinWidth(0); outputTable.getColumnModel().getColumn(tableCols[dyn][N_DY]).setPreferredWidth(5); outputTable.getColumnModel().getColumn(tableCols[dyn][N_DY]).setMaxWidth(5); } boolean paramDualslope = parent.Parameters.dualSlope.isSelected(); Double d; double paramScale; if(parent.Parameters.scalePGA.isSelected()) { d = (Double)Utils.checkNum(parent.Parameters.scalePGAval.getText(), "scale PGA field", null, false, null, new Double(0), false, null, false); if(d == null) { parent.selectParameters(); return null; } paramScale = d.doubleValue(); } else if(parent.Parameters.scaleOn.isSelected()) { d = (Double)Utils.checkNum(parent.Parameters.scaleData.getText(), "scale data field", null, false, null, null, false, null, false); if(d == null) { parent.selectParameters(); return null; } paramScale = d.doubleValue(); } else paramScale = 0; changeDecimal(); boolean paramRigid = parent.Parameters.typeRigid.isSelected(); boolean paramDecoupled = parent.Parameters.typeDecoupled.isSelected(); boolean paramCoupled = parent.Parameters.typeCoupled.isSelected(); graphDisp(paramRigid, paramDecoupled, paramCoupled); if(!paramRigid && !paramDecoupled && !paramCoupled) { parent.selectParameters(); GUIUtils.popupError("Error: no analyses methods selected."); return null; } Object[][] res = Utils.getDB().runQuery("select eq, record, digi_int, path, pga from data where select2=1 and analyze=1"); if(res == null || res.length <= 1) { parent.selectSelectRecords(); GUIUtils.popupError("No records selected for analysis."); return null; } xys = new XYSeries[res.length][3][2]; dataVect = new ArrayList[3][3]; String eq, record; DoubleList dat; double di; int num = 0; double avg; double total[][] = new double[3][3]; double scale = 1, iscale, scaleRB; double inv, norm; double[][] ca; double[] ain = null; double thrust = 0, uwgt = 0, height = 0, vs = 0, damp = 0, refstrain = 0, vr = 0; boolean dv3 = false; scaleRB = paramUnit ? 1 : Analysis.CMtoIN; if(parent.Parameters.CAdisp.isSelected()) { String value; java.util.Vector caVect; TableCellEditor editor = null; editor = parent.Parameters.dispTable.getCellEditor(); caVect = parent.Parameters.dispTableModel.getDataVector(); if(editor != null) editor.stopCellEditing(); ca = new double[caVect.size()][2]; for(int i = 0; i < caVect.size(); i++) { for(int j = 0; j < 2; j++) { value = (String)(((java.util.Vector)(caVect.get(i))).get(j)); if(value == null || value == "") { parent.selectParameters(); GUIUtils.popupError("Error: empty field in table.\nPlease complete the displacement table so that all data pairs have values, or delete all empty rows."); return null; } d = (Double)Utils.checkNum(value, "displacement table", null, false, null, null, false, null, false); if(d == null) { parent.selectParameters(); return null; } ca[i][j] = d.doubleValue(); } } if(caVect.size() == 0) { parent.selectParameters(); GUIUtils.popupError("Error: no displacements listed in displacement table."); return null; } } else { d = (Double)Utils.checkNum(parent.Parameters.CAconstTF.getText(), "constant critical acceleration field", null, false, null, new Double(0), true, null, false); if(d == null) { parent.selectParameters(); return null; } ca = new double[1][2]; ca[0][0] = 0; ca[0][1] = d.doubleValue(); } if(paramRigid && paramDualslope) { Double thrustD = (Double)Utils.checkNum(parent.Parameters.thrustAngle.getText(), "thrust angle field", new Double(90), true, null, new Double(0), true, null, false); if(thrustD == null) { parent.selectParameters(); return null; } else thrust = thrustD.doubleValue(); } if(paramDecoupled || paramCoupled) { Double tempd; uwgt = 100.0; // unit weight is disabled, so hardcode to 100 tempd = (Double)Utils.checkNum(parent.Parameters.paramHeight.getText(), ParametersPanel.stringHeight + " field", null, false, null, null, false, null, false); if(tempd == null) { parent.selectParameters(); return null; } else height = tempd.doubleValue(); tempd = (Double)Utils.checkNum(parent.Parameters.paramVs.getText(), ParametersPanel.stringVs + " field", null, false, null, null, false, null, false); if(tempd == null) { parent.selectParameters(); return null; } else vs = tempd.doubleValue(); tempd = (Double)Utils.checkNum(parent.Parameters.paramVr.getText(), ParametersPanel.stringVr + " field", null, false, null, null, false, null, false); if(tempd == null) { parent.selectParameters(); return null; } else vr = tempd.doubleValue(); tempd = (Double)Utils.checkNum(parent.Parameters.paramDamp.getText(), ParametersPanel.stringDamp + " field", null, false, null, null, false, null, false); if(tempd == null) { parent.selectParameters(); return null; } else damp = tempd.doubleValue() / 100.0; tempd = (Double)Utils.checkNum(parent.Parameters.paramRefStrain.getText(), ParametersPanel.stringRefStrain + " field", null, false, null, null, false, null, false); if(tempd == null) { parent.selectParameters(); return null; } else refstrain = tempd.doubleValue(); dv3 = parent.Parameters.paramSoilModel.getSelectedIndex() == 1; // metric if(paramUnit) { uwgt /= Analysis.M3toCM3; height *= Analysis.MtoCM; vs *= Analysis.MtoCM; vr *= Analysis.MtoCM; } // english else { uwgt /= Analysis.FT3toIN3; height *= Analysis.FTtoIN; vs *= Analysis.FTtoIN; vr *= Analysis.FTtoIN; } } File testFile; String path; int num_analyses = 0; if(paramRigid) { num_analyses++; dataVect[RB][NOR] = new ArrayList<Double>(res.length - 1); dataVect[RB][INV] = new ArrayList<Double>(res.length - 1); dataVect[RB][AVG] = new ArrayList<Double>(res.length - 1); } if(paramDecoupled) { num_analyses++; dataVect[DC][NOR] = new ArrayList<Double>(res.length - 1); dataVect[DC][INV] = new ArrayList<Double>(res.length - 1); dataVect[DC][AVG] = new ArrayList<Double>(res.length - 1); } if(paramCoupled) { num_analyses++; dataVect[CP][NOR] = new ArrayList<Double>(res.length - 1); dataVect[CP][INV] = new ArrayList<Double>(res.length - 1); dataVect[CP][AVG] = new ArrayList<Double>(res.length - 1); } iscale = -1.0 * scale; pm.setMaximum(res.length * 2 * num_analyses); pm.update(0, "Initializing"); int j, k; Object[] row; int rowcount = 0; resultVec = new java.util.Vector<ResultThread>(res.length * 2 * ANALYSIS_TYPES); // 2 orientations per analysis NUM_CORES = Runtime.getRuntime().availableProcessors(); pool = Executors.newFixedThreadPool(NUM_CORES); ResultThread rt; int row_idx; long startTime = System.currentTimeMillis(); for(int i = 1; i < res.length && !pm.isCanceled(); i++) { row = new Object[tableCols[dyn][LEN]]; eq = res[i][0].toString(); row_idx = i - 1; record = res[i][1].toString(); row[0] = eq; row[1] = record; path = res[i][3].toString(); testFile = new File(path); if(!testFile.exists() || !testFile.canRead()) { row[2] = "File does not exist or is not readable"; row[3] = path; outputTableModel.addRow(row); rowcount++; continue; } dat = new DoubleList(path, 0, parent.Parameters.scaleOn.isSelected() ? paramScale : 1.0); if(dat.bad()) { row[2] = "Invalid data at point " + dat.badEntry(); row[3] = path; outputTableModel.addRow(row); rowcount++; continue; } num++; di = Double.parseDouble(res[i][2].toString()); if(parent.Parameters.scalePGA.isSelected()) { scale = paramScale / Double.parseDouble(res[i][4].toString()); iscale = -1.0 * scale; } ain = dat.getAsArray(); // do the actual analysis if(paramRigid) { rt = new ResultThread(eq, record, row_idx, rowcount, RB, NOR, ain, di, ca, scale, paramDualslope, thrust, scaleRB, pm); pool.execute(rt); resultVec.add(rt); rt = new ResultThread(eq, record, row_idx, rowcount, RB, INV, ain, di, ca, iscale, paramDualslope, thrust, scaleRB, pm); pool.execute(rt); resultVec.add(rt); } if(paramDecoupled) { // [i]scale is divided by Gcmss because the algorithm expects input data in Gs, but our input files are in cmss. this has nothing to do with, and is not affected by, the unit base being used (english or metric). - rt = new ResultThread(eq, record, row_idx, rowcount, DC, NOR, ain, uwgt, height, vs, damp, refstrain, di, scale / Analysis.Gcmss, g, vr, ca, dv3, pm); + rt = new ResultThread(eq, record, row_idx, rowcount, DC, NOR, ain, uwgt, height, vs, damp, refstrain, di, iscale / Analysis.Gcmss, g, vr, ca, dv3, pm); pool.execute(rt); resultVec.add(rt); - rt = new ResultThread(eq, record, row_idx, rowcount, DC, INV, ain, uwgt, height, vs, damp, refstrain, di, iscale / Analysis.Gcmss, g, vr, ca, dv3, pm); + rt = new ResultThread(eq, record, row_idx, rowcount, DC, INV, ain, uwgt, height, vs, damp, refstrain, di, scale / Analysis.Gcmss, g, vr, ca, dv3, pm); pool.execute(rt); resultVec.add(rt); } if(paramCoupled) { // [i]scale is divided by Gcmss because the algorithm expects input data in Gs, but our input files are in cmss. this has nothing to do with, and is not affected by, the unit base being used (english or metric). - rt = new ResultThread(eq, record, row_idx, rowcount, CP, NOR, ain, uwgt, height, vs, damp, refstrain, di, scale / Analysis.Gcmss, g, vr, ca, dv3, pm); + rt = new ResultThread(eq, record, row_idx, rowcount, CP, NOR, ain, uwgt, height, vs, damp, refstrain, di, iscale / Analysis.Gcmss, g, vr, ca, dv3, pm); pool.execute(rt); resultVec.add(rt); - rt = new ResultThread(eq, record, row_idx, rowcount, CP, INV, ain, uwgt, height, vs, damp, refstrain, di, iscale / Analysis.Gcmss, g, vr, ca, dv3, pm); + rt = new ResultThread(eq, record, row_idx, rowcount, CP, INV, ain, uwgt, height, vs, damp, refstrain, di, scale / Analysis.Gcmss, g, vr, ca, dv3, pm); pool.execute(rt); resultVec.add(rt); } outputTableModel.addRow(row); rowcount++; } pool.shutdown(); while(!pool.awaitTermination(1, TimeUnit.SECONDS)) { if(pm.isCanceled()) { pool.shutdownNow(); break; } } pm.update("Calculating results..."); ResultThread prt; int i_analysis; for(int i = 0; i < resultVec.size(); i++) { rt = resultVec.get(i); if(!rt.finished()) continue; rt.graphData.setKey(rt.eq + " - " + rt.record + " - " + ParametersPanel.stringRB + ", " + polarityName[NOR]); xys[rt.idx][rt.analysis][rt.orientation] = rt.graphData; total[rt.analysis][rt.orientation] += rt.result; i_analysis = 1 + rt.analysis * 2; for(j = 0; j < dataVect[rt.analysis][rt.orientation].size() && ((Double)dataVect[rt.analysis][rt.orientation].get(j)).doubleValue() < rt.result; j++) ; dataVect[rt.analysis][rt.orientation].add(j, new Double(rt.result)); outputTableModel.setValueAt(unitFmt.format(rt.result), rt.row, tableCols[dyn][i_analysis] + rt.orientation); // INV is always second, so NOR was already computed: we can compute avg now if(rt.orientation == INV) { prt = resultVec.get(i - 1); // NOR result avg = avg(rt.result, prt.result); total[rt.analysis][AVG] += avg; for(j = 0; j < dataVect[rt.analysis][AVG].size() && ((Double)dataVect[rt.analysis][AVG].get(j)).doubleValue() < avg; j++) ; dataVect[rt.analysis][AVG].add(j, new Double(avg)); outputTableModel.setValueAt(unitFmt.format(avg), rt.row, tableCols[dyn][i_analysis] + AVG); if(dyn == WITH_DYN && (rt.analysis == DC || rt.analysis == CP)) { outputTableModel.setValueAt(unitFmt.format(rt._kmax / g), rt.row, tableCols[dyn][I_DY] + 0); outputTableModel.setValueAt(unitFmt.format(rt._vs / Analysis.MtoCM), rt.row, tableCols[dyn][I_DY] + 1); outputTableModel.setValueAt(unitFmt.format(rt._damp), rt.row, tableCols[dyn][I_DY] + 2); } } } if(!pm.isCanceled()) { double mean, value, valtemp; int idx; Object[] rmean = new Object[tableCols[dyn][LEN]]; Object[] rmedian = new Object[tableCols[dyn][LEN]]; Object[] rsd = new Object[tableCols[dyn][LEN]]; rmean[1] = "Mean value"; rmedian[1] = "Median value"; rsd[1] = "Standard deviation"; for(j = 0; j < total.length; j++) { for(k = 0; k < total[j].length; k++) { if(dataVect[j][k] == null || dataVect[j][k].size() == 0) continue; idx = tableCols[dyn][1 + j * 2] + k; mean = Double.parseDouble(unitFmt.format(total[j][k] / num)); rmean[idx] = unitFmt.format(mean); if(num % 2 == 0) { double fst = (Double)dataVect[j][k].get(num / 2); double snd = (Double)dataVect[j][k].get(num / 2 - 1); rmedian[idx] = unitFmt.format(avg(fst, snd)); } else rmedian[idx] = unitFmt.format(dataVect[j][k].get(num / 2)); value = 0; for(int i = 0; i < num; i++) { valtemp = mean - ((Double)dataVect[j][k].get(i)).doubleValue(); value += (valtemp * valtemp); } value /= num; value = Math.sqrt(value); rsd[idx] = unitFmt.format(value); } } outputTableModel.addRow(new Object[0]); outputTableModel.addRow(rmean); outputTableModel.addRow(rmedian); outputTableModel.addRow(rsd); } } catch(Throwable ex) { Utils.catchException(ex); } return null; } public void finished() { pm.dispose(); } }; worker.start(); } else if(command.equals("clearOutput")) { clearOutput(); } else if(command.equals("saveResultsOutput")) { if(fc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) { FileWriter fw = new FileWriter(fc.getSelectedFile()); String delim; if(outputDelSpace.isSelected()) delim = " "; else if(outputDelComma.isSelected()) delim = ","; else delim = "\t"; int c = outputTableModel.getColumnCount(); int r = outputTableModel.getRowCount(); // table column headers for(int i = 0; i < c; i++) { if(i != 0) fw.write(delim); fw.write(outputTableModel.getColumnName(i).replaceAll("\\<.*?\\>", "")); } fw.write("\n"); Object o; for(int i = 0; i < r; i++) { for(int j = 0; j < c; j++) { if(j != 0) fw.write(delim); o = outputTableModel.getValueAt(i, j); if(o == null) o = ""; fw.write(o.toString()); } fw.write("\n"); } fw.close(); } } else if(command.equals("plotHistogram")) { if(dataVect == null) return; String name = "", title, pname; HistogramDataset dataset = new HistogramDataset(); int polarity, analysis = -1; if(polarityAvgHist.isSelected()) polarity = AVG; else if(polarityNorHist.isSelected()) polarity = NOR; else if(polarityInvHist.isSelected()) polarity = INV; else polarity = -1; for(int i = 0; i < analysisHist.length; i++) if(analysisHist[i].isSelected()) analysis = i; if(analysis == -1) return; pname = polarityName[polarity]; Double Bins = (Double)Utils.checkNum(outputBins.getText(), "output bins field", null, false, null, new Double(0), false, null, false); if(Bins == null || dataVect[analysis][polarity] == null) return; name = analysisTitle[analysis]; double series[] = new double[dataVect[analysis][polarity].size()]; for(int j = 0; j < dataVect[analysis][polarity].size(); j++) series[j] = (((Double)dataVect[analysis][polarity].get(j)).doubleValue()); dataset.addSeries(name, series, (int)Bins.doubleValue()); title = "Histogram of " + name + " Displacements (" + pname + " Polarity)"; JFreeChart hist = ChartFactory.createHistogram(title, "Displacement " + unitDisplacement, "Number of Records", dataset, org.jfree.chart.plot.PlotOrientation.VERTICAL, false, true, false); ChartFrame frame = new ChartFrame(title, hist); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } else if(command.equals("plotDisplacement")) { XYSeriesCollection xysc = new XYSeriesCollection(); int polarity = polarityNorDisp.isSelected() ? NOR : INV; String pname = polarityName[polarity]; String name = ""; boolean first = true; for(int i = 0; i < analysisDisp.length; i++) { if(analysisDisp[i].isSelected() && dataVect[i][polarity] != null) { if(first) first = false; else name += ", "; name += analysisTitle[i]; for(int j = 0; j < dataVect[i][polarity].size(); j++) xysc.addSeries(xys[j][i][polarity]); } } if(first) return; name += " Displacement versus Time"; JFreeChart chart = ChartFactory.createXYLineChart(name, "Time (s)", "Displacement--" + pname + " polarity " + unitDisplacement, xysc, org.jfree.chart.plot.PlotOrientation.VERTICAL, plotDisplacementLegend.isSelected(), true, false); //margins are stupid chart.getXYPlot().getDomainAxis().setLowerMargin(0); chart.getXYPlot().getDomainAxis().setUpperMargin(0); chart.getXYPlot().getDomainAxis().setLowerBound(0); ChartFrame frame = new ChartFrame(name, chart); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } } catch(Exception ex) { Utils.catchException(ex); } } private JPanel createHeader() { JPanel containerL = new JPanel(); containerL.add(new JLabel("Display results to")); containerL.add(decimalsTF); containerL.add(new JLabel("decimals. ")); JPanel container = new JPanel(new BorderLayout()); container.add(containerL, BorderLayout.WEST); container.add(Analyze, BorderLayout.CENTER); JPanel east = new JPanel(); east.add(dynamicRespParams); east.add(ClearOutput); container.add(east, BorderLayout.EAST); return container; } private JPanel createTable() { JPanel outputTablePanel = new JPanel(new BorderLayout()); outputTablePanel.add(BorderLayout.CENTER, outputTablePane); return outputTablePanel; } private JTabbedPane createGraphs() { JTabbedPane jtp = new JTabbedPane(); jtp.add("Graph displacements", createGraphDisplacementsPanel()); jtp.add("Graph histogram", createGraphHistogramPanel()); jtp.add("Save results table", createSaveResultsPanel()); return jtp; } private JPanel createGraphDisplacementsPanel() { JPanel panel = new JPanel(); GridBagLayout gridbag = new GridBagLayout(); panel.setLayout(gridbag); GridBagConstraints c = new GridBagConstraints(); JLabel label; int x = 0; int y = 0; c.anchor = GridBagConstraints.NORTHWEST; c.gridx = x++; c.gridy = y++; label = new JLabel("Analyses:"); gridbag.setConstraints(label, c); panel.add(label); c.gridy = y++; gridbag.setConstraints(analysisDisp[RB], c); panel.add(analysisDisp[RB]); c.gridy = y++; gridbag.setConstraints(analysisDisp[DC], c); panel.add(analysisDisp[DC]); c.gridy = y++; gridbag.setConstraints(analysisDisp[CP], c); panel.add(analysisDisp[CP]); y = 0; c.gridy = y++; c.gridx = x++; c.insets = new Insets(0, 5, 0, 0); label = new JLabel("Polarity:"); gridbag.setConstraints(label, c); panel.add(label); c.gridy = y++; gridbag.setConstraints(polarityNorDisp, c); panel.add(polarityNorDisp); c.gridy = y++; gridbag.setConstraints(polarityInvDisp, c); panel.add(polarityInvDisp); y = 0; c.gridy = y++; c.gridx = x++; c.gridheight = 2; c.anchor = GridBagConstraints.WEST; gridbag.setConstraints(plotDisplacement, c); panel.add(plotDisplacement); y++; c.gridy = y; gridbag.setConstraints(plotDisplacementLegend, c); panel.add(plotDisplacementLegend); c.gridx = x; label = new JLabel(); c.weightx = 1; gridbag.setConstraints(label, c); panel.add(label); return panel; } private JPanel createGraphHistogramPanel() { JPanel panel = new JPanel(); GridBagLayout gridbag = new GridBagLayout(); panel.setLayout(gridbag); GridBagConstraints c = new GridBagConstraints(); JLabel label; int x = 0; int y = 0; c.anchor = GridBagConstraints.NORTHWEST; c.gridx = x++; c.gridy = y++; label = new JLabel("Analysis:"); gridbag.setConstraints(label, c); panel.add(label); c.gridy = y++; gridbag.setConstraints(analysisHist[RB], c); panel.add(analysisHist[RB]); c.gridy = y++; gridbag.setConstraints(analysisHist[DC], c); panel.add(analysisHist[DC]); c.gridy = y++; gridbag.setConstraints(analysisHist[CP], c); panel.add(analysisHist[CP]); y = 0; c.gridy = y++; c.gridx = x++; c.insets = new Insets(0, 5, 0, 0); label = new JLabel("Polarity:"); gridbag.setConstraints(label, c); panel.add(label); c.gridy = y++; gridbag.setConstraints(polarityAvgHist, c); panel.add(polarityAvgHist); c.gridy = y++; gridbag.setConstraints(polarityNorHist, c); panel.add(polarityNorHist); c.gridy = y++; gridbag.setConstraints(polarityInvHist, c); panel.add(polarityInvHist); y = 0; c.gridx = x++; c.gridy = y++; c.gridheight = 2; c.anchor = GridBagConstraints.WEST; gridbag.setConstraints(plotHistogram, c); panel.add(plotHistogram); JPanel bins = new JPanel(); bins.add(new JLabel("Plot with ")); bins.add(outputBins); bins.add(new JLabel(" bins.")); y++; c.gridy = y; gridbag.setConstraints(bins, c); panel.add(bins); c.gridx = x; label = new JLabel(); c.weightx = 1; gridbag.setConstraints(label, c); panel.add(label); return panel; } private JPanel createSaveResultsPanel() { JPanel panel = new JPanel(); GridBagLayout gridbag = new GridBagLayout(); panel.setLayout(gridbag); GridBagConstraints c = new GridBagConstraints(); JLabel label; int x = 0; int y = 0; c.anchor = GridBagConstraints.WEST; c.gridx = x++; c.gridy = y++; gridbag.setConstraints(outputDelTab, c); panel.add(outputDelTab); c.gridy = y++; gridbag.setConstraints(outputDelSpace, c); panel.add(outputDelSpace); c.gridy = y++; gridbag.setConstraints(outputDelComma, c); panel.add(outputDelComma); c.gridx = x++; c.gridheight = y; c.gridy = 0; gridbag.setConstraints(saveResultsOutput, c); panel.add(saveResultsOutput); c.gridx = x; label = new JLabel(); c.weightx = 1; gridbag.setConstraints(label, c); panel.add(label); return panel; } private void clearOutput() { dataVect = null; xys = null; graphDisp(false, false, false); outputTableModel.setRowCount(0); } private void graphDisp(boolean rigid, boolean decoupled, boolean coupled) { boolean any = rigid || decoupled || coupled; analysisDisp[RB].setEnabled(rigid); analysisHist[RB].setEnabled(rigid); analysisDisp[DC].setEnabled(decoupled); analysisHist[DC].setEnabled(decoupled); analysisDisp[CP].setEnabled(coupled); analysisHist[CP].setEnabled(coupled); plotHistogram.setEnabled(any); plotDisplacement.setEnabled(any); } private void changeDecimal() { int i; Double d = (Double)Utils.checkNum(decimalsTF.getText(), "display decimals field", null, false, null, new Double(0), true, null, false); if(d == null) i = 1; else i = (int)d.doubleValue(); String s = "0"; if(i > 0) s = s + "."; while(i-- > 0) s = s + "0"; unitFmt = new DecimalFormat(s); } private double avg(final double a, final double b) { return (a + b) / 2.0; } }
false
true
public void actionPerformed(java.awt.event.ActionEvent e) { try { String command = e.getActionCommand(); if(command.equals("analyze")) { final SwingWorker worker = new SwingWorker() { SynchronizedProgressFrame pm = new SynchronizedProgressFrame(0); public Object construct() { try { clearOutput(); paramUnit = parent.Parameters.unitMetric.isSelected(); final double g = paramUnit ? Analysis.Gcmss : Analysis.Ginss; int dyn = dynamicRespParams.isSelected() ? WITH_DYN : NO_DYN; unitDisplacement = paramUnit ? "(cm)" : "(in.)"; String h_rb = "<html><center>" + ParametersPanel.stringRB + " " + unitDisplacement + "<p>"; String h_dc = "<html><center>" + ParametersPanel.stringDC + " " + unitDisplacement + "<p>"; String h_cp = "<html><center>" + ParametersPanel.stringCP + " " + unitDisplacement + "<p>"; String h_km = "<html><center>k<sub>max</sub> (g)<p>"; String h_damp = "<html><center>damp<p>"; String h_vs = "<html><center>"; if(parent.Parameters.paramSoilModel.getSelectedIndex() == 1) h_vs += "EQL "; h_vs += "V<sub>s</sub> (m/s)<p>"; if(dyn == NO_DYN) outputTableModel.setColumnIdentifiers(new Object[] {"Earthquake", "Record", "", h_rb + polarityName[NOR], h_rb + polarityName[INV], h_rb + polarityName[AVG], "", h_dc + polarityName[NOR], h_dc + polarityName[INV], h_dc + polarityName[AVG], "", h_cp + polarityName[NOR], h_cp + polarityName[INV], h_cp + polarityName[AVG] }); else outputTableModel.setColumnIdentifiers(new Object[] {"Earthquake", "Record", "", h_rb + polarityName[NOR], h_rb + polarityName[INV], h_rb + polarityName[AVG], "", h_dc + polarityName[NOR], h_dc + polarityName[INV], h_dc + polarityName[AVG], "", h_cp + polarityName[NOR], h_cp + polarityName[INV], h_cp + polarityName[AVG], "", h_km, h_vs, h_damp }); outputTable.getTableHeader().setDefaultRenderer(new ResultsRenderer()); outputTable.getColumnModel().getColumn(tableCols[dyn][N_RB]).setMinWidth(0); outputTable.getColumnModel().getColumn(tableCols[dyn][N_DC]).setMinWidth(0); outputTable.getColumnModel().getColumn(tableCols[dyn][N_CP]).setMinWidth(0); outputTable.getColumnModel().getColumn(tableCols[dyn][N_RB]).setPreferredWidth(5); outputTable.getColumnModel().getColumn(tableCols[dyn][N_DC]).setPreferredWidth(5); outputTable.getColumnModel().getColumn(tableCols[dyn][N_CP]).setPreferredWidth(5); outputTable.getColumnModel().getColumn(tableCols[dyn][N_RB]).setMaxWidth(5); outputTable.getColumnModel().getColumn(tableCols[dyn][N_DC]).setMaxWidth(5); outputTable.getColumnModel().getColumn(tableCols[dyn][N_CP]).setMaxWidth(5); if(dyn == WITH_DYN) { outputTable.getColumnModel().getColumn(tableCols[dyn][N_DY]).setMinWidth(0); outputTable.getColumnModel().getColumn(tableCols[dyn][N_DY]).setPreferredWidth(5); outputTable.getColumnModel().getColumn(tableCols[dyn][N_DY]).setMaxWidth(5); } boolean paramDualslope = parent.Parameters.dualSlope.isSelected(); Double d; double paramScale; if(parent.Parameters.scalePGA.isSelected()) { d = (Double)Utils.checkNum(parent.Parameters.scalePGAval.getText(), "scale PGA field", null, false, null, new Double(0), false, null, false); if(d == null) { parent.selectParameters(); return null; } paramScale = d.doubleValue(); } else if(parent.Parameters.scaleOn.isSelected()) { d = (Double)Utils.checkNum(parent.Parameters.scaleData.getText(), "scale data field", null, false, null, null, false, null, false); if(d == null) { parent.selectParameters(); return null; } paramScale = d.doubleValue(); } else paramScale = 0; changeDecimal(); boolean paramRigid = parent.Parameters.typeRigid.isSelected(); boolean paramDecoupled = parent.Parameters.typeDecoupled.isSelected(); boolean paramCoupled = parent.Parameters.typeCoupled.isSelected(); graphDisp(paramRigid, paramDecoupled, paramCoupled); if(!paramRigid && !paramDecoupled && !paramCoupled) { parent.selectParameters(); GUIUtils.popupError("Error: no analyses methods selected."); return null; } Object[][] res = Utils.getDB().runQuery("select eq, record, digi_int, path, pga from data where select2=1 and analyze=1"); if(res == null || res.length <= 1) { parent.selectSelectRecords(); GUIUtils.popupError("No records selected for analysis."); return null; } xys = new XYSeries[res.length][3][2]; dataVect = new ArrayList[3][3]; String eq, record; DoubleList dat; double di; int num = 0; double avg; double total[][] = new double[3][3]; double scale = 1, iscale, scaleRB; double inv, norm; double[][] ca; double[] ain = null; double thrust = 0, uwgt = 0, height = 0, vs = 0, damp = 0, refstrain = 0, vr = 0; boolean dv3 = false; scaleRB = paramUnit ? 1 : Analysis.CMtoIN; if(parent.Parameters.CAdisp.isSelected()) { String value; java.util.Vector caVect; TableCellEditor editor = null; editor = parent.Parameters.dispTable.getCellEditor(); caVect = parent.Parameters.dispTableModel.getDataVector(); if(editor != null) editor.stopCellEditing(); ca = new double[caVect.size()][2]; for(int i = 0; i < caVect.size(); i++) { for(int j = 0; j < 2; j++) { value = (String)(((java.util.Vector)(caVect.get(i))).get(j)); if(value == null || value == "") { parent.selectParameters(); GUIUtils.popupError("Error: empty field in table.\nPlease complete the displacement table so that all data pairs have values, or delete all empty rows."); return null; } d = (Double)Utils.checkNum(value, "displacement table", null, false, null, null, false, null, false); if(d == null) { parent.selectParameters(); return null; } ca[i][j] = d.doubleValue(); } } if(caVect.size() == 0) { parent.selectParameters(); GUIUtils.popupError("Error: no displacements listed in displacement table."); return null; } } else { d = (Double)Utils.checkNum(parent.Parameters.CAconstTF.getText(), "constant critical acceleration field", null, false, null, new Double(0), true, null, false); if(d == null) { parent.selectParameters(); return null; } ca = new double[1][2]; ca[0][0] = 0; ca[0][1] = d.doubleValue(); } if(paramRigid && paramDualslope) { Double thrustD = (Double)Utils.checkNum(parent.Parameters.thrustAngle.getText(), "thrust angle field", new Double(90), true, null, new Double(0), true, null, false); if(thrustD == null) { parent.selectParameters(); return null; } else thrust = thrustD.doubleValue(); } if(paramDecoupled || paramCoupled) { Double tempd; uwgt = 100.0; // unit weight is disabled, so hardcode to 100 tempd = (Double)Utils.checkNum(parent.Parameters.paramHeight.getText(), ParametersPanel.stringHeight + " field", null, false, null, null, false, null, false); if(tempd == null) { parent.selectParameters(); return null; } else height = tempd.doubleValue(); tempd = (Double)Utils.checkNum(parent.Parameters.paramVs.getText(), ParametersPanel.stringVs + " field", null, false, null, null, false, null, false); if(tempd == null) { parent.selectParameters(); return null; } else vs = tempd.doubleValue(); tempd = (Double)Utils.checkNum(parent.Parameters.paramVr.getText(), ParametersPanel.stringVr + " field", null, false, null, null, false, null, false); if(tempd == null) { parent.selectParameters(); return null; } else vr = tempd.doubleValue(); tempd = (Double)Utils.checkNum(parent.Parameters.paramDamp.getText(), ParametersPanel.stringDamp + " field", null, false, null, null, false, null, false); if(tempd == null) { parent.selectParameters(); return null; } else damp = tempd.doubleValue() / 100.0; tempd = (Double)Utils.checkNum(parent.Parameters.paramRefStrain.getText(), ParametersPanel.stringRefStrain + " field", null, false, null, null, false, null, false); if(tempd == null) { parent.selectParameters(); return null; } else refstrain = tempd.doubleValue(); dv3 = parent.Parameters.paramSoilModel.getSelectedIndex() == 1; // metric if(paramUnit) { uwgt /= Analysis.M3toCM3; height *= Analysis.MtoCM; vs *= Analysis.MtoCM; vr *= Analysis.MtoCM; } // english else { uwgt /= Analysis.FT3toIN3; height *= Analysis.FTtoIN; vs *= Analysis.FTtoIN; vr *= Analysis.FTtoIN; } } File testFile; String path; int num_analyses = 0; if(paramRigid) { num_analyses++; dataVect[RB][NOR] = new ArrayList<Double>(res.length - 1); dataVect[RB][INV] = new ArrayList<Double>(res.length - 1); dataVect[RB][AVG] = new ArrayList<Double>(res.length - 1); } if(paramDecoupled) { num_analyses++; dataVect[DC][NOR] = new ArrayList<Double>(res.length - 1); dataVect[DC][INV] = new ArrayList<Double>(res.length - 1); dataVect[DC][AVG] = new ArrayList<Double>(res.length - 1); } if(paramCoupled) { num_analyses++; dataVect[CP][NOR] = new ArrayList<Double>(res.length - 1); dataVect[CP][INV] = new ArrayList<Double>(res.length - 1); dataVect[CP][AVG] = new ArrayList<Double>(res.length - 1); } iscale = -1.0 * scale; pm.setMaximum(res.length * 2 * num_analyses); pm.update(0, "Initializing"); int j, k; Object[] row; int rowcount = 0; resultVec = new java.util.Vector<ResultThread>(res.length * 2 * ANALYSIS_TYPES); // 2 orientations per analysis NUM_CORES = Runtime.getRuntime().availableProcessors(); pool = Executors.newFixedThreadPool(NUM_CORES); ResultThread rt; int row_idx; long startTime = System.currentTimeMillis(); for(int i = 1; i < res.length && !pm.isCanceled(); i++) { row = new Object[tableCols[dyn][LEN]]; eq = res[i][0].toString(); row_idx = i - 1; record = res[i][1].toString(); row[0] = eq; row[1] = record; path = res[i][3].toString(); testFile = new File(path); if(!testFile.exists() || !testFile.canRead()) { row[2] = "File does not exist or is not readable"; row[3] = path; outputTableModel.addRow(row); rowcount++; continue; } dat = new DoubleList(path, 0, parent.Parameters.scaleOn.isSelected() ? paramScale : 1.0); if(dat.bad()) { row[2] = "Invalid data at point " + dat.badEntry(); row[3] = path; outputTableModel.addRow(row); rowcount++; continue; } num++; di = Double.parseDouble(res[i][2].toString()); if(parent.Parameters.scalePGA.isSelected()) { scale = paramScale / Double.parseDouble(res[i][4].toString()); iscale = -1.0 * scale; } ain = dat.getAsArray(); // do the actual analysis if(paramRigid) { rt = new ResultThread(eq, record, row_idx, rowcount, RB, NOR, ain, di, ca, scale, paramDualslope, thrust, scaleRB, pm); pool.execute(rt); resultVec.add(rt); rt = new ResultThread(eq, record, row_idx, rowcount, RB, INV, ain, di, ca, iscale, paramDualslope, thrust, scaleRB, pm); pool.execute(rt); resultVec.add(rt); } if(paramDecoupled) { // [i]scale is divided by Gcmss because the algorithm expects input data in Gs, but our input files are in cmss. this has nothing to do with, and is not affected by, the unit base being used (english or metric). rt = new ResultThread(eq, record, row_idx, rowcount, DC, NOR, ain, uwgt, height, vs, damp, refstrain, di, scale / Analysis.Gcmss, g, vr, ca, dv3, pm); pool.execute(rt); resultVec.add(rt); rt = new ResultThread(eq, record, row_idx, rowcount, DC, INV, ain, uwgt, height, vs, damp, refstrain, di, iscale / Analysis.Gcmss, g, vr, ca, dv3, pm); pool.execute(rt); resultVec.add(rt); } if(paramCoupled) { // [i]scale is divided by Gcmss because the algorithm expects input data in Gs, but our input files are in cmss. this has nothing to do with, and is not affected by, the unit base being used (english or metric). rt = new ResultThread(eq, record, row_idx, rowcount, CP, NOR, ain, uwgt, height, vs, damp, refstrain, di, scale / Analysis.Gcmss, g, vr, ca, dv3, pm); pool.execute(rt); resultVec.add(rt); rt = new ResultThread(eq, record, row_idx, rowcount, CP, INV, ain, uwgt, height, vs, damp, refstrain, di, iscale / Analysis.Gcmss, g, vr, ca, dv3, pm); pool.execute(rt); resultVec.add(rt); } outputTableModel.addRow(row); rowcount++; } pool.shutdown(); while(!pool.awaitTermination(1, TimeUnit.SECONDS)) { if(pm.isCanceled()) { pool.shutdownNow(); break; } } pm.update("Calculating results..."); ResultThread prt; int i_analysis; for(int i = 0; i < resultVec.size(); i++) { rt = resultVec.get(i); if(!rt.finished()) continue; rt.graphData.setKey(rt.eq + " - " + rt.record + " - " + ParametersPanel.stringRB + ", " + polarityName[NOR]); xys[rt.idx][rt.analysis][rt.orientation] = rt.graphData; total[rt.analysis][rt.orientation] += rt.result; i_analysis = 1 + rt.analysis * 2; for(j = 0; j < dataVect[rt.analysis][rt.orientation].size() && ((Double)dataVect[rt.analysis][rt.orientation].get(j)).doubleValue() < rt.result; j++) ; dataVect[rt.analysis][rt.orientation].add(j, new Double(rt.result)); outputTableModel.setValueAt(unitFmt.format(rt.result), rt.row, tableCols[dyn][i_analysis] + rt.orientation); // INV is always second, so NOR was already computed: we can compute avg now if(rt.orientation == INV) { prt = resultVec.get(i - 1); // NOR result avg = avg(rt.result, prt.result); total[rt.analysis][AVG] += avg; for(j = 0; j < dataVect[rt.analysis][AVG].size() && ((Double)dataVect[rt.analysis][AVG].get(j)).doubleValue() < avg; j++) ; dataVect[rt.analysis][AVG].add(j, new Double(avg)); outputTableModel.setValueAt(unitFmt.format(avg), rt.row, tableCols[dyn][i_analysis] + AVG); if(dyn == WITH_DYN && (rt.analysis == DC || rt.analysis == CP)) { outputTableModel.setValueAt(unitFmt.format(rt._kmax / g), rt.row, tableCols[dyn][I_DY] + 0); outputTableModel.setValueAt(unitFmt.format(rt._vs / Analysis.MtoCM), rt.row, tableCols[dyn][I_DY] + 1); outputTableModel.setValueAt(unitFmt.format(rt._damp), rt.row, tableCols[dyn][I_DY] + 2); } } } if(!pm.isCanceled()) { double mean, value, valtemp; int idx; Object[] rmean = new Object[tableCols[dyn][LEN]]; Object[] rmedian = new Object[tableCols[dyn][LEN]]; Object[] rsd = new Object[tableCols[dyn][LEN]]; rmean[1] = "Mean value"; rmedian[1] = "Median value"; rsd[1] = "Standard deviation"; for(j = 0; j < total.length; j++) { for(k = 0; k < total[j].length; k++) { if(dataVect[j][k] == null || dataVect[j][k].size() == 0) continue; idx = tableCols[dyn][1 + j * 2] + k; mean = Double.parseDouble(unitFmt.format(total[j][k] / num)); rmean[idx] = unitFmt.format(mean); if(num % 2 == 0) { double fst = (Double)dataVect[j][k].get(num / 2); double snd = (Double)dataVect[j][k].get(num / 2 - 1); rmedian[idx] = unitFmt.format(avg(fst, snd)); } else rmedian[idx] = unitFmt.format(dataVect[j][k].get(num / 2)); value = 0; for(int i = 0; i < num; i++) { valtemp = mean - ((Double)dataVect[j][k].get(i)).doubleValue(); value += (valtemp * valtemp); } value /= num; value = Math.sqrt(value); rsd[idx] = unitFmt.format(value); } } outputTableModel.addRow(new Object[0]); outputTableModel.addRow(rmean); outputTableModel.addRow(rmedian); outputTableModel.addRow(rsd); } } catch(Throwable ex) { Utils.catchException(ex); } return null; } public void finished() { pm.dispose(); } }; worker.start(); } else if(command.equals("clearOutput")) { clearOutput(); } else if(command.equals("saveResultsOutput")) { if(fc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) { FileWriter fw = new FileWriter(fc.getSelectedFile()); String delim; if(outputDelSpace.isSelected()) delim = " "; else if(outputDelComma.isSelected()) delim = ","; else delim = "\t"; int c = outputTableModel.getColumnCount(); int r = outputTableModel.getRowCount(); // table column headers for(int i = 0; i < c; i++) { if(i != 0) fw.write(delim); fw.write(outputTableModel.getColumnName(i).replaceAll("\\<.*?\\>", "")); } fw.write("\n"); Object o; for(int i = 0; i < r; i++) { for(int j = 0; j < c; j++) { if(j != 0) fw.write(delim); o = outputTableModel.getValueAt(i, j); if(o == null) o = ""; fw.write(o.toString()); } fw.write("\n"); } fw.close(); } } else if(command.equals("plotHistogram")) { if(dataVect == null) return; String name = "", title, pname; HistogramDataset dataset = new HistogramDataset(); int polarity, analysis = -1; if(polarityAvgHist.isSelected()) polarity = AVG; else if(polarityNorHist.isSelected()) polarity = NOR; else if(polarityInvHist.isSelected()) polarity = INV; else polarity = -1; for(int i = 0; i < analysisHist.length; i++) if(analysisHist[i].isSelected()) analysis = i; if(analysis == -1) return; pname = polarityName[polarity]; Double Bins = (Double)Utils.checkNum(outputBins.getText(), "output bins field", null, false, null, new Double(0), false, null, false); if(Bins == null || dataVect[analysis][polarity] == null) return; name = analysisTitle[analysis]; double series[] = new double[dataVect[analysis][polarity].size()]; for(int j = 0; j < dataVect[analysis][polarity].size(); j++) series[j] = (((Double)dataVect[analysis][polarity].get(j)).doubleValue()); dataset.addSeries(name, series, (int)Bins.doubleValue()); title = "Histogram of " + name + " Displacements (" + pname + " Polarity)"; JFreeChart hist = ChartFactory.createHistogram(title, "Displacement " + unitDisplacement, "Number of Records", dataset, org.jfree.chart.plot.PlotOrientation.VERTICAL, false, true, false); ChartFrame frame = new ChartFrame(title, hist); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } else if(command.equals("plotDisplacement")) { XYSeriesCollection xysc = new XYSeriesCollection(); int polarity = polarityNorDisp.isSelected() ? NOR : INV; String pname = polarityName[polarity]; String name = ""; boolean first = true; for(int i = 0; i < analysisDisp.length; i++) { if(analysisDisp[i].isSelected() && dataVect[i][polarity] != null) { if(first) first = false; else name += ", "; name += analysisTitle[i]; for(int j = 0; j < dataVect[i][polarity].size(); j++) xysc.addSeries(xys[j][i][polarity]); } } if(first) return; name += " Displacement versus Time"; JFreeChart chart = ChartFactory.createXYLineChart(name, "Time (s)", "Displacement--" + pname + " polarity " + unitDisplacement, xysc, org.jfree.chart.plot.PlotOrientation.VERTICAL, plotDisplacementLegend.isSelected(), true, false); //margins are stupid chart.getXYPlot().getDomainAxis().setLowerMargin(0); chart.getXYPlot().getDomainAxis().setUpperMargin(0); chart.getXYPlot().getDomainAxis().setLowerBound(0); ChartFrame frame = new ChartFrame(name, chart); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } } catch(Exception ex) { Utils.catchException(ex); } }
public void actionPerformed(java.awt.event.ActionEvent e) { try { String command = e.getActionCommand(); if(command.equals("analyze")) { final SwingWorker worker = new SwingWorker() { SynchronizedProgressFrame pm = new SynchronizedProgressFrame(0); public Object construct() { try { clearOutput(); paramUnit = parent.Parameters.unitMetric.isSelected(); final double g = paramUnit ? Analysis.Gcmss : Analysis.Ginss; int dyn = dynamicRespParams.isSelected() ? WITH_DYN : NO_DYN; unitDisplacement = paramUnit ? "(cm)" : "(in.)"; String h_rb = "<html><center>" + ParametersPanel.stringRB + " " + unitDisplacement + "<p>"; String h_dc = "<html><center>" + ParametersPanel.stringDC + " " + unitDisplacement + "<p>"; String h_cp = "<html><center>" + ParametersPanel.stringCP + " " + unitDisplacement + "<p>"; String h_km = "<html><center>k<sub>max</sub> (g)<p>"; String h_damp = "<html><center>damp<p>"; String h_vs = "<html><center>"; if(parent.Parameters.paramSoilModel.getSelectedIndex() == 1) h_vs += "EQL "; h_vs += "V<sub>s</sub> (m/s)<p>"; if(dyn == NO_DYN) outputTableModel.setColumnIdentifiers(new Object[] {"Earthquake", "Record", "", h_rb + polarityName[NOR], h_rb + polarityName[INV], h_rb + polarityName[AVG], "", h_dc + polarityName[NOR], h_dc + polarityName[INV], h_dc + polarityName[AVG], "", h_cp + polarityName[NOR], h_cp + polarityName[INV], h_cp + polarityName[AVG] }); else outputTableModel.setColumnIdentifiers(new Object[] {"Earthquake", "Record", "", h_rb + polarityName[NOR], h_rb + polarityName[INV], h_rb + polarityName[AVG], "", h_dc + polarityName[NOR], h_dc + polarityName[INV], h_dc + polarityName[AVG], "", h_cp + polarityName[NOR], h_cp + polarityName[INV], h_cp + polarityName[AVG], "", h_km, h_vs, h_damp }); outputTable.getTableHeader().setDefaultRenderer(new ResultsRenderer()); outputTable.getColumnModel().getColumn(tableCols[dyn][N_RB]).setMinWidth(0); outputTable.getColumnModel().getColumn(tableCols[dyn][N_DC]).setMinWidth(0); outputTable.getColumnModel().getColumn(tableCols[dyn][N_CP]).setMinWidth(0); outputTable.getColumnModel().getColumn(tableCols[dyn][N_RB]).setPreferredWidth(5); outputTable.getColumnModel().getColumn(tableCols[dyn][N_DC]).setPreferredWidth(5); outputTable.getColumnModel().getColumn(tableCols[dyn][N_CP]).setPreferredWidth(5); outputTable.getColumnModel().getColumn(tableCols[dyn][N_RB]).setMaxWidth(5); outputTable.getColumnModel().getColumn(tableCols[dyn][N_DC]).setMaxWidth(5); outputTable.getColumnModel().getColumn(tableCols[dyn][N_CP]).setMaxWidth(5); if(dyn == WITH_DYN) { outputTable.getColumnModel().getColumn(tableCols[dyn][N_DY]).setMinWidth(0); outputTable.getColumnModel().getColumn(tableCols[dyn][N_DY]).setPreferredWidth(5); outputTable.getColumnModel().getColumn(tableCols[dyn][N_DY]).setMaxWidth(5); } boolean paramDualslope = parent.Parameters.dualSlope.isSelected(); Double d; double paramScale; if(parent.Parameters.scalePGA.isSelected()) { d = (Double)Utils.checkNum(parent.Parameters.scalePGAval.getText(), "scale PGA field", null, false, null, new Double(0), false, null, false); if(d == null) { parent.selectParameters(); return null; } paramScale = d.doubleValue(); } else if(parent.Parameters.scaleOn.isSelected()) { d = (Double)Utils.checkNum(parent.Parameters.scaleData.getText(), "scale data field", null, false, null, null, false, null, false); if(d == null) { parent.selectParameters(); return null; } paramScale = d.doubleValue(); } else paramScale = 0; changeDecimal(); boolean paramRigid = parent.Parameters.typeRigid.isSelected(); boolean paramDecoupled = parent.Parameters.typeDecoupled.isSelected(); boolean paramCoupled = parent.Parameters.typeCoupled.isSelected(); graphDisp(paramRigid, paramDecoupled, paramCoupled); if(!paramRigid && !paramDecoupled && !paramCoupled) { parent.selectParameters(); GUIUtils.popupError("Error: no analyses methods selected."); return null; } Object[][] res = Utils.getDB().runQuery("select eq, record, digi_int, path, pga from data where select2=1 and analyze=1"); if(res == null || res.length <= 1) { parent.selectSelectRecords(); GUIUtils.popupError("No records selected for analysis."); return null; } xys = new XYSeries[res.length][3][2]; dataVect = new ArrayList[3][3]; String eq, record; DoubleList dat; double di; int num = 0; double avg; double total[][] = new double[3][3]; double scale = 1, iscale, scaleRB; double inv, norm; double[][] ca; double[] ain = null; double thrust = 0, uwgt = 0, height = 0, vs = 0, damp = 0, refstrain = 0, vr = 0; boolean dv3 = false; scaleRB = paramUnit ? 1 : Analysis.CMtoIN; if(parent.Parameters.CAdisp.isSelected()) { String value; java.util.Vector caVect; TableCellEditor editor = null; editor = parent.Parameters.dispTable.getCellEditor(); caVect = parent.Parameters.dispTableModel.getDataVector(); if(editor != null) editor.stopCellEditing(); ca = new double[caVect.size()][2]; for(int i = 0; i < caVect.size(); i++) { for(int j = 0; j < 2; j++) { value = (String)(((java.util.Vector)(caVect.get(i))).get(j)); if(value == null || value == "") { parent.selectParameters(); GUIUtils.popupError("Error: empty field in table.\nPlease complete the displacement table so that all data pairs have values, or delete all empty rows."); return null; } d = (Double)Utils.checkNum(value, "displacement table", null, false, null, null, false, null, false); if(d == null) { parent.selectParameters(); return null; } ca[i][j] = d.doubleValue(); } } if(caVect.size() == 0) { parent.selectParameters(); GUIUtils.popupError("Error: no displacements listed in displacement table."); return null; } } else { d = (Double)Utils.checkNum(parent.Parameters.CAconstTF.getText(), "constant critical acceleration field", null, false, null, new Double(0), true, null, false); if(d == null) { parent.selectParameters(); return null; } ca = new double[1][2]; ca[0][0] = 0; ca[0][1] = d.doubleValue(); } if(paramRigid && paramDualslope) { Double thrustD = (Double)Utils.checkNum(parent.Parameters.thrustAngle.getText(), "thrust angle field", new Double(90), true, null, new Double(0), true, null, false); if(thrustD == null) { parent.selectParameters(); return null; } else thrust = thrustD.doubleValue(); } if(paramDecoupled || paramCoupled) { Double tempd; uwgt = 100.0; // unit weight is disabled, so hardcode to 100 tempd = (Double)Utils.checkNum(parent.Parameters.paramHeight.getText(), ParametersPanel.stringHeight + " field", null, false, null, null, false, null, false); if(tempd == null) { parent.selectParameters(); return null; } else height = tempd.doubleValue(); tempd = (Double)Utils.checkNum(parent.Parameters.paramVs.getText(), ParametersPanel.stringVs + " field", null, false, null, null, false, null, false); if(tempd == null) { parent.selectParameters(); return null; } else vs = tempd.doubleValue(); tempd = (Double)Utils.checkNum(parent.Parameters.paramVr.getText(), ParametersPanel.stringVr + " field", null, false, null, null, false, null, false); if(tempd == null) { parent.selectParameters(); return null; } else vr = tempd.doubleValue(); tempd = (Double)Utils.checkNum(parent.Parameters.paramDamp.getText(), ParametersPanel.stringDamp + " field", null, false, null, null, false, null, false); if(tempd == null) { parent.selectParameters(); return null; } else damp = tempd.doubleValue() / 100.0; tempd = (Double)Utils.checkNum(parent.Parameters.paramRefStrain.getText(), ParametersPanel.stringRefStrain + " field", null, false, null, null, false, null, false); if(tempd == null) { parent.selectParameters(); return null; } else refstrain = tempd.doubleValue(); dv3 = parent.Parameters.paramSoilModel.getSelectedIndex() == 1; // metric if(paramUnit) { uwgt /= Analysis.M3toCM3; height *= Analysis.MtoCM; vs *= Analysis.MtoCM; vr *= Analysis.MtoCM; } // english else { uwgt /= Analysis.FT3toIN3; height *= Analysis.FTtoIN; vs *= Analysis.FTtoIN; vr *= Analysis.FTtoIN; } } File testFile; String path; int num_analyses = 0; if(paramRigid) { num_analyses++; dataVect[RB][NOR] = new ArrayList<Double>(res.length - 1); dataVect[RB][INV] = new ArrayList<Double>(res.length - 1); dataVect[RB][AVG] = new ArrayList<Double>(res.length - 1); } if(paramDecoupled) { num_analyses++; dataVect[DC][NOR] = new ArrayList<Double>(res.length - 1); dataVect[DC][INV] = new ArrayList<Double>(res.length - 1); dataVect[DC][AVG] = new ArrayList<Double>(res.length - 1); } if(paramCoupled) { num_analyses++; dataVect[CP][NOR] = new ArrayList<Double>(res.length - 1); dataVect[CP][INV] = new ArrayList<Double>(res.length - 1); dataVect[CP][AVG] = new ArrayList<Double>(res.length - 1); } iscale = -1.0 * scale; pm.setMaximum(res.length * 2 * num_analyses); pm.update(0, "Initializing"); int j, k; Object[] row; int rowcount = 0; resultVec = new java.util.Vector<ResultThread>(res.length * 2 * ANALYSIS_TYPES); // 2 orientations per analysis NUM_CORES = Runtime.getRuntime().availableProcessors(); pool = Executors.newFixedThreadPool(NUM_CORES); ResultThread rt; int row_idx; long startTime = System.currentTimeMillis(); for(int i = 1; i < res.length && !pm.isCanceled(); i++) { row = new Object[tableCols[dyn][LEN]]; eq = res[i][0].toString(); row_idx = i - 1; record = res[i][1].toString(); row[0] = eq; row[1] = record; path = res[i][3].toString(); testFile = new File(path); if(!testFile.exists() || !testFile.canRead()) { row[2] = "File does not exist or is not readable"; row[3] = path; outputTableModel.addRow(row); rowcount++; continue; } dat = new DoubleList(path, 0, parent.Parameters.scaleOn.isSelected() ? paramScale : 1.0); if(dat.bad()) { row[2] = "Invalid data at point " + dat.badEntry(); row[3] = path; outputTableModel.addRow(row); rowcount++; continue; } num++; di = Double.parseDouble(res[i][2].toString()); if(parent.Parameters.scalePGA.isSelected()) { scale = paramScale / Double.parseDouble(res[i][4].toString()); iscale = -1.0 * scale; } ain = dat.getAsArray(); // do the actual analysis if(paramRigid) { rt = new ResultThread(eq, record, row_idx, rowcount, RB, NOR, ain, di, ca, scale, paramDualslope, thrust, scaleRB, pm); pool.execute(rt); resultVec.add(rt); rt = new ResultThread(eq, record, row_idx, rowcount, RB, INV, ain, di, ca, iscale, paramDualslope, thrust, scaleRB, pm); pool.execute(rt); resultVec.add(rt); } if(paramDecoupled) { // [i]scale is divided by Gcmss because the algorithm expects input data in Gs, but our input files are in cmss. this has nothing to do with, and is not affected by, the unit base being used (english or metric). rt = new ResultThread(eq, record, row_idx, rowcount, DC, NOR, ain, uwgt, height, vs, damp, refstrain, di, iscale / Analysis.Gcmss, g, vr, ca, dv3, pm); pool.execute(rt); resultVec.add(rt); rt = new ResultThread(eq, record, row_idx, rowcount, DC, INV, ain, uwgt, height, vs, damp, refstrain, di, scale / Analysis.Gcmss, g, vr, ca, dv3, pm); pool.execute(rt); resultVec.add(rt); } if(paramCoupled) { // [i]scale is divided by Gcmss because the algorithm expects input data in Gs, but our input files are in cmss. this has nothing to do with, and is not affected by, the unit base being used (english or metric). rt = new ResultThread(eq, record, row_idx, rowcount, CP, NOR, ain, uwgt, height, vs, damp, refstrain, di, iscale / Analysis.Gcmss, g, vr, ca, dv3, pm); pool.execute(rt); resultVec.add(rt); rt = new ResultThread(eq, record, row_idx, rowcount, CP, INV, ain, uwgt, height, vs, damp, refstrain, di, scale / Analysis.Gcmss, g, vr, ca, dv3, pm); pool.execute(rt); resultVec.add(rt); } outputTableModel.addRow(row); rowcount++; } pool.shutdown(); while(!pool.awaitTermination(1, TimeUnit.SECONDS)) { if(pm.isCanceled()) { pool.shutdownNow(); break; } } pm.update("Calculating results..."); ResultThread prt; int i_analysis; for(int i = 0; i < resultVec.size(); i++) { rt = resultVec.get(i); if(!rt.finished()) continue; rt.graphData.setKey(rt.eq + " - " + rt.record + " - " + ParametersPanel.stringRB + ", " + polarityName[NOR]); xys[rt.idx][rt.analysis][rt.orientation] = rt.graphData; total[rt.analysis][rt.orientation] += rt.result; i_analysis = 1 + rt.analysis * 2; for(j = 0; j < dataVect[rt.analysis][rt.orientation].size() && ((Double)dataVect[rt.analysis][rt.orientation].get(j)).doubleValue() < rt.result; j++) ; dataVect[rt.analysis][rt.orientation].add(j, new Double(rt.result)); outputTableModel.setValueAt(unitFmt.format(rt.result), rt.row, tableCols[dyn][i_analysis] + rt.orientation); // INV is always second, so NOR was already computed: we can compute avg now if(rt.orientation == INV) { prt = resultVec.get(i - 1); // NOR result avg = avg(rt.result, prt.result); total[rt.analysis][AVG] += avg; for(j = 0; j < dataVect[rt.analysis][AVG].size() && ((Double)dataVect[rt.analysis][AVG].get(j)).doubleValue() < avg; j++) ; dataVect[rt.analysis][AVG].add(j, new Double(avg)); outputTableModel.setValueAt(unitFmt.format(avg), rt.row, tableCols[dyn][i_analysis] + AVG); if(dyn == WITH_DYN && (rt.analysis == DC || rt.analysis == CP)) { outputTableModel.setValueAt(unitFmt.format(rt._kmax / g), rt.row, tableCols[dyn][I_DY] + 0); outputTableModel.setValueAt(unitFmt.format(rt._vs / Analysis.MtoCM), rt.row, tableCols[dyn][I_DY] + 1); outputTableModel.setValueAt(unitFmt.format(rt._damp), rt.row, tableCols[dyn][I_DY] + 2); } } } if(!pm.isCanceled()) { double mean, value, valtemp; int idx; Object[] rmean = new Object[tableCols[dyn][LEN]]; Object[] rmedian = new Object[tableCols[dyn][LEN]]; Object[] rsd = new Object[tableCols[dyn][LEN]]; rmean[1] = "Mean value"; rmedian[1] = "Median value"; rsd[1] = "Standard deviation"; for(j = 0; j < total.length; j++) { for(k = 0; k < total[j].length; k++) { if(dataVect[j][k] == null || dataVect[j][k].size() == 0) continue; idx = tableCols[dyn][1 + j * 2] + k; mean = Double.parseDouble(unitFmt.format(total[j][k] / num)); rmean[idx] = unitFmt.format(mean); if(num % 2 == 0) { double fst = (Double)dataVect[j][k].get(num / 2); double snd = (Double)dataVect[j][k].get(num / 2 - 1); rmedian[idx] = unitFmt.format(avg(fst, snd)); } else rmedian[idx] = unitFmt.format(dataVect[j][k].get(num / 2)); value = 0; for(int i = 0; i < num; i++) { valtemp = mean - ((Double)dataVect[j][k].get(i)).doubleValue(); value += (valtemp * valtemp); } value /= num; value = Math.sqrt(value); rsd[idx] = unitFmt.format(value); } } outputTableModel.addRow(new Object[0]); outputTableModel.addRow(rmean); outputTableModel.addRow(rmedian); outputTableModel.addRow(rsd); } } catch(Throwable ex) { Utils.catchException(ex); } return null; } public void finished() { pm.dispose(); } }; worker.start(); } else if(command.equals("clearOutput")) { clearOutput(); } else if(command.equals("saveResultsOutput")) { if(fc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) { FileWriter fw = new FileWriter(fc.getSelectedFile()); String delim; if(outputDelSpace.isSelected()) delim = " "; else if(outputDelComma.isSelected()) delim = ","; else delim = "\t"; int c = outputTableModel.getColumnCount(); int r = outputTableModel.getRowCount(); // table column headers for(int i = 0; i < c; i++) { if(i != 0) fw.write(delim); fw.write(outputTableModel.getColumnName(i).replaceAll("\\<.*?\\>", "")); } fw.write("\n"); Object o; for(int i = 0; i < r; i++) { for(int j = 0; j < c; j++) { if(j != 0) fw.write(delim); o = outputTableModel.getValueAt(i, j); if(o == null) o = ""; fw.write(o.toString()); } fw.write("\n"); } fw.close(); } } else if(command.equals("plotHistogram")) { if(dataVect == null) return; String name = "", title, pname; HistogramDataset dataset = new HistogramDataset(); int polarity, analysis = -1; if(polarityAvgHist.isSelected()) polarity = AVG; else if(polarityNorHist.isSelected()) polarity = NOR; else if(polarityInvHist.isSelected()) polarity = INV; else polarity = -1; for(int i = 0; i < analysisHist.length; i++) if(analysisHist[i].isSelected()) analysis = i; if(analysis == -1) return; pname = polarityName[polarity]; Double Bins = (Double)Utils.checkNum(outputBins.getText(), "output bins field", null, false, null, new Double(0), false, null, false); if(Bins == null || dataVect[analysis][polarity] == null) return; name = analysisTitle[analysis]; double series[] = new double[dataVect[analysis][polarity].size()]; for(int j = 0; j < dataVect[analysis][polarity].size(); j++) series[j] = (((Double)dataVect[analysis][polarity].get(j)).doubleValue()); dataset.addSeries(name, series, (int)Bins.doubleValue()); title = "Histogram of " + name + " Displacements (" + pname + " Polarity)"; JFreeChart hist = ChartFactory.createHistogram(title, "Displacement " + unitDisplacement, "Number of Records", dataset, org.jfree.chart.plot.PlotOrientation.VERTICAL, false, true, false); ChartFrame frame = new ChartFrame(title, hist); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } else if(command.equals("plotDisplacement")) { XYSeriesCollection xysc = new XYSeriesCollection(); int polarity = polarityNorDisp.isSelected() ? NOR : INV; String pname = polarityName[polarity]; String name = ""; boolean first = true; for(int i = 0; i < analysisDisp.length; i++) { if(analysisDisp[i].isSelected() && dataVect[i][polarity] != null) { if(first) first = false; else name += ", "; name += analysisTitle[i]; for(int j = 0; j < dataVect[i][polarity].size(); j++) xysc.addSeries(xys[j][i][polarity]); } } if(first) return; name += " Displacement versus Time"; JFreeChart chart = ChartFactory.createXYLineChart(name, "Time (s)", "Displacement--" + pname + " polarity " + unitDisplacement, xysc, org.jfree.chart.plot.PlotOrientation.VERTICAL, plotDisplacementLegend.isSelected(), true, false); //margins are stupid chart.getXYPlot().getDomainAxis().setLowerMargin(0); chart.getXYPlot().getDomainAxis().setUpperMargin(0); chart.getXYPlot().getDomainAxis().setLowerBound(0); ChartFrame frame = new ChartFrame(name, chart); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } } catch(Exception ex) { Utils.catchException(ex); } }
diff --git a/libraries/javalib/java/text/SimpleDateFormat.java b/libraries/javalib/java/text/SimpleDateFormat.java index afe07c107..5a69b0d07 100644 --- a/libraries/javalib/java/text/SimpleDateFormat.java +++ b/libraries/javalib/java/text/SimpleDateFormat.java @@ -1,1068 +1,1069 @@ /* SimpleDateFormat.java -- A class for parsing/formating simple date constructs Copyright (C) 1998, 1999, 2000, 2001, 2003, 2004 Free Software Foundation, Inc. This file is part of GNU Classpath. GNU Classpath 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, or (at your option) any later version. GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ package java.text; import gnu.java.text.AttributedFormatBuffer; import gnu.java.text.FormatBuffer; import gnu.java.text.FormatCharacterIterator; import gnu.java.text.StringFormatBuffer; import java.io.IOException; import java.io.ObjectInputStream; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Iterator; import java.util.Locale; import java.util.SimpleTimeZone; import java.util.TimeZone; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * SimpleDateFormat provides convenient methods for parsing and formatting * dates using Gregorian calendars (see java.util.GregorianCalendar). */ public class SimpleDateFormat extends DateFormat { /** * This class is used by <code>SimpleDateFormat</code> as a * compiled representation of a format string. The field * ID, size, and character used are stored for each sequence * of pattern characters or invalid characters in the format * pattern. */ private class CompiledField { /** * The ID of the field within the local pattern characters, * or -1 if the sequence is invalid. */ private int field; /** * The size of the character sequence. */ private int size; /** * The character used. */ private char character; /** * Constructs a compiled field using the * the given field ID, size and character * values. * * @param f the field ID. * @param s the size of the field. * @param c the character used. */ public CompiledField(int f, int s, char c) { field = f; size = s; character = c; } /** * Retrieves the ID of the field relative to * the local pattern characters, or -1 if * the sequence is invalid. */ public int getField() { return field; } /** * Retrieves the size of the character sequence. */ public int getSize() { return size; } /** * Retrieves the character used in the sequence. */ public char getCharacter() { return character; } /** * Returns a <code>String</code> representation * of the compiled field, primarily for debugging * purposes. * * @return a <code>String</code> representation. */ public String toString() { StringBuilder builder; builder = new StringBuilder(getClass().getName()); builder.append("[field="); builder.append(field); builder.append(", size="); builder.append(size); builder.append(", character="); builder.append(character); builder.append("]"); return builder.toString(); } } private transient ArrayList tokens; private DateFormatSymbols formatData; // formatData private Date defaultCenturyStart; private transient int defaultCentury; private String pattern; private int serialVersionOnStream = 1; // 0 indicates JDK1.1.3 or earlier private static final long serialVersionUID = 4774881970558875024L; // This string is specified in the root of the CLDR. We set it here // rather than doing a DateFormatSymbols(Locale.US).getLocalPatternChars() // since someone could theoretically change those values (though unlikely). private static final String standardChars = "GyMdkHmsSEDFwWahKzYeugAZ"; private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); if (serialVersionOnStream < 1) { computeCenturyStart (); serialVersionOnStream = 1; } else // Ensure that defaultCentury gets set. set2DigitYearStart(defaultCenturyStart); // Set up items normally taken care of by the constructor. tokens = new ArrayList(); compileFormat(pattern); } private void compileFormat(String pattern) { // Any alphabetical characters are treated as pattern characters // unless enclosed in single quotes. char thisChar; int pos; int field; CompiledField current = null; for (int i=0; i<pattern.length(); i++) { thisChar = pattern.charAt(i); field = formatData.getLocalPatternChars().indexOf(thisChar); if (field == -1) { current = null; if ((thisChar >= 'A' && thisChar <= 'Z') || (thisChar >= 'a' && thisChar <= 'z')) { // Not a valid letter tokens.add(new CompiledField(-1,0,thisChar)); } else if (thisChar == '\'') { // Quoted text section; skip to next single quote pos = pattern.indexOf('\'',i+1); if (pos == -1) { // This ought to be an exception, but spec does not // let us throw one. tokens.add(new CompiledField(-1,0,thisChar)); } if ((pos+1 < pattern.length()) && (pattern.charAt(pos+1) == '\'')) { tokens.add(pattern.substring(i+1,pos+1)); } else { tokens.add(pattern.substring(i+1,pos)); } i = pos; } else { // A special character tokens.add(new Character(thisChar)); } } else { // A valid field if ((current != null) && (field == current.field)) { current.size++; } else { current = new CompiledField(field,1,thisChar); tokens.add(current); } } } } public String toString() { StringBuffer output = new StringBuffer(); Iterator i = tokens.iterator(); while (i.hasNext()) { output.append(i.next().toString()); } return output.toString(); } /** * Constructs a SimpleDateFormat using the default pattern for * the default locale. */ public SimpleDateFormat() { /* * There does not appear to be a standard API for determining * what the default pattern for a locale is, so use package-scope * variables in DateFormatSymbols to encapsulate this. */ super(); Locale locale = Locale.getDefault(); calendar = new GregorianCalendar(locale); computeCenturyStart(); tokens = new ArrayList(); formatData = new DateFormatSymbols(locale); pattern = (formatData.dateFormats[DEFAULT] + ' ' + formatData.timeFormats[DEFAULT]); compileFormat(pattern); numberFormat = NumberFormat.getInstance(locale); numberFormat.setGroupingUsed (false); numberFormat.setParseIntegerOnly (true); numberFormat.setMaximumFractionDigits (0); } /** * Creates a date formatter using the specified pattern, with the default * DateFormatSymbols for the default locale. */ public SimpleDateFormat(String pattern) { this(pattern, Locale.getDefault()); } /** * Creates a date formatter using the specified pattern, with the default * DateFormatSymbols for the given locale. */ public SimpleDateFormat(String pattern, Locale locale) { super(); calendar = new GregorianCalendar(locale); computeCenturyStart(); tokens = new ArrayList(); formatData = new DateFormatSymbols(locale); compileFormat(pattern); this.pattern = pattern; numberFormat = NumberFormat.getInstance(locale); numberFormat.setGroupingUsed (false); numberFormat.setParseIntegerOnly (true); numberFormat.setMaximumFractionDigits (0); } /** * Creates a date formatter using the specified pattern. The * specified DateFormatSymbols will be used when formatting. */ public SimpleDateFormat(String pattern, DateFormatSymbols formatData) { super(); calendar = new GregorianCalendar(); computeCenturyStart (); tokens = new ArrayList(); this.formatData = formatData; compileFormat(pattern); this.pattern = pattern; numberFormat = NumberFormat.getInstance(); numberFormat.setGroupingUsed (false); numberFormat.setParseIntegerOnly (true); numberFormat.setMaximumFractionDigits (0); } // What is the difference between localized and unlocalized? The // docs don't say. /** * This method returns a string with the formatting pattern being used * by this object. This string is unlocalized. * * @return The format string. */ public String toPattern() { return pattern; } /** * This method returns a string with the formatting pattern being used * by this object. This string is localized. * * @return The format string. */ public String toLocalizedPattern() { String localChars = formatData.getLocalPatternChars(); return applyLocalizedPattern (pattern, standardChars, localChars); } /** * This method sets the formatting pattern that should be used by this * object. This string is not localized. * * @param pattern The new format pattern. */ public void applyPattern(String pattern) { tokens = new ArrayList(); compileFormat(pattern); this.pattern = pattern; } /** * This method sets the formatting pattern that should be used by this * object. This string is localized. * * @param pattern The new format pattern. */ public void applyLocalizedPattern(String pattern) { String localChars = formatData.getLocalPatternChars(); pattern = applyLocalizedPattern (pattern, localChars, standardChars); applyPattern(pattern); } private String applyLocalizedPattern(String pattern, String oldChars, String newChars) { int len = pattern.length(); StringBuffer buf = new StringBuffer(len); boolean quoted = false; for (int i = 0; i < len; i++) { char ch = pattern.charAt(i); if (ch == '\'') quoted = ! quoted; if (! quoted) { int j = oldChars.indexOf(ch); if (j >= 0) ch = newChars.charAt(j); } buf.append(ch); } return buf.toString(); } /** * Returns the start of the century used for two digit years. * * @return A <code>Date</code> representing the start of the century * for two digit years. */ public Date get2DigitYearStart() { return defaultCenturyStart; } /** * Sets the start of the century used for two digit years. * * @param date A <code>Date</code> representing the start of the century for * two digit years. */ public void set2DigitYearStart(Date date) { defaultCenturyStart = date; calendar.clear(); calendar.setTime(date); int year = calendar.get(Calendar.YEAR); defaultCentury = year - (year % 100); } /** * This method returns a copy of the format symbol information used * for parsing and formatting dates. * * @return a copy of the date format symbols. */ public DateFormatSymbols getDateFormatSymbols() { return (DateFormatSymbols) formatData.clone(); } /** * This method sets the format symbols information used for parsing * and formatting dates. * * @param formatData The date format symbols. * @throws NullPointerException if <code>formatData</code> is null. */ public void setDateFormatSymbols(DateFormatSymbols formatData) { if (formatData == null) { throw new NullPointerException("The supplied format data was null."); } this.formatData = formatData; } /** * This methods tests whether the specified object is equal to this * object. This will be true if and only if the specified object: * <p> * <ul> * <li>Is not <code>null</code>.</li> * <li>Is an instance of <code>SimpleDateFormat</code>.</li> * <li>Is equal to this object at the superclass (i.e., <code>DateFormat</code>) * level.</li> * <li>Has the same formatting pattern.</li> * <li>Is using the same formatting symbols.</li> * <li>Is using the same century for two digit years.</li> * </ul> * * @param obj The object to compare for equality against. * * @return <code>true</code> if the specified object is equal to this object, * <code>false</code> otherwise. */ public boolean equals(Object o) { if (!super.equals(o)) return false; if (!(o instanceof SimpleDateFormat)) return false; SimpleDateFormat sdf = (SimpleDateFormat)o; if (defaultCentury != sdf.defaultCentury) return false; if (!toPattern().equals(sdf.toPattern())) return false; if (!getDateFormatSymbols().equals(sdf.getDateFormatSymbols())) return false; return true; } /** * This method returns a hash value for this object. * * @return A hash value for this object. */ public int hashCode() { return super.hashCode() ^ toPattern().hashCode() ^ defaultCentury ^ getDateFormatSymbols().hashCode(); } /** * Formats the date input according to the format string in use, * appending to the specified StringBuffer. The input StringBuffer * is returned as output for convenience. */ private void formatWithAttribute(Date date, FormatBuffer buffer, FieldPosition pos) { String temp; AttributedCharacterIterator.Attribute attribute; calendar.setTime(date); // go through vector, filling in fields where applicable, else toString Iterator iter = tokens.iterator(); while (iter.hasNext()) { Object o = iter.next(); if (o instanceof CompiledField) { CompiledField cf = (CompiledField) o; int beginIndex = buffer.length(); switch (cf.getField()) { case ERA_FIELD: buffer.append (formatData.eras[calendar.get (Calendar.ERA)], DateFormat.Field.ERA); break; case YEAR_FIELD: // If we have two digits, then we truncate. Otherwise, we // use the size of the pattern, and zero pad. buffer.setDefaultAttribute (DateFormat.Field.YEAR); if (cf.getSize() == 2) { temp = String.valueOf (calendar.get (Calendar.YEAR)); buffer.append (temp.substring (temp.length() - 2)); } else withLeadingZeros (calendar.get (Calendar.YEAR), cf.getSize(), buffer); break; case MONTH_FIELD: buffer.setDefaultAttribute (DateFormat.Field.MONTH); if (cf.getSize() < 3) withLeadingZeros (calendar.get (Calendar.MONTH) + 1, cf.getSize(), buffer); else if (cf.getSize() < 4) buffer.append (formatData.shortMonths[calendar.get (Calendar.MONTH)]); else buffer.append (formatData.months[calendar.get (Calendar.MONTH)]); break; case DATE_FIELD: buffer.setDefaultAttribute (DateFormat.Field.DAY_OF_MONTH); withLeadingZeros (calendar.get (Calendar.DATE), cf.getSize(), buffer); break; case HOUR_OF_DAY1_FIELD: // 1-24 buffer.setDefaultAttribute(DateFormat.Field.HOUR_OF_DAY1); withLeadingZeros ( ((calendar.get (Calendar.HOUR_OF_DAY) + 23) % 24) + 1, cf.getSize(), buffer); break; case HOUR_OF_DAY0_FIELD: // 0-23 buffer.setDefaultAttribute (DateFormat.Field.HOUR_OF_DAY0); withLeadingZeros (calendar.get (Calendar.HOUR_OF_DAY), cf.getSize(), buffer); break; case MINUTE_FIELD: buffer.setDefaultAttribute (DateFormat.Field.MINUTE); withLeadingZeros (calendar.get (Calendar.MINUTE), cf.getSize(), buffer); break; case SECOND_FIELD: buffer.setDefaultAttribute (DateFormat.Field.SECOND); withLeadingZeros(calendar.get (Calendar.SECOND), cf.getSize(), buffer); break; case MILLISECOND_FIELD: buffer.setDefaultAttribute (DateFormat.Field.MILLISECOND); withLeadingZeros (calendar.get (Calendar.MILLISECOND), cf.getSize(), buffer); break; case DAY_OF_WEEK_FIELD: buffer.setDefaultAttribute (DateFormat.Field.DAY_OF_WEEK); if (cf.getSize() < 4) buffer.append (formatData.shortWeekdays[calendar.get (Calendar.DAY_OF_WEEK)]); else buffer.append (formatData.weekdays[calendar.get (Calendar.DAY_OF_WEEK)]); break; case DAY_OF_YEAR_FIELD: buffer.setDefaultAttribute (DateFormat.Field.DAY_OF_YEAR); withLeadingZeros (calendar.get (Calendar.DAY_OF_YEAR), cf.getSize(), buffer); break; case DAY_OF_WEEK_IN_MONTH_FIELD: buffer.setDefaultAttribute (DateFormat.Field.DAY_OF_WEEK_IN_MONTH); withLeadingZeros (calendar.get (Calendar.DAY_OF_WEEK_IN_MONTH), cf.getSize(), buffer); break; case WEEK_OF_YEAR_FIELD: buffer.setDefaultAttribute (DateFormat.Field.WEEK_OF_YEAR); withLeadingZeros (calendar.get (Calendar.WEEK_OF_YEAR), cf.getSize(), buffer); break; case WEEK_OF_MONTH_FIELD: buffer.setDefaultAttribute (DateFormat.Field.WEEK_OF_MONTH); withLeadingZeros (calendar.get (Calendar.WEEK_OF_MONTH), cf.getSize(), buffer); break; case AM_PM_FIELD: buffer.setDefaultAttribute (DateFormat.Field.AM_PM); buffer.append (formatData.ampms[calendar.get (Calendar.AM_PM)]); break; case HOUR1_FIELD: // 1-12 buffer.setDefaultAttribute (DateFormat.Field.HOUR1); withLeadingZeros (((calendar.get (Calendar.HOUR) + 11) % 12) + 1, cf.getSize(), buffer); break; case HOUR0_FIELD: // 0-11 buffer.setDefaultAttribute (DateFormat.Field.HOUR0); withLeadingZeros (calendar.get (Calendar.HOUR), cf.getSize(), buffer); break; case TIMEZONE_FIELD: buffer.setDefaultAttribute (DateFormat.Field.TIME_ZONE); TimeZone zone = calendar.getTimeZone(); boolean isDST = calendar.get (Calendar.DST_OFFSET) != 0; // FIXME: XXX: This should be a localized time zone. String zoneID = zone.getDisplayName (isDST, cf.getSize() > 3 ? TimeZone.LONG : TimeZone.SHORT); buffer.append (zoneID); break; case RFC822_TIMEZONE_FIELD: buffer.setDefaultAttribute(DateFormat.Field.RFC822_TIME_ZONE); int pureMinutes = (calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET)) / (1000 * 60); String sign = (pureMinutes < 0) ? "-" : "+"; int hours = pureMinutes / 60; int minutes = pureMinutes % 60; buffer.append(sign); withLeadingZeros(hours, 2, buffer); withLeadingZeros(minutes, 2, buffer); break; default: throw new IllegalArgumentException ("Illegal pattern character " + cf.getCharacter()); } if (pos != null && (buffer.getDefaultAttribute() == pos.getFieldAttribute() || cf.getField() == pos.getField())) { pos.setBeginIndex(beginIndex); pos.setEndIndex(buffer.length()); } } else { buffer.append(o.toString(), null); } } } public StringBuffer format(Date date, StringBuffer buffer, FieldPosition pos) { formatWithAttribute(date, new StringFormatBuffer (buffer), pos); return buffer; } public AttributedCharacterIterator formatToCharacterIterator(Object date) throws IllegalArgumentException { if (date == null) throw new NullPointerException("null argument"); if (!(date instanceof Date)) throw new IllegalArgumentException("argument should be an instance of java.util.Date"); AttributedFormatBuffer buf = new AttributedFormatBuffer(); formatWithAttribute((Date)date, buf, null); buf.sync(); return new FormatCharacterIterator(buf.getBuffer().toString(), buf.getRanges(), buf.getAttributes()); } private void withLeadingZeros(int value, int length, FormatBuffer buffer) { String valStr = String.valueOf(value); for (length -= valStr.length(); length > 0; length--) buffer.append('0'); buffer.append(valStr); } private boolean expect(String source, ParsePosition pos, char ch) { int x = pos.getIndex(); boolean r = x < source.length() && source.charAt(x) == ch; if (r) pos.setIndex(x + 1); else pos.setErrorIndex(x); return r; } /** * This method parses the specified string into a date. * * @param dateStr The date string to parse. * @param pos The input and output parse position * * @return The parsed date, or <code>null</code> if the string cannot be * parsed. */ public Date parse (String dateStr, ParsePosition pos) { int fmt_index = 0; int fmt_max = pattern.length(); calendar.clear(); boolean saw_timezone = false; int quote_start = -1; boolean is2DigitYear = false; try { for (; fmt_index < fmt_max; ++fmt_index) { char ch = pattern.charAt(fmt_index); if (ch == '\'') { int index = pos.getIndex(); if (fmt_index < fmt_max - 1 && pattern.charAt(fmt_index + 1) == '\'') { if (! expect (dateStr, pos, ch)) return null; ++fmt_index; } else quote_start = quote_start < 0 ? fmt_index : -1; continue; } if (quote_start != -1 || ((ch < 'a' || ch > 'z') && (ch < 'A' || ch > 'Z'))) { if (! expect (dateStr, pos, ch)) return null; continue; } // We've arrived at a potential pattern character in the // pattern. int fmt_count = 1; while (++fmt_index < fmt_max && pattern.charAt(fmt_index) == ch) { ++fmt_count; } // We might need to limit the number of digits to parse in // some cases. We look to the next pattern character to // decide. boolean limit_digits = false; if (fmt_index < fmt_max && standardChars.indexOf(pattern.charAt(fmt_index)) >= 0) limit_digits = true; --fmt_index; // We can handle most fields automatically: most either are // numeric or are looked up in a string vector. In some cases // we need an offset. When numeric, `offset' is added to the // resulting value. When doing a string lookup, offset is the // initial index into the string array. int calendar_field; boolean is_numeric = true; int offset = 0; boolean maybe2DigitYear = false; Integer simpleOffset; String[] set1 = null; String[] set2 = null; switch (ch) { case 'd': calendar_field = Calendar.DATE; break; case 'D': calendar_field = Calendar.DAY_OF_YEAR; break; case 'F': calendar_field = Calendar.DAY_OF_WEEK_IN_MONTH; break; case 'E': is_numeric = false; offset = 1; calendar_field = Calendar.DAY_OF_WEEK; set1 = formatData.getWeekdays(); set2 = formatData.getShortWeekdays(); break; case 'w': calendar_field = Calendar.WEEK_OF_YEAR; break; case 'W': calendar_field = Calendar.WEEK_OF_MONTH; break; case 'M': calendar_field = Calendar.MONTH; if (fmt_count <= 2) offset = -1; else { is_numeric = false; set1 = formatData.getMonths(); set2 = formatData.getShortMonths(); } break; case 'y': calendar_field = Calendar.YEAR; if (fmt_count <= 2) maybe2DigitYear = true; break; case 'K': calendar_field = Calendar.HOUR; break; case 'h': calendar_field = Calendar.HOUR; break; case 'H': calendar_field = Calendar.HOUR_OF_DAY; break; case 'k': calendar_field = Calendar.HOUR_OF_DAY; break; case 'm': calendar_field = Calendar.MINUTE; break; case 's': calendar_field = Calendar.SECOND; break; case 'S': calendar_field = Calendar.MILLISECOND; break; case 'a': is_numeric = false; calendar_field = Calendar.AM_PM; set1 = formatData.getAmPmStrings(); break; case 'z': case 'Z': // We need a special case for the timezone, because it // uses a different data structure than the other cases. is_numeric = false; calendar_field = Calendar.ZONE_OFFSET; String[][] zoneStrings = formatData.getZoneStrings(); int zoneCount = zoneStrings.length; int index = pos.getIndex(); boolean found_zone = false; simpleOffset = computeOffset(dateStr.substring(index)); if (simpleOffset != null) { found_zone = true; saw_timezone = true; + calendar.set(Calendar.DST_OFFSET, 0); offset = simpleOffset.intValue(); } else { for (int j = 0; j < zoneCount; j++) { String[] strings = zoneStrings[j]; int k; for (k = 0; k < strings.length; ++k) { if (dateStr.startsWith(strings[k], index)) break; } if (k != strings.length) { found_zone = true; saw_timezone = true; TimeZone tz = TimeZone.getTimeZone (strings[0]); calendar.set (Calendar.DST_OFFSET, tz.getDSTSavings()); offset = tz.getRawOffset (); pos.setIndex(index + strings[k].length()); break; } } } if (! found_zone) { pos.setErrorIndex(pos.getIndex()); return null; } break; default: pos.setErrorIndex(pos.getIndex()); return null; } // Compute the value we should assign to the field. int value; int index = -1; if (is_numeric) { numberFormat.setMinimumIntegerDigits(fmt_count); if (limit_digits) numberFormat.setMaximumIntegerDigits(fmt_count); if (maybe2DigitYear) index = pos.getIndex(); Number n = numberFormat.parse(dateStr, pos); if (pos == null || ! (n instanceof Long)) return null; value = n.intValue() + offset; } else if (set1 != null) { index = pos.getIndex(); int i; boolean found = false; for (i = offset; i < set1.length; ++i) { if (set1[i] != null) if (dateStr.toUpperCase().startsWith(set1[i].toUpperCase(), index)) { found = true; pos.setIndex(index + set1[i].length()); break; } } if (!found && set2 != null) { for (i = offset; i < set2.length; ++i) { if (set2[i] != null) if (dateStr.toUpperCase().startsWith(set2[i].toUpperCase(), index)) { found = true; pos.setIndex(index + set2[i].length()); break; } } } if (!found) { pos.setErrorIndex(index); return null; } value = i; } else value = offset; if (maybe2DigitYear) { // Parse into default century if the numeric year string has // exactly 2 digits. int digit_count = pos.getIndex() - index; if (digit_count == 2) is2DigitYear = true; } // Assign the value and move on. calendar.set(calendar_field, value); } if (is2DigitYear) { // Apply the 80-20 heuristic to dermine the full year based on // defaultCenturyStart. int year = defaultCentury + calendar.get(Calendar.YEAR); calendar.set(Calendar.YEAR, year); if (calendar.getTime().compareTo(defaultCenturyStart) < 0) calendar.set(Calendar.YEAR, year + 100); } if (! saw_timezone) { // Use the real rules to determine whether or not this // particular time is in daylight savings. calendar.clear (Calendar.DST_OFFSET); calendar.clear (Calendar.ZONE_OFFSET); } return calendar.getTime(); } catch (IllegalArgumentException x) { pos.setErrorIndex(pos.getIndex()); return null; } } /** * <p> * Computes the time zone offset in milliseconds * relative to GMT, based on the supplied * <code>String</code> representation. * </p> * <p> * The supplied <code>String</code> must be a three * or four digit signed number, with an optional 'GMT' * prefix. The first one or two digits represents the hours, * while the last two represent the minutes. The * two sets of digits can optionally be separated by * ':'. The mandatory sign prefix (either '+' or '-') * indicates the direction of the offset from GMT. * </p> * <p> * For example, 'GMT+0200' specifies 2 hours after * GMT, while '-05:00' specifies 5 hours prior to * GMT. The special case of 'GMT' alone can be used * to represent the offset, 0. * </p> * <p> * If the <code>String</code> can not be parsed, * the result will be null. The resulting offset * is wrapped in an <code>Integer</code> object, in * order to allow such failure to be represented. * </p> * * @param zoneString a string in the form * (GMT)? sign hours : minutes * where sign = '+' or '-', hours * is a one or two digits representing * a number between 0 and 23, and * minutes is two digits representing * a number between 0 and 59. * @return the parsed offset, or null if parsing * failed. */ private Integer computeOffset(String zoneString) { Pattern pattern = Pattern.compile("(GMT)?([+-])([012])?([0-9]):?([0-9]{2})"); Matcher matcher = pattern.matcher(zoneString); if (matcher.matches()) { int sign = matcher.group(2).equals("+") ? 1 : -1; int hour = (Integer.parseInt(matcher.group(3)) * 10) + Integer.parseInt(matcher.group(4)); int minutes = Integer.parseInt(matcher.group(5)); if (hour > 23) return null; int offset = sign * ((hour * 60) + minutes) * 60000; return new Integer(offset); } else if (zoneString.startsWith("GMT")) { return new Integer(0); } return null; } // Compute the start of the current century as defined by // get2DigitYearStart. private void computeCenturyStart() { int year = calendar.get(Calendar.YEAR); calendar.set(Calendar.YEAR, year - 80); set2DigitYearStart(calendar.getTime()); } /** * Returns a copy of this instance of * <code>SimpleDateFormat</code>. The copy contains * clones of the formatting symbols and the 2-digit * year century start date. */ public Object clone() { SimpleDateFormat clone = (SimpleDateFormat) super.clone(); clone.setDateFormatSymbols((DateFormatSymbols) formatData.clone()); clone.set2DigitYearStart((Date) defaultCenturyStart.clone()); return clone; } }
true
true
public Date parse (String dateStr, ParsePosition pos) { int fmt_index = 0; int fmt_max = pattern.length(); calendar.clear(); boolean saw_timezone = false; int quote_start = -1; boolean is2DigitYear = false; try { for (; fmt_index < fmt_max; ++fmt_index) { char ch = pattern.charAt(fmt_index); if (ch == '\'') { int index = pos.getIndex(); if (fmt_index < fmt_max - 1 && pattern.charAt(fmt_index + 1) == '\'') { if (! expect (dateStr, pos, ch)) return null; ++fmt_index; } else quote_start = quote_start < 0 ? fmt_index : -1; continue; } if (quote_start != -1 || ((ch < 'a' || ch > 'z') && (ch < 'A' || ch > 'Z'))) { if (! expect (dateStr, pos, ch)) return null; continue; } // We've arrived at a potential pattern character in the // pattern. int fmt_count = 1; while (++fmt_index < fmt_max && pattern.charAt(fmt_index) == ch) { ++fmt_count; } // We might need to limit the number of digits to parse in // some cases. We look to the next pattern character to // decide. boolean limit_digits = false; if (fmt_index < fmt_max && standardChars.indexOf(pattern.charAt(fmt_index)) >= 0) limit_digits = true; --fmt_index; // We can handle most fields automatically: most either are // numeric or are looked up in a string vector. In some cases // we need an offset. When numeric, `offset' is added to the // resulting value. When doing a string lookup, offset is the // initial index into the string array. int calendar_field; boolean is_numeric = true; int offset = 0; boolean maybe2DigitYear = false; Integer simpleOffset; String[] set1 = null; String[] set2 = null; switch (ch) { case 'd': calendar_field = Calendar.DATE; break; case 'D': calendar_field = Calendar.DAY_OF_YEAR; break; case 'F': calendar_field = Calendar.DAY_OF_WEEK_IN_MONTH; break; case 'E': is_numeric = false; offset = 1; calendar_field = Calendar.DAY_OF_WEEK; set1 = formatData.getWeekdays(); set2 = formatData.getShortWeekdays(); break; case 'w': calendar_field = Calendar.WEEK_OF_YEAR; break; case 'W': calendar_field = Calendar.WEEK_OF_MONTH; break; case 'M': calendar_field = Calendar.MONTH; if (fmt_count <= 2) offset = -1; else { is_numeric = false; set1 = formatData.getMonths(); set2 = formatData.getShortMonths(); } break; case 'y': calendar_field = Calendar.YEAR; if (fmt_count <= 2) maybe2DigitYear = true; break; case 'K': calendar_field = Calendar.HOUR; break; case 'h': calendar_field = Calendar.HOUR; break; case 'H': calendar_field = Calendar.HOUR_OF_DAY; break; case 'k': calendar_field = Calendar.HOUR_OF_DAY; break; case 'm': calendar_field = Calendar.MINUTE; break; case 's': calendar_field = Calendar.SECOND; break; case 'S': calendar_field = Calendar.MILLISECOND; break; case 'a': is_numeric = false; calendar_field = Calendar.AM_PM; set1 = formatData.getAmPmStrings(); break; case 'z': case 'Z': // We need a special case for the timezone, because it // uses a different data structure than the other cases. is_numeric = false; calendar_field = Calendar.ZONE_OFFSET; String[][] zoneStrings = formatData.getZoneStrings(); int zoneCount = zoneStrings.length; int index = pos.getIndex(); boolean found_zone = false; simpleOffset = computeOffset(dateStr.substring(index)); if (simpleOffset != null) { found_zone = true; saw_timezone = true; offset = simpleOffset.intValue(); } else { for (int j = 0; j < zoneCount; j++) { String[] strings = zoneStrings[j]; int k; for (k = 0; k < strings.length; ++k) { if (dateStr.startsWith(strings[k], index)) break; } if (k != strings.length) { found_zone = true; saw_timezone = true; TimeZone tz = TimeZone.getTimeZone (strings[0]); calendar.set (Calendar.DST_OFFSET, tz.getDSTSavings()); offset = tz.getRawOffset (); pos.setIndex(index + strings[k].length()); break; } } } if (! found_zone) { pos.setErrorIndex(pos.getIndex()); return null; } break; default: pos.setErrorIndex(pos.getIndex()); return null; } // Compute the value we should assign to the field. int value; int index = -1; if (is_numeric) { numberFormat.setMinimumIntegerDigits(fmt_count); if (limit_digits) numberFormat.setMaximumIntegerDigits(fmt_count); if (maybe2DigitYear) index = pos.getIndex(); Number n = numberFormat.parse(dateStr, pos); if (pos == null || ! (n instanceof Long)) return null; value = n.intValue() + offset; } else if (set1 != null) { index = pos.getIndex(); int i; boolean found = false; for (i = offset; i < set1.length; ++i) { if (set1[i] != null) if (dateStr.toUpperCase().startsWith(set1[i].toUpperCase(), index)) { found = true; pos.setIndex(index + set1[i].length()); break; } } if (!found && set2 != null) { for (i = offset; i < set2.length; ++i) { if (set2[i] != null) if (dateStr.toUpperCase().startsWith(set2[i].toUpperCase(), index)) { found = true; pos.setIndex(index + set2[i].length()); break; } } } if (!found) { pos.setErrorIndex(index); return null; } value = i; } else value = offset; if (maybe2DigitYear) { // Parse into default century if the numeric year string has // exactly 2 digits. int digit_count = pos.getIndex() - index; if (digit_count == 2) is2DigitYear = true; } // Assign the value and move on. calendar.set(calendar_field, value); } if (is2DigitYear) { // Apply the 80-20 heuristic to dermine the full year based on // defaultCenturyStart. int year = defaultCentury + calendar.get(Calendar.YEAR); calendar.set(Calendar.YEAR, year); if (calendar.getTime().compareTo(defaultCenturyStart) < 0) calendar.set(Calendar.YEAR, year + 100); } if (! saw_timezone) { // Use the real rules to determine whether or not this // particular time is in daylight savings. calendar.clear (Calendar.DST_OFFSET); calendar.clear (Calendar.ZONE_OFFSET); } return calendar.getTime(); } catch (IllegalArgumentException x) { pos.setErrorIndex(pos.getIndex()); return null; } }
public Date parse (String dateStr, ParsePosition pos) { int fmt_index = 0; int fmt_max = pattern.length(); calendar.clear(); boolean saw_timezone = false; int quote_start = -1; boolean is2DigitYear = false; try { for (; fmt_index < fmt_max; ++fmt_index) { char ch = pattern.charAt(fmt_index); if (ch == '\'') { int index = pos.getIndex(); if (fmt_index < fmt_max - 1 && pattern.charAt(fmt_index + 1) == '\'') { if (! expect (dateStr, pos, ch)) return null; ++fmt_index; } else quote_start = quote_start < 0 ? fmt_index : -1; continue; } if (quote_start != -1 || ((ch < 'a' || ch > 'z') && (ch < 'A' || ch > 'Z'))) { if (! expect (dateStr, pos, ch)) return null; continue; } // We've arrived at a potential pattern character in the // pattern. int fmt_count = 1; while (++fmt_index < fmt_max && pattern.charAt(fmt_index) == ch) { ++fmt_count; } // We might need to limit the number of digits to parse in // some cases. We look to the next pattern character to // decide. boolean limit_digits = false; if (fmt_index < fmt_max && standardChars.indexOf(pattern.charAt(fmt_index)) >= 0) limit_digits = true; --fmt_index; // We can handle most fields automatically: most either are // numeric or are looked up in a string vector. In some cases // we need an offset. When numeric, `offset' is added to the // resulting value. When doing a string lookup, offset is the // initial index into the string array. int calendar_field; boolean is_numeric = true; int offset = 0; boolean maybe2DigitYear = false; Integer simpleOffset; String[] set1 = null; String[] set2 = null; switch (ch) { case 'd': calendar_field = Calendar.DATE; break; case 'D': calendar_field = Calendar.DAY_OF_YEAR; break; case 'F': calendar_field = Calendar.DAY_OF_WEEK_IN_MONTH; break; case 'E': is_numeric = false; offset = 1; calendar_field = Calendar.DAY_OF_WEEK; set1 = formatData.getWeekdays(); set2 = formatData.getShortWeekdays(); break; case 'w': calendar_field = Calendar.WEEK_OF_YEAR; break; case 'W': calendar_field = Calendar.WEEK_OF_MONTH; break; case 'M': calendar_field = Calendar.MONTH; if (fmt_count <= 2) offset = -1; else { is_numeric = false; set1 = formatData.getMonths(); set2 = formatData.getShortMonths(); } break; case 'y': calendar_field = Calendar.YEAR; if (fmt_count <= 2) maybe2DigitYear = true; break; case 'K': calendar_field = Calendar.HOUR; break; case 'h': calendar_field = Calendar.HOUR; break; case 'H': calendar_field = Calendar.HOUR_OF_DAY; break; case 'k': calendar_field = Calendar.HOUR_OF_DAY; break; case 'm': calendar_field = Calendar.MINUTE; break; case 's': calendar_field = Calendar.SECOND; break; case 'S': calendar_field = Calendar.MILLISECOND; break; case 'a': is_numeric = false; calendar_field = Calendar.AM_PM; set1 = formatData.getAmPmStrings(); break; case 'z': case 'Z': // We need a special case for the timezone, because it // uses a different data structure than the other cases. is_numeric = false; calendar_field = Calendar.ZONE_OFFSET; String[][] zoneStrings = formatData.getZoneStrings(); int zoneCount = zoneStrings.length; int index = pos.getIndex(); boolean found_zone = false; simpleOffset = computeOffset(dateStr.substring(index)); if (simpleOffset != null) { found_zone = true; saw_timezone = true; calendar.set(Calendar.DST_OFFSET, 0); offset = simpleOffset.intValue(); } else { for (int j = 0; j < zoneCount; j++) { String[] strings = zoneStrings[j]; int k; for (k = 0; k < strings.length; ++k) { if (dateStr.startsWith(strings[k], index)) break; } if (k != strings.length) { found_zone = true; saw_timezone = true; TimeZone tz = TimeZone.getTimeZone (strings[0]); calendar.set (Calendar.DST_OFFSET, tz.getDSTSavings()); offset = tz.getRawOffset (); pos.setIndex(index + strings[k].length()); break; } } } if (! found_zone) { pos.setErrorIndex(pos.getIndex()); return null; } break; default: pos.setErrorIndex(pos.getIndex()); return null; } // Compute the value we should assign to the field. int value; int index = -1; if (is_numeric) { numberFormat.setMinimumIntegerDigits(fmt_count); if (limit_digits) numberFormat.setMaximumIntegerDigits(fmt_count); if (maybe2DigitYear) index = pos.getIndex(); Number n = numberFormat.parse(dateStr, pos); if (pos == null || ! (n instanceof Long)) return null; value = n.intValue() + offset; } else if (set1 != null) { index = pos.getIndex(); int i; boolean found = false; for (i = offset; i < set1.length; ++i) { if (set1[i] != null) if (dateStr.toUpperCase().startsWith(set1[i].toUpperCase(), index)) { found = true; pos.setIndex(index + set1[i].length()); break; } } if (!found && set2 != null) { for (i = offset; i < set2.length; ++i) { if (set2[i] != null) if (dateStr.toUpperCase().startsWith(set2[i].toUpperCase(), index)) { found = true; pos.setIndex(index + set2[i].length()); break; } } } if (!found) { pos.setErrorIndex(index); return null; } value = i; } else value = offset; if (maybe2DigitYear) { // Parse into default century if the numeric year string has // exactly 2 digits. int digit_count = pos.getIndex() - index; if (digit_count == 2) is2DigitYear = true; } // Assign the value and move on. calendar.set(calendar_field, value); } if (is2DigitYear) { // Apply the 80-20 heuristic to dermine the full year based on // defaultCenturyStart. int year = defaultCentury + calendar.get(Calendar.YEAR); calendar.set(Calendar.YEAR, year); if (calendar.getTime().compareTo(defaultCenturyStart) < 0) calendar.set(Calendar.YEAR, year + 100); } if (! saw_timezone) { // Use the real rules to determine whether or not this // particular time is in daylight savings. calendar.clear (Calendar.DST_OFFSET); calendar.clear (Calendar.ZONE_OFFSET); } return calendar.getTime(); } catch (IllegalArgumentException x) { pos.setErrorIndex(pos.getIndex()); return null; } }
diff --git a/src/jrds/Period.java b/src/jrds/Period.java index 726fc33d..4b251e30 100644 --- a/src/jrds/Period.java +++ b/src/jrds/Period.java @@ -1,167 +1,170 @@ /*########################################################################## _## _## $Id$ _## _##########################################################################*/ package jrds; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.regex.Pattern; import org.apache.log4j.Logger; /** * This class manage a thread that runs in the background and is used to commit to disk the RRD datas modifications. * * @author Fabrice Bacchella * @version $Revision$ */ public class Period { static final private Logger logger = Logger.getLogger(Period.class); static private final DateFormat df = new SimpleDateFormat("yyyy-MM-dd:HH:mm"); static private final Pattern datePattern = Pattern.compile("\\d\\d\\d\\d-\\d\\d-\\d\\d"); private Date begin = null; private Date end = null; private int calPeriod = 7; private static class PeriodItem { String name; int length; int unit; int number; PeriodItem(String name, int unit, int number) { this.name = name; this.unit = unit; this.number = number; } Date getBegin(Date end) { Calendar calBegin = Calendar.getInstance(); calBegin.setTime(end); calBegin.add(unit, number); return calBegin.getTime(); } } static final private List<Period.PeriodItem> periodList = new ArrayList<Period.PeriodItem>(18); static { periodList.add(new Period.PeriodItem("Manual", Calendar.HOUR, -1)); periodList.add(new Period.PeriodItem("Last Hour", Calendar.HOUR, -1)); periodList.add(new Period.PeriodItem("Last 2 Hours", Calendar.HOUR, -2)); periodList.add(new Period.PeriodItem("Last 3 Hours", Calendar.HOUR, -3)); periodList.add(new Period.PeriodItem("Last 4 Hours", Calendar.HOUR, -4)); periodList.add(new Period.PeriodItem("Last 6 Hours", Calendar.HOUR, -6)); periodList.add(new Period.PeriodItem("Last 12 Hours", Calendar.HOUR, -12)); periodList.add(new Period.PeriodItem("Last Day", Calendar.DAY_OF_MONTH, -1)); periodList.add(new Period.PeriodItem("Last 2 Days", Calendar.DAY_OF_MONTH, -2)); periodList.add(new Period.PeriodItem("Last Week", Calendar.WEEK_OF_MONTH, -1)); periodList.add(new Period.PeriodItem("Last 2 Weeks", Calendar.WEEK_OF_MONTH, -2)); periodList.add(new Period.PeriodItem("Last Month", Calendar.MONTH, -1)); periodList.add(new Period.PeriodItem("Last 2 Months", Calendar.MONTH, -2)); periodList.add(new Period.PeriodItem("Last 3 Months", Calendar.MONTH, -3)); periodList.add(new Period.PeriodItem("Last 4 Months", Calendar.MONTH, -4)); periodList.add(new Period.PeriodItem("Last 6 Months", Calendar.MONTH, -6)); periodList.add(new Period.PeriodItem("Last Year", Calendar.YEAR, -1)); periodList.add(new Period.PeriodItem("Last 2 Years", Calendar.YEAR, -2)); } public Period() { } public Period(int p) { calPeriod = p; end = new Date(); } public Period(String begin, String end) { setBegin(begin); setEnd(end); } /** * @return Returns the begin. */ public Date getBegin() { if(begin == null && end != null) { if(calPeriod > periodList.size()) { logger.info("Period invalid: " + calPeriod); calPeriod = periodList.size(); } PeriodItem pi = (PeriodItem) periodList.get(calPeriod); begin = pi.getBegin(end); } return begin; } /** * @param begin The begin to set. */ public void setBegin(String begin) { this.begin = string2Date(begin, "00:00"); } /** * @return Returns the end. */ public Date getEnd() { return end; } /** * @param end The end to set. */ public void setEnd(String end) { this.end = string2Date(end, "23:59"); if(this.end == null) this.end = new Date(); } public void setScale(int scale) { calPeriod = scale; end = new Date(); begin = null; } /** * Calculate date from string parametrs comming from the URL * * @param sbegin String * @param send String * @param begin The calculated begin date * @param end The calculated end date */ private Date string2Date(String date, String hour){ Date foundDate = null; if("NOW".compareToIgnoreCase(date) == 0) { foundDate = new Date(); } else if(datePattern.matcher(date).matches()) { try { foundDate = df.parse(date + ":" + hour); } catch (ParseException e) { logger.error("Illegal date argument: " + e); } + catch (NumberFormatException e) { + logger.error("Illegal date argument: " + e); + } } if(foundDate == null) { try { long value = Long.parseLong(date); if(value == 0) foundDate = new Date(); else if(value > 0) foundDate = new Date(value); else calPeriod = (int) value; } catch (NumberFormatException ex) {} } return foundDate; } static public List<String> getPeriodNames() { List<String> periodName = new ArrayList<String>(periodList.size()); for(Period.PeriodItem pi: periodList) periodName.add(pi.name); return periodName; } }
true
true
private Date string2Date(String date, String hour){ Date foundDate = null; if("NOW".compareToIgnoreCase(date) == 0) { foundDate = new Date(); } else if(datePattern.matcher(date).matches()) { try { foundDate = df.parse(date + ":" + hour); } catch (ParseException e) { logger.error("Illegal date argument: " + e); } } if(foundDate == null) { try { long value = Long.parseLong(date); if(value == 0) foundDate = new Date(); else if(value > 0) foundDate = new Date(value); else calPeriod = (int) value; } catch (NumberFormatException ex) {} } return foundDate; }
private Date string2Date(String date, String hour){ Date foundDate = null; if("NOW".compareToIgnoreCase(date) == 0) { foundDate = new Date(); } else if(datePattern.matcher(date).matches()) { try { foundDate = df.parse(date + ":" + hour); } catch (ParseException e) { logger.error("Illegal date argument: " + e); } catch (NumberFormatException e) { logger.error("Illegal date argument: " + e); } } if(foundDate == null) { try { long value = Long.parseLong(date); if(value == 0) foundDate = new Date(); else if(value > 0) foundDate = new Date(value); else calPeriod = (int) value; } catch (NumberFormatException ex) {} } return foundDate; }
diff --git a/src/main/java/com/jayway/maven/plugins/android/phase09package/ApkMojo.java b/src/main/java/com/jayway/maven/plugins/android/phase09package/ApkMojo.java index 00714bb9..5065c689 100644 --- a/src/main/java/com/jayway/maven/plugins/android/phase09package/ApkMojo.java +++ b/src/main/java/com/jayway/maven/plugins/android/phase09package/ApkMojo.java @@ -1,1130 +1,1130 @@ /* * Copyright (C) 2009 Jayway AB * Copyright (C) 2007-2008 JVending Masa * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jayway.maven.plugins.android.phase09package; import com.android.sdklib.build.ApkBuilder; import com.android.sdklib.build.ApkCreationException; import com.android.sdklib.build.DuplicateFileException; import com.android.sdklib.build.SealedApkException; import com.jayway.maven.plugins.android.AbstractAndroidMojo; import com.jayway.maven.plugins.android.AndroidNdk; import com.jayway.maven.plugins.android.AndroidSigner; import com.jayway.maven.plugins.android.CommandExecutor; import com.jayway.maven.plugins.android.ExecutionException; import com.jayway.maven.plugins.android.common.NativeHelper; import com.jayway.maven.plugins.android.config.ConfigHandler; import com.jayway.maven.plugins.android.config.ConfigPojo; import com.jayway.maven.plugins.android.config.PullParameter; import com.jayway.maven.plugins.android.configuration.Apk; import com.jayway.maven.plugins.android.configuration.MetaInf; import com.jayway.maven.plugins.android.configuration.Sign; import org.apache.commons.io.FileUtils; import org.apache.commons.io.filefilter.DirectoryFileFilter; import org.apache.commons.io.filefilter.FileFileFilter; import org.apache.commons.io.filefilter.FileFilterUtils; import org.apache.commons.io.filefilter.IOFileFilter; import org.apache.commons.lang.StringUtils; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.factory.ArtifactFactory; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.codehaus.plexus.util.AbstractScanner; import java.io.File; import java.io.FileFilter; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipOutputStream; import static com.jayway.maven.plugins.android.common.AndroidExtension.APK; import static com.jayway.maven.plugins.android.common.AndroidExtension.AAR; import static com.jayway.maven.plugins.android.common.AndroidExtension.APKLIB; /** * Creates the apk file. By default signs it with debug keystore.<br/> * Change that by setting configuration parameter * <code>&lt;sign&gt;&lt;debug&gt;false&lt;/debug&gt;&lt;/sign&gt;</code>. * * @author [email protected] * @goal apk * @phase package * @requiresDependencyResolution compile */ public class ApkMojo extends AbstractAndroidMojo { /** * <p>How to sign the apk.</p> * <p>Looks like this:</p> * <pre> * &lt;sign&gt; * &lt;debug&gt;auto&lt;/debug&gt; * &lt;/sign&gt; * </pre> * <p>Valid values for <code>&lt;debug&gt;</code> are: * <ul> * <li><code>true</code> = sign with the debug keystore. * <li><code>false</code> = don't sign with the debug keystore. * <li><code>both</code> = create a signed as well as an unsigned apk. * <li><code>auto</code> (default) = sign with debug keystore, unless another keystore is defined. (Signing with * other keystores is not yet implemented. See * <a href="http://code.google.com/p/maven-android-plugin/issues/detail?id=2">Issue 2</a>.) * </ul></p> * <p>Can also be configured from command-line with parameter <code>-Dandroid.sign.debug</code>.</p> * * @parameter */ private Sign sign; /** * <p>Parameter designed to pick up <code>-Dandroid.sign.debug</code> in case there is no pom with a * <code>&lt;sign&gt;</code> configuration tag.</p> * <p>Corresponds to {@link com.jayway.maven.plugins.android.configuration.Sign#debug}.</p> * * @parameter expression="${android.sign.debug}" default-value="auto" * @readonly */ private String signDebug; /** * <p>Rewrite the manifest so that all of its instrumentation components target the given package. * This value will be passed on to the aapt parameter --rename-instrumentation-target-package. * Look to aapt for more help on this. </p> * * @parameter expression="${android.renameInstrumentationTargetPackage}" * * TODO pass this into AaptExecutor */ private String renameInstrumentationTargetPackage; /** * <p>Allows to detect and extract the duplicate files from embedded jars. In that case, the plugin analyzes * the content of all embedded dependencies and checks they are no duplicates inside those dependencies. Indeed, * Android does not support duplicates, and all dependencies are inlined in the APK. If duplicates files are found, * the resource is kept in the first dependency and removes from others. * * @parameter expression="${android.extractDuplicates}" default-value="false" */ private boolean extractDuplicates; /** * <p>Temporary folder for collecting native libraries.</p> * * @parameter default-value="${project.build.directory}/libs" * @readonly */ private File nativeLibrariesOutputDirectory; /** * <p>Classifier to add to the artifact generated. If given, the artifact will be an attachment instead.</p> * * @parameter */ private String classifier; /** * <p>Additional source directories that contain resources to be packaged into the apk.</p> * <p>These are not source directories, that contain java classes to be compiled. * It corresponds to the -df option of the apkbuilder program. It allows you to specify directories, * that contain additional resources to be packaged into the apk. </p> * So an example inside the plugin configuration could be: * <pre> * &lt;configuration&gt; * ... * &lt;sourceDirectories&gt; * &lt;sourceDirectory&gt;${project.basedir}/additionals&lt;/sourceDirectory&gt; * &lt;/sourceDirectories&gt; * ... * &lt;/configuration&gt; * </pre> * * @parameter expression="${android.sourceDirectories}" default-value="" */ private File[] sourceDirectories; /** * @component * @readonly * @required */ protected ArtifactFactory artifactFactory; /** * Pattern for additional META-INF resources to be packaged into the apk. * <p> * The APK builder filters these resources and doesn't include them into the apk. * This leads to bad behaviour of dependent libraries relying on these resources, * for instance service discovery doesn't work.<br/> * By specifying this pattern, the android plugin adds these resources to the final apk. * </p> * <p>The pattern is relative to META-INF, i.e. one must use * <pre> * <code> * &lt;apkMetaIncludes&gt; * &lt;metaInclude>services/**&lt;/metaInclude&gt; * &lt;/apkMetaIncludes&gt; * </code> * </pre> * ... instead of * <pre> * <code> * &lt;apkMetaIncludes&gt; * &lt;metaInclude>META-INF/services/**&lt;/metaInclude&gt; * &lt;/apkMetaIncludes&gt; * </code> * </pre> * <p> * See also <a href="http://code.google.com/p/maven-android-plugin/issues/detail?id=97">Issue 97</a> * </p> * * @parameter expression="${android.apk.metaIncludes}" * @deprecated in favour of apk.metaInf */ @PullParameter private String[] apkMetaIncludes; @PullParameter( defaultValueGetterMethod = "getDefaultMetaInf" ) private MetaInf apkMetaInf; /** * @parameter alias="metaInf" */ private MetaInf pluginMetaInf; /** * Defines whether or not the APK is being produced in debug mode or not. * * @parameter expression="${android.apk.debug}" */ @PullParameter( defaultValue = "false" ) private Boolean apkDebug; /** * @parameter expression="${android.nativeToolchain}" */ @PullParameter( defaultValue = "arm-linux-androideabi-4.4.3" ) private String apkNativeToolchain; /** * Specifies the final name of the library output by the build (this allows * * @parameter expression="${android.ndk.build.build.final-library.name}" */ private String ndkFinalLibraryName; /** * Specify a list of patterns that are matched against the names of jar file * dependencies. Matching jar files will not have their resources added to the * resulting APK. * * The patterns are standard Java regexes. * * @parameter */ private String[] excludeJarResources; private Pattern[] excludeJarResourcesPatterns; /** * Embedded configuration of this mojo. * * @parameter */ @ConfigPojo( prefix = "apk" ) private Apk apk; private static final Pattern PATTERN_JAR_EXT = Pattern.compile( "^.+\\.jar$", 2 ); /** * <p>Default hardware architecture for native library dependencies (with {@code &lt;type>so&lt;/type>}) * without a classifier.</p> * <p>Valid values currently include {@code armeabi}, {@code armeabi-v7a}, {@code mips} and {@code x86}.</p> * * @parameter expression="${android.nativeLibrariesDependenciesHardwareArchitectureDefault}" default-value="armeabi" */ private String nativeLibrariesDependenciesHardwareArchitectureDefault; /** * * @throws MojoExecutionException * @throws MojoFailureException */ public void execute() throws MojoExecutionException, MojoFailureException { // Make an early exit if we're not supposed to generate the APK if ( ! generateApk ) { return; } ConfigHandler cfh = new ConfigHandler( this, this.session, this.execution ); cfh.parseConfiguration(); generateIntermediateApk(); // Compile resource exclusion patterns, if any if ( excludeJarResources != null && excludeJarResources.length > 0 ) { getLog().debug( "Compiling " + excludeJarResources.length + " patterns" ); excludeJarResourcesPatterns = new Pattern[excludeJarResources.length]; for ( int index = 0; index < excludeJarResources.length; ++index ) { excludeJarResourcesPatterns[index] = Pattern.compile( excludeJarResources[index] ); } } // Initialize apk build configuration File outputFile = new File( project.getBuild().getDirectory(), project.getBuild().getFinalName() + "." + APK ); final boolean signWithDebugKeyStore = getAndroidSigner().isSignWithDebugKeyStore(); if ( getAndroidSigner().shouldCreateBothSignedAndUnsignedApk() ) { getLog().info( "Creating debug key signed apk file " + outputFile ); createApkFile( outputFile, true ); final File unsignedOutputFile = new File( project.getBuild().getDirectory(), project.getBuild().getFinalName() + "-unsigned." + APK ); getLog().info( "Creating additional unsigned apk file " + unsignedOutputFile ); createApkFile( unsignedOutputFile, false ); projectHelper.attachArtifact( project, unsignedOutputFile, classifier == null ? "unsigned" : classifier + "_unsigned" ); } else { createApkFile( outputFile, signWithDebugKeyStore ); } if ( classifier == null ) { // Set the generated .apk file as the main artifact (because the pom states <packaging>apk</packaging>) project.getArtifact().setFile( outputFile ); } else { // If there is a classifier specified, attach the artifact using that projectHelper.attachArtifact( project, outputFile, classifier ); } } void createApkFile( File outputFile, boolean signWithDebugKeyStore ) throws MojoExecutionException { File dexFile = new File( project.getBuild().getDirectory(), "classes.dex" ); File zipArchive = new File( project.getBuild().getDirectory(), project.getBuild().getFinalName() + ".ap_" ); ArrayList<File> sourceFolders = new ArrayList<File>(); if ( sourceDirectories != null ) { for ( File f : sourceDirectories ) { sourceFolders.add( f ); } } ArrayList<File> jarFiles = new ArrayList<File>(); ArrayList<File> nativeFolders = new ArrayList<File>(); // Process the native libraries, looking both in the current build directory as well as // at the dependencies declared in the pom. Currently, all .so files are automatically included processNativeLibraries( nativeFolders ); doAPKWithAPKBuilder( outputFile, dexFile, zipArchive, sourceFolders, jarFiles, nativeFolders, signWithDebugKeyStore ); if ( this.apkMetaInf != null ) { try { addMetaInf( outputFile, jarFiles ); } catch ( IOException e ) { throw new MojoExecutionException( "Could not add META-INF resources.", e ); } } } private void addMetaInf( File outputFile, ArrayList<File> jarFiles ) throws IOException { File tmp = File.createTempFile( outputFile.getName(), ".add", outputFile.getParentFile() ); FileOutputStream fos = new FileOutputStream( tmp ); ZipOutputStream zos = new ZipOutputStream( fos ); Set<String> entries = new HashSet<String>(); updateWithMetaInf( zos, outputFile, entries, false ); for ( File f : jarFiles ) { updateWithMetaInf( zos, f, entries, true ); } zos.close(); outputFile.delete(); if ( ! tmp.renameTo( outputFile ) ) { throw new IOException( String.format( "Cannot rename %s to %s", tmp, outputFile.getName() ) ); } } private void updateWithMetaInf( ZipOutputStream zos, File jarFile, Set<String> entries, boolean metaInfOnly ) throws IOException { ZipFile zin = new ZipFile( jarFile ); for ( Enumeration<? extends ZipEntry> en = zin.entries(); en.hasMoreElements(); ) { ZipEntry ze = en.nextElement(); if ( ze.isDirectory() ) { continue; } String zn = ze.getName(); if ( metaInfOnly ) { if ( ! zn.startsWith( "META-INF/" ) ) { continue; } if ( this.extractDuplicates && ! entries.add( zn ) ) { continue; } if ( ! this.apkMetaInf.isIncluded( zn ) ) { continue; } } zos.putNextEntry( new ZipEntry( zn ) ); InputStream is = zin.getInputStream( ze ); copyStreamWithoutClosing( is, zos ); is.close(); zos.closeEntry(); } zin.close(); } private Map<String, List<File>> jars = new HashMap<String, List<File>>(); private void computeDuplicateFiles( File jar ) throws IOException { ZipFile file = new ZipFile( jar ); Enumeration<? extends ZipEntry> list = file.entries(); while ( list.hasMoreElements() ) { ZipEntry ze = list.nextElement(); if ( ! ( ze.getName().contains( "META-INF/" ) || ze.isDirectory() ) ) { // Exclude META-INF and Directories List<File> l = jars.get( ze.getName() ); if ( l == null ) { l = new ArrayList<File>(); jars.put( ze.getName(), l ); } l.add( jar ); } } } /** * Creates the APK file using the internal APKBuilder. * * @param outputFile the output file * @param dexFile the dex file * @param zipArchive the classes folder * @param sourceFolders the resources * @param jarFiles the embedded java files * @param nativeFolders the native folders * @param signWithDebugKeyStore enables the signature of the APK using the debug key * @throws MojoExecutionException if the APK cannot be created. */ private void doAPKWithAPKBuilder( File outputFile, File dexFile, File zipArchive, ArrayList<File> sourceFolders, ArrayList<File> jarFiles, ArrayList<File> nativeFolders, boolean signWithDebugKeyStore ) throws MojoExecutionException { getLog().debug( "Building APK with internal APKBuilder" ); sourceFolders.add( new File( project.getBuild().getOutputDirectory() ) ); for ( Artifact artifact : getRelevantCompileArtifacts() ) { if ( extractDuplicates ) { try { computeDuplicateFiles( artifact.getFile() ); } catch ( Exception e ) { getLog().warn( "Cannot compute duplicates files from " + artifact.getFile().getAbsolutePath(), e ); } } jarFiles.add( artifact.getFile() ); } // Check duplicates. if ( extractDuplicates ) { List<String> duplicates = new ArrayList<String>(); List<File> jarToModify = new ArrayList<File>(); for ( String s : jars.keySet() ) { List<File> l = jars.get( s ); if ( l.size() > 1 ) { getLog().warn( "Duplicate file " + s + " : " + l ); duplicates.add( s ); for ( int i = 1; i < l.size(); i++ ) { if ( ! jarToModify.contains( l.get( i ) ) ) { jarToModify.add( l.get( i ) ); } } } } // Rebuild jars. for ( File file : jarToModify ) { File newJar; newJar = removeDuplicatesFromJar( file, duplicates ); int index = jarFiles.indexOf( file ); if ( newJar != null ) { jarFiles.set( index, newJar ); } } } String debugKeyStore; ApkBuilder apkBuilder; try { debugKeyStore = ApkBuilder.getDebugKeystore(); apkBuilder = new ApkBuilder( outputFile, zipArchive, dexFile, ( signWithDebugKeyStore ) ? debugKeyStore : null, null ); if ( apkDebug ) { apkBuilder.setDebugMode( apkDebug ); } for ( File sourceFolder : sourceFolders ) { apkBuilder.addSourceFolder( sourceFolder ); } for ( File jarFile : jarFiles ) { boolean excluded = false; if ( excludeJarResourcesPatterns != null ) { final String name = jarFile.getName(); getLog().debug( "Checking " + name + " against patterns" ); for ( Pattern pattern : excludeJarResourcesPatterns ) { final Matcher matcher = pattern.matcher( name ); if ( matcher.matches() ) { getLog().debug( "Jar " + name + " excluded by pattern " + pattern ); excluded = true; break; } else { getLog().debug( "Jar " + name + " not excluded by pattern " + pattern ); } } } if ( excluded ) { continue; } if ( jarFile.isDirectory() ) { String[] filenames = jarFile.list( new FilenameFilter() { public boolean accept( File dir, String name ) { return PATTERN_JAR_EXT.matcher( name ).matches(); } } ); for ( String filename : filenames ) { apkBuilder.addResourcesFromJar( new File( jarFile, filename ) ); } } else { apkBuilder.addResourcesFromJar( jarFile ); } } for ( File nativeFolder : nativeFolders ) { apkBuilder.addNativeLibraries( nativeFolder ); } apkBuilder.sealApk(); } catch ( ApkCreationException e ) { throw new MojoExecutionException( e.getMessage() ); } catch ( DuplicateFileException e ) { - final String msg = String.format( "Duplicate file! archive: %s, file1: %s, file2: %s", + final String msg = String.format( "Duplicated file: %s, found in archive %s and %s", e.getArchivePath(), e.getFile1(), e.getFile2() ); throw new MojoExecutionException( msg, e ); } catch ( SealedApkException e ) { throw new MojoExecutionException( e.getMessage() ); } } private File removeDuplicatesFromJar( File in, List<String> duplicates ) { String target = project.getBuild().getOutputDirectory(); File tmp = new File( target, "unpacked-embedded-jars" ); tmp.mkdirs(); File out = new File( tmp, in.getName() ); if ( out.exists() ) { return out; } else { try { out.createNewFile(); } catch ( IOException e ) { e.printStackTrace(); } } // Create a new Jar file FileOutputStream fos = null; ZipOutputStream jos = null; try { fos = new FileOutputStream( out ); jos = new ZipOutputStream( fos ); } catch ( FileNotFoundException e1 ) { getLog().error( "Cannot remove duplicates : the output file " + out.getAbsolutePath() + " does not found" ); return null; } ZipFile inZip = null; try { inZip = new ZipFile( in ); Enumeration<? extends ZipEntry> entries = inZip.entries(); while ( entries.hasMoreElements() ) { ZipEntry entry = entries.nextElement(); // If the entry is not a duplicate, copy. if ( ! duplicates.contains( entry.getName() ) ) { // copy the entry header to jos jos.putNextEntry( entry ); InputStream currIn = inZip.getInputStream( entry ); copyStreamWithoutClosing( currIn, jos ); currIn.close(); jos.closeEntry(); } } } catch ( IOException e ) { getLog().error( "Cannot removing duplicates : " + e.getMessage() ); return null; } try { if ( inZip != null ) { inZip.close(); } jos.close(); fos.close(); jos = null; fos = null; } catch ( IOException e ) { // ignore it. } getLog().info( in.getName() + " rewritten without duplicates : " + out.getAbsolutePath() ); return out; } /** * Copies an input stream into an output stream but does not close the streams. * * @param in the input stream * @param out the output stream * @throws IOException if the stream cannot be copied */ private static void copyStreamWithoutClosing( InputStream in, OutputStream out ) throws IOException { final int bufferSize = 4096; byte[] b = new byte[ bufferSize ]; int n; while ( ( n = in.read( b ) ) != - 1 ) { out.write( b, 0, n ); } } private void processNativeLibraries( final List<File> natives ) throws MojoExecutionException { for ( String ndkArchitecture : AndroidNdk.NDK_ARCHITECTURES ) { processNativeLibraries( natives, ndkArchitecture ); } } private void addNativeDirectory( final List<File> natives, final File nativeDirectory ) { if ( ! natives.contains( nativeDirectory ) ) { natives.add( nativeDirectory ); } } private void processNativeLibraries( final List<File> natives, String ndkArchitecture ) throws MojoExecutionException { // Examine the native libraries directory for content. This will only be true if: // a) the directory exists // b) it contains at least 1 file final boolean hasValidNativeLibrariesDirectory = hasValidNativeLibrariesDirectory(); final boolean hasValidBuildNativeLibrariesDirectory = hasValidBuildNativeLibrariesDirectory(); final Set<Artifact> artifacts = getNativeLibraryArtifacts(); if ( artifacts.isEmpty() && hasValidNativeLibrariesDirectory && ! hasValidBuildNativeLibrariesDirectory ) { getLog().debug( "No native library dependencies detected, will point directly to " + nativeLibrariesDirectory ); // Point directly to the directory in this case - no need to copy files around addNativeDirectory( natives, nativeLibrariesDirectory ); // FIXME: This would pollute a libs folder which is under source control // FIXME: Would be better to not support this case? optionallyCopyGdbServer( nativeLibrariesDirectory, ndkArchitecture ); } else { if ( ! artifacts.isEmpty() || hasValidNativeLibrariesDirectory ) { // In this case, we may have both .so files in it's normal location // as well as .so dependencies final File destinationDirectory = makeNativeLibrariesOutputDirectory(); // Point directly to the directory addNativeDirectory( natives, destinationDirectory ); // If we have a valid native libs, copy those files - these already come in the structure required if ( hasValidNativeLibrariesDirectory ) { copyLocalNativeLibraries( nativeLibrariesDirectory, destinationDirectory ); } if ( ! artifacts.isEmpty() ) { for ( Artifact resolvedArtifact : artifacts ) { if ( NativeHelper.artifactHasHardwareArchitecture( resolvedArtifact, ndkArchitecture, nativeLibrariesDependenciesHardwareArchitectureDefault ) ) { copyNativeLibraryArtifactFileToDirectory( resolvedArtifact, destinationDirectory, ndkArchitecture ); } else if ( APKLIB.equals( resolvedArtifact.getType() ) || AAR.equals( resolvedArtifact.getType() ) ) { addNativeDirectory( natives, new File( getLibraryUnpackDirectory( resolvedArtifact ) + "/libs" ) ); } } } // Finally, think about copying the gdbserver binary into the APK output as well optionallyCopyGdbServer( destinationDirectory, ndkArchitecture ); } } } /** * Examine the native libraries directory for content. This will only be true if: * <ul> * <li>The directory exists</li> * <li>It contains at least 1 file</li> * </ul> */ private boolean hasValidNativeLibrariesDirectory() { return nativeLibrariesDirectory != null && nativeLibrariesDirectory.exists() && ( nativeLibrariesDirectory.listFiles() != null && nativeLibrariesDirectory.listFiles().length > 0 ); } private boolean hasValidBuildNativeLibrariesDirectory() { return nativeLibrariesOutputDirectory.exists() && ( nativeLibrariesOutputDirectory.listFiles() != null && nativeLibrariesOutputDirectory.listFiles().length > 0 ); } /** * @return Any native dependencies or attached artifacts. This may include artifacts from the ndk-build MOJO. * @throws MojoExecutionException */ private Set<Artifact> getNativeLibraryArtifacts() throws MojoExecutionException { return new NativeHelper( project, projectRepos, repoSession, repoSystem, artifactFactory, getLog() ) .getNativeDependenciesArtifacts( unpackedApkLibsDirectory, true ); } /** * Create the ${project.build.outputDirectory}/libs directory. * * @return File reference to the native libraries output directory. */ private File makeNativeLibrariesOutputDirectory() { final File destinationDirectory = new File( nativeLibrariesOutputDirectory.getAbsolutePath() ); destinationDirectory.mkdirs(); return destinationDirectory; } private void copyNativeLibraryArtifactFileToDirectory( Artifact artifact, File destinationDirectory, String ndkArchitecture ) throws MojoExecutionException { final File artifactFile = artifact.getFile(); try { final String artifactId = artifact.getArtifactId(); String filename = artifactId.startsWith( "lib" ) ? artifactId + ".so" : "lib" + artifactId + ".so"; if ( ndkFinalLibraryName != null && artifact.getFile().getName().startsWith( "lib" + ndkFinalLibraryName ) ) { // The artifact looks like one we built with the NDK in this module // preserve the name from the NDK build filename = artifact.getFile().getName(); } final File finalDestinationDirectory = getFinalDestinationDirectoryFor( artifact, destinationDirectory, ndkArchitecture ); final File file = new File( finalDestinationDirectory, filename ); getLog().debug( "Copying native dependency " + artifactId + " (" + artifact.getGroupId() + ") to " + file ); FileUtils.copyFile( artifactFile, file ); } catch ( Exception e ) { throw new MojoExecutionException( "Could not copy native dependency.", e ); } } private void optionallyCopyGdbServer( File destinationDirectory, String architecture ) throws MojoExecutionException { try { final File destDir = new File( destinationDirectory, architecture ); if ( apkDebug && destDir.exists() ) { // Copy the gdbserver binary to libs/<architecture>/ final File gdbServerFile = getAndroidNdk().getGdbServer( architecture ); final File destFile = new File( destDir, "gdbserver" ); if ( ! destFile.exists() ) { FileUtils.copyFile( gdbServerFile, destFile ); } else { getLog().info( "Note: gdbserver binary already exists at destination, will not copy over" ); } } } catch ( Exception e ) { getLog().error( "Error while copying gdbserver: " + e.getMessage(), e ); throw new MojoExecutionException( "Error while copying gdbserver: " + e.getMessage(), e ); } } private File getFinalDestinationDirectoryFor( Artifact resolvedArtifact, File destinationDirectory, String ndkArchitecture ) { File finalDestinationDirectory = new File( destinationDirectory, ndkArchitecture + "/" ); finalDestinationDirectory.mkdirs(); return finalDestinationDirectory; } private void copyLocalNativeLibraries( final File localNativeLibrariesDirectory, final File destinationDirectory ) throws MojoExecutionException { getLog().debug( "Copying existing native libraries from " + localNativeLibrariesDirectory ); try { IOFileFilter libSuffixFilter = FileFilterUtils.suffixFileFilter( ".so" ); IOFileFilter gdbserverNameFilter = FileFilterUtils.nameFileFilter( "gdbserver" ); IOFileFilter orFilter = FileFilterUtils.or( libSuffixFilter, gdbserverNameFilter ); IOFileFilter libFiles = FileFilterUtils.and( FileFileFilter.FILE, orFilter ); FileFilter filter = FileFilterUtils.or( DirectoryFileFilter.DIRECTORY, libFiles ); org.apache.commons.io.FileUtils .copyDirectory( localNativeLibrariesDirectory, destinationDirectory, filter ); } catch ( IOException e ) { getLog().error( "Could not copy native libraries: " + e.getMessage(), e ); throw new MojoExecutionException( "Could not copy native dependency.", e ); } } /** * Generates an intermediate apk file (actually .ap_) containing the resources and assets. * * @throws MojoExecutionException */ private void generateIntermediateApk() throws MojoExecutionException { CommandExecutor executor = CommandExecutor.Factory.createDefaultCommmandExecutor(); executor.setLogger( this.getLog() ); File[] overlayDirectories = getResourceOverlayDirectories(); File androidJar = getAndroidSdk().getAndroidJar(); File outputFile = new File( project.getBuild().getDirectory(), project.getBuild().getFinalName() + ".ap_" ); List<String> commands = new ArrayList<String>(); commands.add( "package" ); commands.add( "-f" ); commands.add( "-M" ); commands.add( androidManifestFile.getAbsolutePath() ); for ( File resOverlayDir : overlayDirectories ) { if ( resOverlayDir != null && resOverlayDir.exists() ) { commands.add( "-S" ); commands.add( resOverlayDir.getAbsolutePath() ); } } if ( resourceDirectory.exists() ) { commands.add( "-S" ); commands.add( resourceDirectory.getAbsolutePath() ); } for ( Artifact artifact : getAllRelevantDependencyArtifacts() ) { if ( artifact.getType().equals( APKLIB ) || artifact.getType().equals( AAR ) ) { final String apkLibResDir = getLibraryUnpackDirectory( artifact ) + "/res"; if ( new File( apkLibResDir ).exists() ) { commands.add( "-S" ); commands.add( apkLibResDir ); } } } commands.add( "--auto-add-overlay" ); // NB aapt only accepts a single assets parameter - combinedAssets is a merge of all assets if ( combinedAssets.exists() ) { getLog().debug( "Adding assets folder : " + combinedAssets ); commands.add( "-A" ); commands.add( combinedAssets.getAbsolutePath() ); } if ( StringUtils.isNotBlank( renameManifestPackage ) ) { commands.add( "--rename-manifest-package" ); commands.add( renameManifestPackage ); } if ( StringUtils.isNotBlank( renameInstrumentationTargetPackage ) ) { commands.add( "--rename-instrumentation-target-package" ); commands.add( renameInstrumentationTargetPackage ); } commands.add( "-I" ); commands.add( androidJar.getAbsolutePath() ); commands.add( "-F" ); commands.add( outputFile.getAbsolutePath() ); if ( StringUtils.isNotBlank( configurations ) ) { commands.add( "-c" ); commands.add( configurations ); } for ( String aaptExtraArg : aaptExtraArgs ) { commands.add( aaptExtraArg ); } if ( !release ) { getLog().info( "Enabling debug build for apk." ); commands.add( "--debug-mode" ); } else { getLog().info( "Enabling release build for apk." ); } getLog().info( getAndroidSdk().getAaptPath() + " " + commands.toString() ); try { executor.executeCommand( getAndroidSdk().getAaptPath(), commands, project.getBasedir(), false ); } catch ( ExecutionException e ) { throw new MojoExecutionException( "", e ); } } private void processApkLibAssets() throws MojoExecutionException { // Next pull APK Lib assets, reverse the order to give precedence to libs higher up the chain List<Artifact> artifactList = new ArrayList<Artifact>( getAllRelevantDependencyArtifacts() ); for ( Artifact artifact : artifactList ) { if ( artifact.getType().equals( APKLIB ) || artifact.getType().equals( AAR ) ) { File apklibAsssetsDirectory = new File( getLibraryUnpackDirectory( artifact ) + "/assets" ); if ( apklibAsssetsDirectory.exists() ) { try { getLog().info( "Copying dependency assets files to combined assets directory." ); org.apache.commons.io.FileUtils .copyDirectory( apklibAsssetsDirectory, combinedAssets, new FileFilter() { /** * Excludes files matching one of the common file to exclude. * The default excludes pattern are the ones from * {org.codehaus.plexus.util.AbstractScanner#DEFAULTEXCLUDES} * @see java.io.FileFilter#accept(java.io.File) */ public boolean accept( File file ) { for ( String pattern : AbstractScanner.DEFAULTEXCLUDES ) { if ( AbstractScanner.match( pattern, file.getAbsolutePath() ) ) { getLog().debug( "Excluding " + file.getName() + " from asset copy : " + "matching " + pattern ); return false; } } return true; } } ); } catch ( IOException e ) { throw new MojoExecutionException( "", e ); } } } } } protected AndroidSigner getAndroidSigner() { if ( sign == null ) { return new AndroidSigner( signDebug ); } else { return new AndroidSigner( sign.getDebug() ); } } private MetaInf getDefaultMetaInf() { // check for deprecated first if ( apkMetaIncludes != null && apkMetaIncludes.length > 0 ) { return new MetaInf().include( apkMetaIncludes ); } return this.pluginMetaInf; } }
true
true
private void doAPKWithAPKBuilder( File outputFile, File dexFile, File zipArchive, ArrayList<File> sourceFolders, ArrayList<File> jarFiles, ArrayList<File> nativeFolders, boolean signWithDebugKeyStore ) throws MojoExecutionException { getLog().debug( "Building APK with internal APKBuilder" ); sourceFolders.add( new File( project.getBuild().getOutputDirectory() ) ); for ( Artifact artifact : getRelevantCompileArtifacts() ) { if ( extractDuplicates ) { try { computeDuplicateFiles( artifact.getFile() ); } catch ( Exception e ) { getLog().warn( "Cannot compute duplicates files from " + artifact.getFile().getAbsolutePath(), e ); } } jarFiles.add( artifact.getFile() ); } // Check duplicates. if ( extractDuplicates ) { List<String> duplicates = new ArrayList<String>(); List<File> jarToModify = new ArrayList<File>(); for ( String s : jars.keySet() ) { List<File> l = jars.get( s ); if ( l.size() > 1 ) { getLog().warn( "Duplicate file " + s + " : " + l ); duplicates.add( s ); for ( int i = 1; i < l.size(); i++ ) { if ( ! jarToModify.contains( l.get( i ) ) ) { jarToModify.add( l.get( i ) ); } } } } // Rebuild jars. for ( File file : jarToModify ) { File newJar; newJar = removeDuplicatesFromJar( file, duplicates ); int index = jarFiles.indexOf( file ); if ( newJar != null ) { jarFiles.set( index, newJar ); } } } String debugKeyStore; ApkBuilder apkBuilder; try { debugKeyStore = ApkBuilder.getDebugKeystore(); apkBuilder = new ApkBuilder( outputFile, zipArchive, dexFile, ( signWithDebugKeyStore ) ? debugKeyStore : null, null ); if ( apkDebug ) { apkBuilder.setDebugMode( apkDebug ); } for ( File sourceFolder : sourceFolders ) { apkBuilder.addSourceFolder( sourceFolder ); } for ( File jarFile : jarFiles ) { boolean excluded = false; if ( excludeJarResourcesPatterns != null ) { final String name = jarFile.getName(); getLog().debug( "Checking " + name + " against patterns" ); for ( Pattern pattern : excludeJarResourcesPatterns ) { final Matcher matcher = pattern.matcher( name ); if ( matcher.matches() ) { getLog().debug( "Jar " + name + " excluded by pattern " + pattern ); excluded = true; break; } else { getLog().debug( "Jar " + name + " not excluded by pattern " + pattern ); } } } if ( excluded ) { continue; } if ( jarFile.isDirectory() ) { String[] filenames = jarFile.list( new FilenameFilter() { public boolean accept( File dir, String name ) { return PATTERN_JAR_EXT.matcher( name ).matches(); } } ); for ( String filename : filenames ) { apkBuilder.addResourcesFromJar( new File( jarFile, filename ) ); } } else { apkBuilder.addResourcesFromJar( jarFile ); } } for ( File nativeFolder : nativeFolders ) { apkBuilder.addNativeLibraries( nativeFolder ); } apkBuilder.sealApk(); } catch ( ApkCreationException e ) { throw new MojoExecutionException( e.getMessage() ); } catch ( DuplicateFileException e ) { final String msg = String.format( "Duplicate file! archive: %s, file1: %s, file2: %s", e.getArchivePath(), e.getFile1(), e.getFile2() ); throw new MojoExecutionException( msg, e ); } catch ( SealedApkException e ) { throw new MojoExecutionException( e.getMessage() ); } }
private void doAPKWithAPKBuilder( File outputFile, File dexFile, File zipArchive, ArrayList<File> sourceFolders, ArrayList<File> jarFiles, ArrayList<File> nativeFolders, boolean signWithDebugKeyStore ) throws MojoExecutionException { getLog().debug( "Building APK with internal APKBuilder" ); sourceFolders.add( new File( project.getBuild().getOutputDirectory() ) ); for ( Artifact artifact : getRelevantCompileArtifacts() ) { if ( extractDuplicates ) { try { computeDuplicateFiles( artifact.getFile() ); } catch ( Exception e ) { getLog().warn( "Cannot compute duplicates files from " + artifact.getFile().getAbsolutePath(), e ); } } jarFiles.add( artifact.getFile() ); } // Check duplicates. if ( extractDuplicates ) { List<String> duplicates = new ArrayList<String>(); List<File> jarToModify = new ArrayList<File>(); for ( String s : jars.keySet() ) { List<File> l = jars.get( s ); if ( l.size() > 1 ) { getLog().warn( "Duplicate file " + s + " : " + l ); duplicates.add( s ); for ( int i = 1; i < l.size(); i++ ) { if ( ! jarToModify.contains( l.get( i ) ) ) { jarToModify.add( l.get( i ) ); } } } } // Rebuild jars. for ( File file : jarToModify ) { File newJar; newJar = removeDuplicatesFromJar( file, duplicates ); int index = jarFiles.indexOf( file ); if ( newJar != null ) { jarFiles.set( index, newJar ); } } } String debugKeyStore; ApkBuilder apkBuilder; try { debugKeyStore = ApkBuilder.getDebugKeystore(); apkBuilder = new ApkBuilder( outputFile, zipArchive, dexFile, ( signWithDebugKeyStore ) ? debugKeyStore : null, null ); if ( apkDebug ) { apkBuilder.setDebugMode( apkDebug ); } for ( File sourceFolder : sourceFolders ) { apkBuilder.addSourceFolder( sourceFolder ); } for ( File jarFile : jarFiles ) { boolean excluded = false; if ( excludeJarResourcesPatterns != null ) { final String name = jarFile.getName(); getLog().debug( "Checking " + name + " against patterns" ); for ( Pattern pattern : excludeJarResourcesPatterns ) { final Matcher matcher = pattern.matcher( name ); if ( matcher.matches() ) { getLog().debug( "Jar " + name + " excluded by pattern " + pattern ); excluded = true; break; } else { getLog().debug( "Jar " + name + " not excluded by pattern " + pattern ); } } } if ( excluded ) { continue; } if ( jarFile.isDirectory() ) { String[] filenames = jarFile.list( new FilenameFilter() { public boolean accept( File dir, String name ) { return PATTERN_JAR_EXT.matcher( name ).matches(); } } ); for ( String filename : filenames ) { apkBuilder.addResourcesFromJar( new File( jarFile, filename ) ); } } else { apkBuilder.addResourcesFromJar( jarFile ); } } for ( File nativeFolder : nativeFolders ) { apkBuilder.addNativeLibraries( nativeFolder ); } apkBuilder.sealApk(); } catch ( ApkCreationException e ) { throw new MojoExecutionException( e.getMessage() ); } catch ( DuplicateFileException e ) { final String msg = String.format( "Duplicated file: %s, found in archive %s and %s", e.getArchivePath(), e.getFile1(), e.getFile2() ); throw new MojoExecutionException( msg, e ); } catch ( SealedApkException e ) { throw new MojoExecutionException( e.getMessage() ); } }
diff --git a/src/nl/nikhef/jgridstart/logging/UserTestRunner.java b/src/nl/nikhef/jgridstart/logging/UserTestRunner.java index 0cdd8cd..098832a 100644 --- a/src/nl/nikhef/jgridstart/logging/UserTestRunner.java +++ b/src/nl/nikhef/jgridstart/logging/UserTestRunner.java @@ -1,308 +1,305 @@ package nl.nikhef.jgridstart.logging; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.URL; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.Box; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.SwingUtilities; import nl.nikhef.jgridstart.util.ConnectionUtils; import nl.nikhef.jgridstart.util.FileUtils; import org.apache.commons.exec.CommandLine; import org.apache.commons.exec.DefaultExecutor; import org.apache.commons.exec.ExecuteException; import org.apache.commons.exec.ExecuteResultHandler; import org.apache.commons.exec.Executor; import org.apache.commons.exec.PumpStreamHandler; import org.apache.commons.exec.ShutdownHookProcessDestroyer; import org.apache.commons.exec.StreamPumper; import org.apache.commons.lang.StringUtils; /** GUI test program that runs a command and uploads the output */ public class UserTestRunner { /** GUI test program that runs unit tests */ public static void main(String[] args) { new TesterFrame().setVisible(true); } /** Simple GUI for running and submitting tests. * <p> * To enable diagnostics on the user's computer, the tests are packaged * in a single testing package. A GUI is provided so that the user can * easily run the tests, and submit them to the jGridstart developers. * This allows us to gather test results on a variety of platforms. * * @author wvengen */ static class TesterFrame extends JFrame implements ExecuteResultHandler { /** JUnit suite to run */ final String testclass = "nl.nikhef.jgridstart.AllTests"; /** Where to post test result data to */ final String url = "http://jgridstart.nikhef.nl/tests/upload.php"; /** tempdir for jars */ File tmpdir = null; /** Frame title */ final String title = "jGridstart Testing Program"; /** Label with user message */ JLabel msg; /** Testing output display */ JTextArea outputpane; /** Testing output display scrolled area */ JScrollPane outputscroll; /** Allow upload checkbox */ JCheckBox uploadCheck; /** Action button (run or upload) */ JButton actionBtn; /** Quit action, stops testing process as well */ Action quitAction; /** Run action */ Action runAction; /** Upload action */ Action uploadAction; /** Testing process */ Executor exec = null; /** Testing output */ StringBuffer output; final String linesep = System.getProperty("line.separator"); public TesterFrame() { setTitle(title); setSize(new Dimension(650, 400)); setDefaultCloseOperation(DISPOSE_ON_CLOSE); addWindowListener(new WindowAdapter() { @Override public void windowClosed(WindowEvent e) { if (tmpdir!=null) FileUtils.recursiveDelete(tmpdir); System.exit(0); } }); JPanel panel = new JPanel(); panel.setLayout(new BorderLayout(2, 2)); panel.add((msg = new JLabel()), BorderLayout.NORTH); JPanel cpanel = new JPanel(new BorderLayout()); outputpane = new JTextArea(); outputscroll = new JScrollPane(outputpane, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); outputpane.setEditable(false); cpanel.add(outputscroll, BorderLayout.CENTER); uploadCheck = new JCheckBox("Submit results to developers when the tests are finished."); cpanel.add(uploadCheck, BorderLayout.SOUTH); uploadCheck.setSelected(true); panel.add(cpanel, BorderLayout.CENTER); JPanel btnpanel = new JPanel(new FlowLayout(FlowLayout.CENTER)); runAction = new AbstractAction("Run tests") { public void actionPerformed(ActionEvent event) { runTests(); } }; btnpanel.add((actionBtn = new JButton(runAction))); getRootPane().setDefaultButton(actionBtn); uploadAction = new AbstractAction("Upload result") { public void actionPerformed(ActionEvent event) { doUpload(); } }; btnpanel.add(Box.createHorizontalStrut(5)); quitAction = new AbstractAction("Quit") { public void actionPerformed(ActionEvent event) { dispose(); } }; btnpanel.add(new JButton(quitAction)); panel.add(btnpanel, BorderLayout.SOUTH); setContentPane(panel); setMessage("Thank you for running the jGridstart testing program. Your cooperation enables us to " + "improve the software. Please press the button 'Run tests' below, then wait while the " + "tests are running, until a message appears about them being done.\n" + "\n" + "By default, the test results shown here will be sent to the jGridstart developers. If you " + "don't want this, feel free to disable it below. You will be able to upload it later."); } /** Set the message area to a string */ void setMessage(String txt) { msg.setText("<html><body>" + "<h1>"+title+"</h1>" + txt.replaceAll("\n", "<br>")+"<br><br></html></body>"); } /** Start the tests */ void runTests() { if (exec!=null) return; try { setMessage("Please <i>don't touch</i> your mouse or keyboard while the tests are running...\n" + "(the graphical user-interface tests require this to function)"); runAction.setEnabled(false); // find java first String java = new File(new File(new File(System.getProperty("java.home")), "bin"), "java").getPath(); if (System.getProperty("os.name").startsWith("Windows")) java = java + ".exe"; // if in a jar, extract files String classpath = System.getProperty("java.class.path"); URL testjars = getClass().getResource("testjars.txt"); if (testjars != null && testjars.toString().startsWith("jar:")) { tmpdir = FileUtils.createTempDir("jgridstart-testrun-"); BufferedReader jars = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("testjars.txt"))); String line; classpath = ""; while ( (line=jars.readLine())!=null ) { line = StringUtils.trim(line); if (line.equals("")) continue; InputStream jarin = getClass().getResourceAsStream("/"+line); if (jarin==null) throw new Exception("Incomplete tests jar file: "+line); File jaroutfile = new File(tmpdir, line); jaroutfile.deleteOnExit(); FileOutputStream jarout = new FileOutputStream(jaroutfile); byte[] b = new byte[1024]; int len; while ( (len=jarin.read(b)) != -1) jarout.write(b, 0, len); jarout.close(); jarin.close(); classpath += jaroutfile.getAbsolutePath() + System.getProperty("path.separator"); } // remove trailing ':' classpath = classpath.substring(0, classpath.length()-System.getProperty("path.separator").length()); tmpdir.deleteOnExit(); } CommandLine cmdline = new CommandLine(java); - /* cmdline.addArgument("-cp"); cmdline.addArgument(classpath); cmdline.addArgument("org.junit.runner.JUnitCore"); cmdline.addArgument(testclass); - */ - cmdline.addArgument("-version"); DefaultExecutor exec = new DefaultExecutor(); TextareaOutputStream outputstream = new TextareaOutputStream(outputpane); exec.setStreamHandler(new PumpStreamHandler(outputstream)); exec.setProcessDestroyer(new ShutdownHookProcessDestroyer()); System.out.println(cmdline); exec.execute(cmdline, this); } catch (Exception e) { e.printStackTrace(); // TODO finish } } /** Update gui to signal that tests are done */ void signalTestsDone() { setMessage("The tests have finished."); actionBtn.setAction(uploadAction); if (uploadCheck.isSelected()) doUpload(); } public void onProcessComplete(int exitValue) { outputpane.append("\n(testing exited with "+exitValue+")\n"); signalTestsDone(); } public void onProcessFailed(ExecuteException e) { outputpane.append("\n(testing failed: "+e+")\n"); signalTestsDone(); } /** Upload test results */ void doUpload() { if (!uploadAction.isEnabled()) return; uploadAction.setEnabled(false); uploadCheck.setEnabled(false); outputpane.append("-- Uploading data to developers"+linesep); new Thread() { final String txt = outputpane.getText(); @Override public void run() { try { final String ret = ConnectionUtils.pageContents( new URL(url), new String[] { "testresult", txt }, true); if (ret.charAt(0) == 'E') throw new Exception("Upload server error: "+ret.substring(1)); SwingUtilities.invokeLater(new Runnable() { public void run() { outputpane.append(ret+linesep); signalUploadDone(); } }); } catch (final Exception e) { e.printStackTrace(); SwingUtilities.invokeLater(new Runnable() { public void run() { outputpane.append("-- Submission of test results failed"+linesep); outputpane.append(e.getLocalizedMessage()+linesep); setMessage("Submission of test results failed, sorry."); uploadAction.setEnabled(true); } }); } } }.start(); } /** Update gui to signal that upload is done */ void signalUploadDone() { uploadAction.setEnabled(false); setMessage("The test results have been uploaded. Thank you for participating!\n" + "You can now close this window."); } protected class TextareaOutputStream extends OutputStream { private final JTextArea area; private final StringBuffer buf = new StringBuffer(128); public TextareaOutputStream(final JTextArea area) { this.area = area; } @Override public void write(int c) throws IOException { // append character to buffer buf.append((char)c); // and newline appends to textarea if ( c=='\n' ) flush(); } @Override public void close() { flush(); } @Override public void flush() { SwingUtilities.invokeLater(new Runnable() { String str = buf.toString(); public void run() { area.append(str); } }); buf.setLength(0); } public void message(String msg) { if (buf.charAt(buf.length()-1) != '\n') buf.append('\n'); buf.append(msg); buf.append('\n'); flush(); } } } }
false
true
void runTests() { if (exec!=null) return; try { setMessage("Please <i>don't touch</i> your mouse or keyboard while the tests are running...\n" + "(the graphical user-interface tests require this to function)"); runAction.setEnabled(false); // find java first String java = new File(new File(new File(System.getProperty("java.home")), "bin"), "java").getPath(); if (System.getProperty("os.name").startsWith("Windows")) java = java + ".exe"; // if in a jar, extract files String classpath = System.getProperty("java.class.path"); URL testjars = getClass().getResource("testjars.txt"); if (testjars != null && testjars.toString().startsWith("jar:")) { tmpdir = FileUtils.createTempDir("jgridstart-testrun-"); BufferedReader jars = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("testjars.txt"))); String line; classpath = ""; while ( (line=jars.readLine())!=null ) { line = StringUtils.trim(line); if (line.equals("")) continue; InputStream jarin = getClass().getResourceAsStream("/"+line); if (jarin==null) throw new Exception("Incomplete tests jar file: "+line); File jaroutfile = new File(tmpdir, line); jaroutfile.deleteOnExit(); FileOutputStream jarout = new FileOutputStream(jaroutfile); byte[] b = new byte[1024]; int len; while ( (len=jarin.read(b)) != -1) jarout.write(b, 0, len); jarout.close(); jarin.close(); classpath += jaroutfile.getAbsolutePath() + System.getProperty("path.separator"); } // remove trailing ':' classpath = classpath.substring(0, classpath.length()-System.getProperty("path.separator").length()); tmpdir.deleteOnExit(); } CommandLine cmdline = new CommandLine(java); /* cmdline.addArgument("-cp"); cmdline.addArgument(classpath); cmdline.addArgument("org.junit.runner.JUnitCore"); cmdline.addArgument(testclass); */ cmdline.addArgument("-version"); DefaultExecutor exec = new DefaultExecutor(); TextareaOutputStream outputstream = new TextareaOutputStream(outputpane); exec.setStreamHandler(new PumpStreamHandler(outputstream)); exec.setProcessDestroyer(new ShutdownHookProcessDestroyer()); System.out.println(cmdline); exec.execute(cmdline, this); } catch (Exception e) { e.printStackTrace(); // TODO finish } }
void runTests() { if (exec!=null) return; try { setMessage("Please <i>don't touch</i> your mouse or keyboard while the tests are running...\n" + "(the graphical user-interface tests require this to function)"); runAction.setEnabled(false); // find java first String java = new File(new File(new File(System.getProperty("java.home")), "bin"), "java").getPath(); if (System.getProperty("os.name").startsWith("Windows")) java = java + ".exe"; // if in a jar, extract files String classpath = System.getProperty("java.class.path"); URL testjars = getClass().getResource("testjars.txt"); if (testjars != null && testjars.toString().startsWith("jar:")) { tmpdir = FileUtils.createTempDir("jgridstart-testrun-"); BufferedReader jars = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("testjars.txt"))); String line; classpath = ""; while ( (line=jars.readLine())!=null ) { line = StringUtils.trim(line); if (line.equals("")) continue; InputStream jarin = getClass().getResourceAsStream("/"+line); if (jarin==null) throw new Exception("Incomplete tests jar file: "+line); File jaroutfile = new File(tmpdir, line); jaroutfile.deleteOnExit(); FileOutputStream jarout = new FileOutputStream(jaroutfile); byte[] b = new byte[1024]; int len; while ( (len=jarin.read(b)) != -1) jarout.write(b, 0, len); jarout.close(); jarin.close(); classpath += jaroutfile.getAbsolutePath() + System.getProperty("path.separator"); } // remove trailing ':' classpath = classpath.substring(0, classpath.length()-System.getProperty("path.separator").length()); tmpdir.deleteOnExit(); } CommandLine cmdline = new CommandLine(java); cmdline.addArgument("-cp"); cmdline.addArgument(classpath); cmdline.addArgument("org.junit.runner.JUnitCore"); cmdline.addArgument(testclass); DefaultExecutor exec = new DefaultExecutor(); TextareaOutputStream outputstream = new TextareaOutputStream(outputpane); exec.setStreamHandler(new PumpStreamHandler(outputstream)); exec.setProcessDestroyer(new ShutdownHookProcessDestroyer()); System.out.println(cmdline); exec.execute(cmdline, this); } catch (Exception e) { e.printStackTrace(); // TODO finish } }
diff --git a/src/main/battlecode/world/Motor.java b/src/main/battlecode/world/Motor.java index 4436de42..6c161c5e 100644 --- a/src/main/battlecode/world/Motor.java +++ b/src/main/battlecode/world/Motor.java @@ -1,65 +1,65 @@ package battlecode.world; import battlecode.common.ComponentType; import battlecode.common.Direction; import battlecode.common.GameActionException; import battlecode.common.GameActionExceptionType; import battlecode.common.MapLocation; import battlecode.common.MovementController; import battlecode.common.TerrainTile; import battlecode.world.signal.MovementSignal; import battlecode.world.signal.SetDirectionSignal; public class Motor extends BaseComponent implements MovementController { public Motor(ComponentType type, InternalRobot robot) { super(type,robot); } public void moveForward() throws GameActionException { move(robot.getDirection()); } public void moveBackward() throws GameActionException { move(robot.getDirection().opposite()); } private void move(Direction d) throws GameActionException { assertInactive(); - assertCanMove(robot.getDirection()); + assertCanMove(d); int delay = d.isDiagonal()?robot.getChassis().moveDelayDiagonal: robot.getChassis().moveDelayOrthogonal; activate(new MovementSignal(robot,getLocation().add(d), d==getDirection(),delay),delay); } public void setDirection(Direction d) throws GameActionException { assertValidDirection(d); assertInactive(); activate(new SetDirectionSignal(robot,d),1); } public boolean canMove(Direction d) { assertValidDirection(d); return gameWorld.canMove(robot,d); } public TerrainTile senseTerrainTile(MapLocation loc) { return rc.senseTerrainTile(loc); } public void assertCanMove(Direction d) throws GameActionException { if(type==ComponentType.BUILDING_MOTOR) throw new IllegalStateException("Buildings cannot move."); if(!gameWorld.canMove(robot,d)) throw new GameActionException(GameActionExceptionType.CANT_MOVE_THERE, "Cannot move in the given direction: " + d); } public void assertValidDirection(Direction d) { assertNotNull(d); if(d==Direction.NONE||d==Direction.OMNI) throw new IllegalArgumentException("You cannot move in the direction NONE or OMNI."); } }
true
true
private void move(Direction d) throws GameActionException { assertInactive(); assertCanMove(robot.getDirection()); int delay = d.isDiagonal()?robot.getChassis().moveDelayDiagonal: robot.getChassis().moveDelayOrthogonal; activate(new MovementSignal(robot,getLocation().add(d), d==getDirection(),delay),delay); }
private void move(Direction d) throws GameActionException { assertInactive(); assertCanMove(d); int delay = d.isDiagonal()?robot.getChassis().moveDelayDiagonal: robot.getChassis().moveDelayOrthogonal; activate(new MovementSignal(robot,getLocation().add(d), d==getDirection(),delay),delay); }
diff --git a/tests/org.eclipse.birt.core.tests/test/org/eclipse/birt/core/script/ScriptableParametersTest.java b/tests/org.eclipse.birt.core.tests/test/org/eclipse/birt/core/script/ScriptableParametersTest.java index 50816b01f..96a05d9eb 100644 --- a/tests/org.eclipse.birt.core.tests/test/org/eclipse/birt/core/script/ScriptableParametersTest.java +++ b/tests/org.eclipse.birt.core.tests/test/org/eclipse/birt/core/script/ScriptableParametersTest.java @@ -1,121 +1,121 @@ /******************************************************************************* * Copyright (c) 2004 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.core.script; import java.util.Date; import java.util.HashMap; import java.util.Map; import junit.framework.TestCase; import org.eclipse.birt.core.exception.BirtException; import org.mozilla.javascript.JavaScriptException; public class ScriptableParametersTest extends TestCase { ScriptContext context; Map params; public void setUp( ) { context = new ScriptContext( ); params = new HashMap( ); addParameter( "string", "abc", "STRING VALUE" ); context.registerBean( "params", new ScriptableParameters( params, context.getScope( ) ) ); } private void addParameter( String name, Object value, String displayText ) { params.put( name, new ParameterAttribute( value, displayText ) ); } public void tearDown( ) { context.exit( ); } public void testAssign( ) throws BirtException { // change to a exits parameters context.eval( "params['string'] = 'abcd'" ); assertEquals( "abcd", context.eval( "params['string']" ) ); context.eval( "params['string'].value = 'abcde'" ); assertEquals( "abcde", context.eval( "params['string']" ) ); context.eval( "params['string'].displayText = 'display'" ); assertEquals( "display", context.eval( "params['string'].displayText" ) ); // assign to a none exist parameter will create a new entry // automatcially context.eval( "params['new param'] = 'abc'" ); assertEquals( "abc", context.eval( "params['new param']" ) ); //test case for 163786 context.eval( "params['date'] = new Date()" ); Object date = context.eval( "params['date'].value"); assertTrue(date instanceof java.util.Date); context.eval( "params['number'] = new Number(3)" ); Object num = context.eval( "params['number'].value"); assertTrue(num instanceof Double); } public void testReterive( ) throws BirtException { // access the none exist paramter will return null directl try { context.eval( "params['none exsit'] == null" ); fail( ); } - catch ( JavaScriptException e ) + catch ( BirtException e ) { assertTrue( true ); } // access the paramters from value assertEquals( "abc", context.eval( "params['string'].value" ) ); assertEquals( "bbc", context .eval( "params['string'].value.replace('a', 'b')" ) ); // access the paramters from the display text assertEquals( "STRING VALUE", context .eval( "params['string'].displayText" ) ); // access the paramters from default value assertEquals( "abc", context.eval( "params['string']" ) ); assertEquals( "bbc", context.eval( "var value = params['string'];" + "value.replace('a', 'b')" ) ); } public void testEval( ) throws BirtException { addParameter( "jsDate", "", "" ); context.eval( "params['jsDate']=new Date();" ); assertTrue( context.eval("params['jsDate'].getFullYear()") instanceof Number ); assertTrue( context.eval( "params['jsDate'].value.getFullYear()" ) instanceof Number ); addParameter( "jsString", "", "" ); context.eval( "params['jsString']='testString';" ); assertEquals( new Integer( 10 ), context .eval( "params['jsString'].length" ) ); assertEquals( new Integer( 10 ), context .eval( "params['jsString'].value.length" ) ); addParameter( "javaDate", new Date(2008, 03, 05), "" ); assertEquals( new Integer( 2008 ), context .eval( "params['javaDate'].getYear()" ) ); assertEquals( new Integer( 2008 ), context .eval( "params['javaDate'].value.getYear()" ) ); } }
true
true
public void testReterive( ) throws BirtException { // access the none exist paramter will return null directl try { context.eval( "params['none exsit'] == null" ); fail( ); } catch ( JavaScriptException e ) { assertTrue( true ); } // access the paramters from value assertEquals( "abc", context.eval( "params['string'].value" ) ); assertEquals( "bbc", context .eval( "params['string'].value.replace('a', 'b')" ) ); // access the paramters from the display text assertEquals( "STRING VALUE", context .eval( "params['string'].displayText" ) ); // access the paramters from default value assertEquals( "abc", context.eval( "params['string']" ) ); assertEquals( "bbc", context.eval( "var value = params['string'];" + "value.replace('a', 'b')" ) ); }
public void testReterive( ) throws BirtException { // access the none exist paramter will return null directl try { context.eval( "params['none exsit'] == null" ); fail( ); } catch ( BirtException e ) { assertTrue( true ); } // access the paramters from value assertEquals( "abc", context.eval( "params['string'].value" ) ); assertEquals( "bbc", context .eval( "params['string'].value.replace('a', 'b')" ) ); // access the paramters from the display text assertEquals( "STRING VALUE", context .eval( "params['string'].displayText" ) ); // access the paramters from default value assertEquals( "abc", context.eval( "params['string']" ) ); assertEquals( "bbc", context.eval( "var value = params['string'];" + "value.replace('a', 'b')" ) ); }
diff --git a/mastermind-parent/mastermind-vaadin/src/main/java/de/fichtelmax/mastermind/vaadin/MastermindUI.java b/mastermind-parent/mastermind-vaadin/src/main/java/de/fichtelmax/mastermind/vaadin/MastermindUI.java index 708e812..bbcbed7 100644 --- a/mastermind-parent/mastermind-vaadin/src/main/java/de/fichtelmax/mastermind/vaadin/MastermindUI.java +++ b/mastermind-parent/mastermind-vaadin/src/main/java/de/fichtelmax/mastermind/vaadin/MastermindUI.java @@ -1,169 +1,170 @@ package de.fichtelmax.mastermind.vaadin; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.List; import org.apache.commons.io.IOUtils; import org.vaadin.addon.extendedlabel.ExtendedContentMode; import org.vaadin.addon.extendedlabel.ExtendedLabel; import com.vaadin.annotations.Theme; import com.vaadin.annotations.Title; import com.vaadin.server.VaadinRequest; import com.vaadin.ui.Alignment; import com.vaadin.ui.Button; import com.vaadin.ui.Component; import com.vaadin.ui.GridLayout; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.Label; import com.vaadin.ui.Layout; import com.vaadin.ui.Panel; import com.vaadin.ui.UI; import com.vaadin.ui.VerticalLayout; import de.fichtelmax.mastermind.vaadin.components.ColorPickupField; import de.fichtelmax.mastermind.vaadin.components.GuessButton; import de.fichtelmax.mastermind.vaadin.components.GuessInputField; import de.fichtelmax.mastermind.vaadin.components.SolutionZone; import de.fichtelmax.mastermind.vaadin.control.MastermindController; @Theme( "mastermind" ) @Title( "Mastermind" ) public class MastermindUI extends UI { private static final long serialVersionUID = -8024776458773591101L; private final List<String> colors = Arrays.asList( "#ff4500", // red "green", // green "#ffd700", // yellow "#000080", // blue "#7b68ee", // purple "#9acd32" // yellow green ); private GuessInputField input1; private GuessInputField input2; private GuessInputField input3; private GuessInputField input4; private VerticalLayout historyContainer; @Override protected void init( VaadinRequest request ) { - Layout main = new HorizontalLayout(); + HorizontalLayout main = new HorizontalLayout(); setContent( main ); main.setSizeFull(); GridLayout game = new GridLayout( 2, 3 ); game.setMargin( true ); SolutionZone solutionZone = new SolutionZone(); Component centerZone = createCenterZone(); Component colorPickupZone = createColorPickupZone( "90px" ); List<GuessInputField> inputs = Arrays.asList( input1, input2, input3, input4 ); MastermindController controller = new MastermindController( historyContainer, inputs, colors, solutionZone ); solutionZone.setHeight( "100px" ); solutionZone.setWidth( "400px" ); game.addComponent( solutionZone, 0, 0 ); game.addComponent( centerZone, 0, 1 ); Panel colorPickup = new Panel(); colorPickup.setWidth( "100px" ); colorPickup.setHeight( "570px" ); colorPickup.setContent( colorPickupZone ); game.addComponent( colorPickup, 1, 1 ); Panel guessButtonZone = new Panel(); guessButtonZone.setWidth( "400px" ); guessButtonZone.setHeight( "100px" ); Button guessButton = new GuessButton( controller ); guessButton.setSizeFull(); guessButton.addStyleName( "guess" ); guessButtonZone.setContent( guessButton ); game.addComponent( guessButtonZone, 0, 2 ); main.addComponent( game ); + main.setComponentAlignment( game, Alignment.TOP_CENTER ); InputStream readmeStream = MastermindUI.class.getResourceAsStream( "/README.md" ); try { String readme = IOUtils.toString( readmeStream ); Label readmeLabel = new ExtendedLabel( readme, ExtendedContentMode.MARKDOWN ); main.addComponent( readmeLabel ); } catch ( IOException e ) { throw new RuntimeException( e ); } } private Component createColorPickupZone( String size ) { Layout colorPickup = new VerticalLayout(); for ( String color : colors ) { ColorPickupField colorPickupField = new ColorPickupField( color ); colorPickupField.setWidth( size ); colorPickupField.setHeight( size ); colorPickup.addComponent( colorPickupField ); } return colorPickup; } private Component createCenterZone() { VerticalLayout centerLayout = new VerticalLayout(); centerLayout.setSizeFull(); centerLayout.addComponent( createHistoryZone() ); Component inputZone = createGuessInputZone(); centerLayout.addComponent( inputZone ); centerLayout.setComponentAlignment( inputZone, Alignment.BOTTOM_CENTER ); Panel centerPanel = new Panel(); centerPanel.setWidth( "400px" ); centerPanel.setHeight( "570px" ); centerPanel.setContent( centerLayout ); return centerPanel; } private Component createHistoryZone() { historyContainer = new VerticalLayout(); // needed for scroll support Panel historyZone = new Panel(); historyZone.setContent( historyContainer ); historyZone.setHeight( "470px" ); return historyZone; } private Component createGuessInputZone() { HorizontalLayout guessInput = new HorizontalLayout(); input1 = new GuessInputField(); input2 = new GuessInputField(); input3 = new GuessInputField(); input4 = new GuessInputField(); guessInput.addComponent( input1 ); guessInput.addComponent( input2 ); guessInput.addComponent( input3 ); guessInput.addComponent( input4 ); return guessInput; } }
false
true
protected void init( VaadinRequest request ) { Layout main = new HorizontalLayout(); setContent( main ); main.setSizeFull(); GridLayout game = new GridLayout( 2, 3 ); game.setMargin( true ); SolutionZone solutionZone = new SolutionZone(); Component centerZone = createCenterZone(); Component colorPickupZone = createColorPickupZone( "90px" ); List<GuessInputField> inputs = Arrays.asList( input1, input2, input3, input4 ); MastermindController controller = new MastermindController( historyContainer, inputs, colors, solutionZone ); solutionZone.setHeight( "100px" ); solutionZone.setWidth( "400px" ); game.addComponent( solutionZone, 0, 0 ); game.addComponent( centerZone, 0, 1 ); Panel colorPickup = new Panel(); colorPickup.setWidth( "100px" ); colorPickup.setHeight( "570px" ); colorPickup.setContent( colorPickupZone ); game.addComponent( colorPickup, 1, 1 ); Panel guessButtonZone = new Panel(); guessButtonZone.setWidth( "400px" ); guessButtonZone.setHeight( "100px" ); Button guessButton = new GuessButton( controller ); guessButton.setSizeFull(); guessButton.addStyleName( "guess" ); guessButtonZone.setContent( guessButton ); game.addComponent( guessButtonZone, 0, 2 ); main.addComponent( game ); InputStream readmeStream = MastermindUI.class.getResourceAsStream( "/README.md" ); try { String readme = IOUtils.toString( readmeStream ); Label readmeLabel = new ExtendedLabel( readme, ExtendedContentMode.MARKDOWN ); main.addComponent( readmeLabel ); } catch ( IOException e ) { throw new RuntimeException( e ); } }
protected void init( VaadinRequest request ) { HorizontalLayout main = new HorizontalLayout(); setContent( main ); main.setSizeFull(); GridLayout game = new GridLayout( 2, 3 ); game.setMargin( true ); SolutionZone solutionZone = new SolutionZone(); Component centerZone = createCenterZone(); Component colorPickupZone = createColorPickupZone( "90px" ); List<GuessInputField> inputs = Arrays.asList( input1, input2, input3, input4 ); MastermindController controller = new MastermindController( historyContainer, inputs, colors, solutionZone ); solutionZone.setHeight( "100px" ); solutionZone.setWidth( "400px" ); game.addComponent( solutionZone, 0, 0 ); game.addComponent( centerZone, 0, 1 ); Panel colorPickup = new Panel(); colorPickup.setWidth( "100px" ); colorPickup.setHeight( "570px" ); colorPickup.setContent( colorPickupZone ); game.addComponent( colorPickup, 1, 1 ); Panel guessButtonZone = new Panel(); guessButtonZone.setWidth( "400px" ); guessButtonZone.setHeight( "100px" ); Button guessButton = new GuessButton( controller ); guessButton.setSizeFull(); guessButton.addStyleName( "guess" ); guessButtonZone.setContent( guessButton ); game.addComponent( guessButtonZone, 0, 2 ); main.addComponent( game ); main.setComponentAlignment( game, Alignment.TOP_CENTER ); InputStream readmeStream = MastermindUI.class.getResourceAsStream( "/README.md" ); try { String readme = IOUtils.toString( readmeStream ); Label readmeLabel = new ExtendedLabel( readme, ExtendedContentMode.MARKDOWN ); main.addComponent( readmeLabel ); } catch ( IOException e ) { throw new RuntimeException( e ); } }
diff --git a/src/main/java/ru/redcraft/pinterest4j/core/api/UserAPI.java b/src/main/java/ru/redcraft/pinterest4j/core/api/UserAPI.java index 70f1a0d..6c96cc2 100644 --- a/src/main/java/ru/redcraft/pinterest4j/core/api/UserAPI.java +++ b/src/main/java/ru/redcraft/pinterest4j/core/api/UserAPI.java @@ -1,282 +1,282 @@ package ru.redcraft.pinterest4j.core.api; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.ws.rs.core.MediaType; import org.apache.log4j.Logger; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import ru.redcraft.pinterest4j.Activity; import ru.redcraft.pinterest4j.Activity.ActivityType; import ru.redcraft.pinterest4j.Board; import ru.redcraft.pinterest4j.Followable; import ru.redcraft.pinterest4j.NewUserSettings; import ru.redcraft.pinterest4j.Pin; import ru.redcraft.pinterest4j.User; import ru.redcraft.pinterest4j.core.activities.CommentActivity; import ru.redcraft.pinterest4j.core.activities.CreateBoardActivity; import ru.redcraft.pinterest4j.core.activities.FollowBoardActivity; import ru.redcraft.pinterest4j.core.activities.FollowUserActivity; import ru.redcraft.pinterest4j.core.activities.PinActivity; import ru.redcraft.pinterest4j.core.api.AdditionalUserSettings.Gender; import ru.redcraft.pinterest4j.core.api.FollowCollection.FollowContainer; import ru.redcraft.pinterest4j.core.api.FollowCollection.FollowType; import ru.redcraft.pinterest4j.exceptions.PinterestRuntimeException; import ru.redcraft.pinterest4j.exceptions.PinterestUserNotFoundException; import com.sun.jersey.api.client.ClientResponse.Status; import com.sun.jersey.multipart.FormDataBodyPart; import com.sun.jersey.multipart.FormDataMultiPart; public class UserAPI extends CoreAPI { private static final String USER_FOLLOWING_PROP_NAME = "pinterestapp:following"; private static final String USER_FOLLOWERS_PROP_NAME = "pinterestapp:followers"; private static final String USER_BOARDS_PROP_NAME = "pinterestapp:boards"; private static final String USER_PINS_PROP_NAME = "pinterestapp:pins"; private static final String USER_IMAGE_PROP_NAME = "og:image"; private static final Logger LOG = Logger.getLogger(UserAPI.class); private static final String USER_API_ERROR = "USER API ERROR: "; UserAPI(PinterestAccessToken accessToken, InternalAPIManager apiManager) { super(accessToken, apiManager); } private Document getUserInfoPage(String userName) { return new APIRequestBuilder(userName + "/") .addExceptionMapping(Status.NOT_FOUND, new PinterestUserNotFoundException(userName)) .setErrorMessage(USER_API_ERROR) .build().getDocument(); } public UserBuilder getCompleteUser(String userName) { LOG.debug("Getting all info for username " + userName); UserBuilder builder = new UserBuilder(); builder.setUserName(userName); Document doc = getUserInfoPage(userName); Map<String, String> metaMap = new HashMap<String, String>(); for(Element meta : doc.select("meta")) { metaMap.put(meta.attr("property"), meta.attr("content")); } builder.setFollowingCount(Integer.valueOf(metaMap.get(USER_FOLLOWING_PROP_NAME))); builder.setFollowersCount(Integer.valueOf(metaMap.get(USER_FOLLOWERS_PROP_NAME))); builder.setBoardsCount(Integer.valueOf(metaMap.get(USER_BOARDS_PROP_NAME))); builder.setPinsCount(Integer.valueOf(metaMap.get(USER_PINS_PROP_NAME))); builder.setImageURL(metaMap.get(USER_IMAGE_PROP_NAME)); Element userInfo = doc.select("div.content").first(); builder.setFullName(userInfo.getElementsByTag("h1").first().text()); Element description = userInfo.getElementsByTag("p").first(); builder.setDescription(description != null ? description.text() : null); Element twitter = userInfo.select("a.twitter").first(); builder.setTwitterURL(twitter != null ? twitter.attr(HREF_TAG_ATTR) : null); Element facebook = userInfo.select("a.facebook").first(); builder.setFacebookURL(facebook != null ? facebook.attr(HREF_TAG_ATTR) : null); Element website = userInfo.select("a.website").first(); builder.setSiteURL(website != null ? website.attr(HREF_TAG_ATTR) : null); Element location = userInfo.select("li#ProfileLocation").first(); builder.setLocation(location != null ? location.text() : null); builder.setLikesCount(Integer.valueOf(doc.select("div#ContextBar").first().getElementsByTag("li").get(2).getElementsByTag("strong").first().text())); return builder; } public User getUserForName(String userName) { return new LazyUser(getCompleteUser(userName), getApiManager()); } private AdditionalUserSettings getUserAdtSettings() { AdditionalUserSettings adtSettings = new AdditionalUserSettings(); Document doc = new APIRequestBuilder("settings/") .setProtocol(Protocol.HTTPS) .setAjaxUsage(false) .setErrorMessage(USER_API_ERROR) .build().getDocument(); adtSettings.setEmail(doc.getElementById("id_email").attr(VALUE_TAG_ATTR)); adtSettings.setFirstName(doc.getElementById("id_first_name").attr(VALUE_TAG_ATTR)); adtSettings.setLastName(doc.getElementById("id_last_name").attr(VALUE_TAG_ATTR)); adtSettings.setUserName(doc.getElementById("id_username").attr(VALUE_TAG_ATTR)); adtSettings.setWebsite(doc.getElementById("id_website").attr(VALUE_TAG_ATTR)); adtSettings.setLocation(doc.getElementById("id_location").attr(VALUE_TAG_ATTR)); if(doc.getElementById("id_gender_0").hasAttr(UserAPI.CHECKED_TAG_ATTR)) { adtSettings.setGender(Gender.MALE); } if(doc.getElementById("id_gender_1").hasAttr(UserAPI.CHECKED_TAG_ATTR)) { adtSettings.setGender(Gender.FEMALE); } if(doc.getElementById("id_gender_2").hasAttr(UserAPI.CHECKED_TAG_ATTR)) { adtSettings.setGender(Gender.UNSPECIFIED); } return adtSettings; } private FormDataMultiPart createUserForm(NewUserSettings settings) { FormDataMultiPart multipartForm = new FormDataMultiPart(); AdditionalUserSettings adtSettings = getUserAdtSettings(); multipartForm.bodyPart(new FormDataBodyPart("csrfmiddlewaretoken", getAccessToken().getCsrfToken().getValue())); multipartForm.bodyPart(new FormDataBodyPart("email", adtSettings.getEmail())); multipartForm.bodyPart(new FormDataBodyPart("gender", adtSettings.getGender().name().toLowerCase(PINTEREST_LOCALE))); multipartForm.bodyPart(new FormDataBodyPart("username", adtSettings.getUserName())); multipartForm.bodyPart(new FormDataBodyPart("first_name", settings.getFirstName() != null ? settings.getFirstName() : adtSettings.getFirstName())); multipartForm.bodyPart(new FormDataBodyPart("last_name", settings.getLastName() != null ? settings.getLastName() : adtSettings.getLastName())); if(settings.getWebsite() != null || adtSettings.getWebsite() != null) { multipartForm.bodyPart(new FormDataBodyPart("website", settings.getWebsite() != null ? settings.getWebsite() : adtSettings.getWebsite())); } if(settings.getLocation() != null || adtSettings.getLocation() != null) { multipartForm.bodyPart(new FormDataBodyPart("location", settings.getLocation() != null ? settings.getLocation() : adtSettings.getLocation())); } if(settings.getAbout() != null) { multipartForm.bodyPart(new FormDataBodyPart("about", settings.getAbout())); } if(settings.getImage() != null) { multipartForm.bodyPart(createImageBodyPart(settings.getImage())); } return multipartForm; } public User updateUser(NewUserSettings settings) { LOG.debug(String.format("Updating user=%s with settings=%s", getAccessToken().getLogin(), settings)); new APIRequestBuilder("settings/") .setProtocol(Protocol.HTTPS) .setAjaxUsage(false) .setMethod(Method.POST, createUserForm(settings)) .setMediaType(MediaType.MULTIPART_FORM_DATA_TYPE) .setHttpSuccessStatus(Status.FOUND) .setErrorMessage(USER_API_ERROR) .build(); User newUser = getUserForName(getAccessToken().getLogin()); LOG.debug("User updated. New user info: " + newUser); return newUser; } public void followUser(User user, boolean follow) { LOG.debug(String.format("Setting follow on user = %s to = %s", user, follow)); new APIRequestBuilder(user.getUserName() + "/follow/") .setMethod(Method.POST, getSwitchForm("unfollow", follow)) .setErrorMessage(USER_API_ERROR) .build().getResponse(); LOG.debug("Board follow mark set to " + follow); } public boolean isFollowing(User user) { LOG.debug("Checking following status for user=" + user); boolean followed = false; if(getUserInfoPage(user.getUserName()).select("a.unfollowuserbutton").size() == 1) { followed = true; } LOG.debug("Following state is " + followed); return followed; } public FollowContainer getFollow(Followable followable, FollowType followType, int page, long marker) { LOG.debug(String.format("Getting follows of type=%s for followable=%s on page=%d with marker=%d", followType.name(), followable, page, marker)); String path = null; if(page != 1) { path = String.format("%s/?page=%d&marker=%d", followType.name().toLowerCase(PINTEREST_LOCALE), page, marker); } else { path = followType.name().toLowerCase(PINTEREST_LOCALE) + "/?page=1"; } String entity = new APIRequestBuilder(followable.getURL() + path) .setErrorMessage(USER_API_ERROR) .build().getResponse().getEntity(String.class); long newMarker = 0; Pattern pattern = Pattern.compile("\"marker\": (-?[0-9]+)"); Matcher m = pattern.matcher(entity); if (m.find()) { newMarker = Long.valueOf(m.group(1)); } else { pattern = Pattern.compile("settings.marker = (-?[0-9]+)"); m = pattern.matcher(entity); if (m.find()) { newMarker = Long.valueOf(m.group(1)); } else { throw new PinterestRuntimeException(USER_API_ERROR + "follow marker parsing error"); } } List<User> users = new ArrayList<User>(); Document doc = Jsoup.parse(entity); for(Element userElement : doc.select("div.PersonInfo")) { User user = new LazyUser(userElement.getElementsByTag("a").first().attr(HREF_TAG_ATTR).replace("/", ""), getApiManager()); users.add(user); } FollowContainer container = new FollowContainer(newMarker, users); LOG.debug("Container with follow created: " + container); return container; } public List<Activity> getActivity(User user) { LOG.debug("Getting activity for user = " + user); List<Activity> activities = new ArrayList<Activity>(); Document doc = new APIRequestBuilder(user.getURL() + "activity") .setErrorMessage(USER_API_ERROR) .build().getDocument(); for(Element activity : doc.select("div.activity")) { Set<String> types = activity.classNames(); if(types.contains("activity-1")) { activities.add(new PinActivity(ActivityType.PIN, new LazyPin(Long.valueOf(activity.attr(DATA_ID_TAG_ATTR)), getApiManager()))); } else if(types.contains("activity-5")) { activities.add(new PinActivity(ActivityType.REPIN, new LazyPin(Long.valueOf(activity.attr(DATA_ID_TAG_ATTR)), getApiManager()))); } else if(types.contains("activity-6")) { activities.add(new PinActivity(ActivityType.LIKE, new LazyPin(Long.valueOf(activity.attr(DATA_ID_TAG_ATTR)), getApiManager()))); } else if(types.contains("activity-7")) { - Pattern pattern = Pattern.compile("“(.*?).“"); + Pattern pattern = Pattern.compile("“(.*?).”"); String info = activity.select("div.info").first().text(); Matcher m = pattern.matcher(info); if (m.find()) { String commentMsg = m.group(1); Pin pin = new LazyPin(Long.valueOf(activity.attr(DATA_ID_TAG_ATTR)), getApiManager()); activities.add(new CommentActivity(pin, commentMsg)); } } else if(types.contains("activity-45")) { activities.add(new FollowUserActivity(new LazyUser((activity.getElementsByTag("a").attr(HREF_TAG_ATTR).replace("/", "")), getApiManager()))); } else if(types.contains("activity-26")) { Board board = new LazyBoard(activity.getElementsByTag("a").attr(HREF_TAG_ATTR), getApiManager()); Pattern pattern = Pattern.compile("Followed"); String info = activity.select("div.info").first().text(); Matcher m = pattern.matcher(info); if (m.find()) { activities.add(new FollowBoardActivity(board)); } else { activities.add(new CreateBoardActivity(board)); } } } LOG.debug("User activity is: " + activities); return activities; } }
true
true
public List<Activity> getActivity(User user) { LOG.debug("Getting activity for user = " + user); List<Activity> activities = new ArrayList<Activity>(); Document doc = new APIRequestBuilder(user.getURL() + "activity") .setErrorMessage(USER_API_ERROR) .build().getDocument(); for(Element activity : doc.select("div.activity")) { Set<String> types = activity.classNames(); if(types.contains("activity-1")) { activities.add(new PinActivity(ActivityType.PIN, new LazyPin(Long.valueOf(activity.attr(DATA_ID_TAG_ATTR)), getApiManager()))); } else if(types.contains("activity-5")) { activities.add(new PinActivity(ActivityType.REPIN, new LazyPin(Long.valueOf(activity.attr(DATA_ID_TAG_ATTR)), getApiManager()))); } else if(types.contains("activity-6")) { activities.add(new PinActivity(ActivityType.LIKE, new LazyPin(Long.valueOf(activity.attr(DATA_ID_TAG_ATTR)), getApiManager()))); } else if(types.contains("activity-7")) { Pattern pattern = Pattern.compile("“(.*?).“"); String info = activity.select("div.info").first().text(); Matcher m = pattern.matcher(info); if (m.find()) { String commentMsg = m.group(1); Pin pin = new LazyPin(Long.valueOf(activity.attr(DATA_ID_TAG_ATTR)), getApiManager()); activities.add(new CommentActivity(pin, commentMsg)); } } else if(types.contains("activity-45")) { activities.add(new FollowUserActivity(new LazyUser((activity.getElementsByTag("a").attr(HREF_TAG_ATTR).replace("/", "")), getApiManager()))); } else if(types.contains("activity-26")) { Board board = new LazyBoard(activity.getElementsByTag("a").attr(HREF_TAG_ATTR), getApiManager()); Pattern pattern = Pattern.compile("Followed"); String info = activity.select("div.info").first().text(); Matcher m = pattern.matcher(info); if (m.find()) { activities.add(new FollowBoardActivity(board)); } else { activities.add(new CreateBoardActivity(board)); } } } LOG.debug("User activity is: " + activities); return activities; }
public List<Activity> getActivity(User user) { LOG.debug("Getting activity for user = " + user); List<Activity> activities = new ArrayList<Activity>(); Document doc = new APIRequestBuilder(user.getURL() + "activity") .setErrorMessage(USER_API_ERROR) .build().getDocument(); for(Element activity : doc.select("div.activity")) { Set<String> types = activity.classNames(); if(types.contains("activity-1")) { activities.add(new PinActivity(ActivityType.PIN, new LazyPin(Long.valueOf(activity.attr(DATA_ID_TAG_ATTR)), getApiManager()))); } else if(types.contains("activity-5")) { activities.add(new PinActivity(ActivityType.REPIN, new LazyPin(Long.valueOf(activity.attr(DATA_ID_TAG_ATTR)), getApiManager()))); } else if(types.contains("activity-6")) { activities.add(new PinActivity(ActivityType.LIKE, new LazyPin(Long.valueOf(activity.attr(DATA_ID_TAG_ATTR)), getApiManager()))); } else if(types.contains("activity-7")) { Pattern pattern = Pattern.compile("“(.*?).”"); String info = activity.select("div.info").first().text(); Matcher m = pattern.matcher(info); if (m.find()) { String commentMsg = m.group(1); Pin pin = new LazyPin(Long.valueOf(activity.attr(DATA_ID_TAG_ATTR)), getApiManager()); activities.add(new CommentActivity(pin, commentMsg)); } } else if(types.contains("activity-45")) { activities.add(new FollowUserActivity(new LazyUser((activity.getElementsByTag("a").attr(HREF_TAG_ATTR).replace("/", "")), getApiManager()))); } else if(types.contains("activity-26")) { Board board = new LazyBoard(activity.getElementsByTag("a").attr(HREF_TAG_ATTR), getApiManager()); Pattern pattern = Pattern.compile("Followed"); String info = activity.select("div.info").first().text(); Matcher m = pattern.matcher(info); if (m.find()) { activities.add(new FollowBoardActivity(board)); } else { activities.add(new CreateBoardActivity(board)); } } } LOG.debug("User activity is: " + activities); return activities; }
diff --git a/Net/src/edu/uw/cs/cse461/Net/RPC/RPCCall.java b/Net/src/edu/uw/cs/cse461/Net/RPC/RPCCall.java index 77bfd29..682e434 100644 --- a/Net/src/edu/uw/cs/cse461/Net/RPC/RPCCall.java +++ b/Net/src/edu/uw/cs/cse461/Net/RPC/RPCCall.java @@ -1,176 +1,174 @@ package edu.uw.cs.cse461.Net.RPC; import java.io.IOException; import java.net.Socket; import java.util.HashMap; import java.util.LinkedList; import java.util.Timer; import java.util.TimerTask; import org.json.JSONException; import org.json.JSONObject; import edu.uw.cs.cse461.Net.Base.NetBase; import edu.uw.cs.cse461.Net.Base.NetLoadable.NetLoadableService; import edu.uw.cs.cse461.Net.TCPMessageHandler.TCPMessageHandler; import edu.uw.cs.cse461.util.Log; /** * Class implementing the caller side of RPC -- the RPCCall.invoke() method. * The invoke() method itself is static, for the convenience of the callers, * but this class is a normal, loadable, service. * <p> * <p> * This class is responsible for implementing persistent connections. * (What you might think of as the actual remote call code is in RCPCallerSocket.java.) * Implementing persistence requires keeping a cache that must be cleaned periodically. * We do that using a cleaner thread. * * @author zahorjan * */ public class RPCCall extends NetLoadableService { private static final String TAG="RPCCall"; //------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------- // The static versions of invoke() is just a convenience for caller's -- it // makes sure the RPCCall service is actually running, and then invokes the // the code that actually implements invoke. /** * Invokes method() on serviceName located on remote host ip:port. * @param ip Remote host's ip address * @param port RPC service port on remote host * @param serviceName Name of service to be invoked * @param method Name of method of the service to invoke * @param userRequest Arguments to call * @return Returns whatever the remote method returns. * @throws JSONException * @throws IOException */ public static JSONObject invoke( String ip, // ip or dns name of remote host int port, // port that RPC is listening on on the remote host String serviceName, // name of the remote service String method, // name of that service's method to invoke JSONObject userRequest // arguments to send to remote method ) throws JSONException, IOException { RPCCall rpcCallObj = (RPCCall)NetBase.theNetBase().getService( "rpccall" ); if ( rpcCallObj == null ) throw new IOException("RPCCall.invoke() called but the RPCCall service isn't loaded"); return rpcCallObj._invoke(ip, port, serviceName, method, userRequest, true); } //------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------- /** * The infrastructure requires a public constructor taking no arguments. Plus, we need a constructor. */ public RPCCall() { super("rpccall", true); } /** * This private method performs the actual invocation, including the management of persistent connections. * * @param ip * @param port * @param serviceName * @param method * @param userRequest * @return * @throws JSONException * @throws IOException */ private JSONObject _invoke( String ip, // ip or dns name of remote host int port, // port that RPC is listening on on the remote host String serviceName, // name of the remote service String method, // name of that service's method to invoke JSONObject userRequest, // arguments to send to remote method boolean tryAgain // true if an invocation failure on a persistent connection should cause a re-try of the call, false to give up ) throws JSONException, IOException { Socket socket = new Socket(ip, port); TCPMessageHandler handler = new TCPMessageHandler(socket); JSONObject handshake = new JSONObject(); int callid = 5; // This choice is arbitrary TODO figure out a better id handshake.put("id", callid); handshake.put("host", ip); handshake.put("action", "connect"); handshake.put("type", "control"); // If a persistent connection is possible, this is where code would be added // Extra credit TODO Log.d(TAG, "Sending handshake to service"); handler.sendMessage(handshake); Log.d(TAG, "Attempting to receive response to handshake"); JSONObject response = handler.readMessageAsJSONObject(); String result = response.getString("type"); // If an error occurs, we want to be informed of it and stop executing this message. if (result.equals("ERROR")) { return response; } else if (result.equals("OK")) { // Makes sure that the response we are receiving was actually for the handshake we sent if (response.getInt("callid") != callid) { Log.e(TAG, "Received a response from the server with the wrong callid number"); Log.e(TAG, response.toString()); return response; } Log.d(TAG, "Handshake successful"); } // If we have reached this point, we know that the handshake was successful, so it is safe to send the user's message. JSONObject call = new JSONObject(); call.put("type", "invoke"); call.put("id", callid*2); call.put("app", serviceName); call.put("method", method); call.put("host", ip); - JSONObject message = new JSONObject(); - message.put("msg", userRequest); - call.put("args", message); + call.put("args", userRequest); Log.d(TAG, "Attempting to send the call"); handler.sendMessage(call); Log.d(TAG, "Attempting to receive a response"); response = handler.readMessageAsJSONObject(); // Makes sure that the response we are receiving was actually for the call we sent if (response.getInt("callid") != callid*2) { Log.e(TAG, "Received a response to the call from the server with the wrong callid number"); return null; } else { result = response.getString("type"); if (result.equals("ERROR")) { Log.e(TAG, "Error received: " + response.get("message").toString()); Log.e(TAG, "on message " + response.getJSONObject("callargs").toString()); return null; } else { Log.d(TAG, response.toString()); return response.getJSONObject("value"); } } } /** * Called when entire infrastructure is coming down. */ @Override public void shutdown() { } /** * Called when some client wants a representation of this server's state. * (Mainly useful for debugging.) */ @Override public String dumpState() { return "Current peristed connections are ..."; } }
true
true
private JSONObject _invoke( String ip, // ip or dns name of remote host int port, // port that RPC is listening on on the remote host String serviceName, // name of the remote service String method, // name of that service's method to invoke JSONObject userRequest, // arguments to send to remote method boolean tryAgain // true if an invocation failure on a persistent connection should cause a re-try of the call, false to give up ) throws JSONException, IOException { Socket socket = new Socket(ip, port); TCPMessageHandler handler = new TCPMessageHandler(socket); JSONObject handshake = new JSONObject(); int callid = 5; // This choice is arbitrary TODO figure out a better id handshake.put("id", callid); handshake.put("host", ip); handshake.put("action", "connect"); handshake.put("type", "control"); // If a persistent connection is possible, this is where code would be added // Extra credit TODO Log.d(TAG, "Sending handshake to service"); handler.sendMessage(handshake); Log.d(TAG, "Attempting to receive response to handshake"); JSONObject response = handler.readMessageAsJSONObject(); String result = response.getString("type"); // If an error occurs, we want to be informed of it and stop executing this message. if (result.equals("ERROR")) { return response; } else if (result.equals("OK")) { // Makes sure that the response we are receiving was actually for the handshake we sent if (response.getInt("callid") != callid) { Log.e(TAG, "Received a response from the server with the wrong callid number"); Log.e(TAG, response.toString()); return response; } Log.d(TAG, "Handshake successful"); } // If we have reached this point, we know that the handshake was successful, so it is safe to send the user's message. JSONObject call = new JSONObject(); call.put("type", "invoke"); call.put("id", callid*2); call.put("app", serviceName); call.put("method", method); call.put("host", ip); JSONObject message = new JSONObject(); message.put("msg", userRequest); call.put("args", message); Log.d(TAG, "Attempting to send the call"); handler.sendMessage(call); Log.d(TAG, "Attempting to receive a response"); response = handler.readMessageAsJSONObject(); // Makes sure that the response we are receiving was actually for the call we sent if (response.getInt("callid") != callid*2) { Log.e(TAG, "Received a response to the call from the server with the wrong callid number"); return null; } else { result = response.getString("type"); if (result.equals("ERROR")) { Log.e(TAG, "Error received: " + response.get("message").toString()); Log.e(TAG, "on message " + response.getJSONObject("callargs").toString()); return null; } else { Log.d(TAG, response.toString()); return response.getJSONObject("value"); } } }
private JSONObject _invoke( String ip, // ip or dns name of remote host int port, // port that RPC is listening on on the remote host String serviceName, // name of the remote service String method, // name of that service's method to invoke JSONObject userRequest, // arguments to send to remote method boolean tryAgain // true if an invocation failure on a persistent connection should cause a re-try of the call, false to give up ) throws JSONException, IOException { Socket socket = new Socket(ip, port); TCPMessageHandler handler = new TCPMessageHandler(socket); JSONObject handshake = new JSONObject(); int callid = 5; // This choice is arbitrary TODO figure out a better id handshake.put("id", callid); handshake.put("host", ip); handshake.put("action", "connect"); handshake.put("type", "control"); // If a persistent connection is possible, this is where code would be added // Extra credit TODO Log.d(TAG, "Sending handshake to service"); handler.sendMessage(handshake); Log.d(TAG, "Attempting to receive response to handshake"); JSONObject response = handler.readMessageAsJSONObject(); String result = response.getString("type"); // If an error occurs, we want to be informed of it and stop executing this message. if (result.equals("ERROR")) { return response; } else if (result.equals("OK")) { // Makes sure that the response we are receiving was actually for the handshake we sent if (response.getInt("callid") != callid) { Log.e(TAG, "Received a response from the server with the wrong callid number"); Log.e(TAG, response.toString()); return response; } Log.d(TAG, "Handshake successful"); } // If we have reached this point, we know that the handshake was successful, so it is safe to send the user's message. JSONObject call = new JSONObject(); call.put("type", "invoke"); call.put("id", callid*2); call.put("app", serviceName); call.put("method", method); call.put("host", ip); call.put("args", userRequest); Log.d(TAG, "Attempting to send the call"); handler.sendMessage(call); Log.d(TAG, "Attempting to receive a response"); response = handler.readMessageAsJSONObject(); // Makes sure that the response we are receiving was actually for the call we sent if (response.getInt("callid") != callid*2) { Log.e(TAG, "Received a response to the call from the server with the wrong callid number"); return null; } else { result = response.getString("type"); if (result.equals("ERROR")) { Log.e(TAG, "Error received: " + response.get("message").toString()); Log.e(TAG, "on message " + response.getJSONObject("callargs").toString()); return null; } else { Log.d(TAG, response.toString()); return response.getJSONObject("value"); } } }
diff --git a/core/src/main/java/org/mule/galaxy/impl/jcr/UserDetailsWrapper.java b/core/src/main/java/org/mule/galaxy/impl/jcr/UserDetailsWrapper.java index 1418e857..2ecff3d5 100755 --- a/core/src/main/java/org/mule/galaxy/impl/jcr/UserDetailsWrapper.java +++ b/core/src/main/java/org/mule/galaxy/impl/jcr/UserDetailsWrapper.java @@ -1,108 +1,108 @@ package org.mule.galaxy.impl.jcr; import java.util.ArrayList; import java.util.Arrays; import java.util.Set; import javax.naming.directory.Attributes; import javax.naming.ldap.Control; import org.acegisecurity.GrantedAuthority; import org.acegisecurity.GrantedAuthorityImpl; import org.acegisecurity.userdetails.ldap.LdapUserDetails; import org.mule.galaxy.security.Permission; import org.mule.galaxy.security.User; public class UserDetailsWrapper implements LdapUserDetails { private User user; private String password; private Set<Permission> permissions; private GrantedAuthority[] authorities; private Attributes attributes; private Control[] controls; private String userDn; public UserDetailsWrapper(User user, Set<Permission> set, String password) { super(); this.user = user; this.permissions = set; this.password = password; } public User getUser() { return user; } public GrantedAuthority[] getAuthorities() { if (authorities == null) { Object[] pArray = permissions.toArray(); authorities = new GrantedAuthority[pArray.length+1]; for (int i = 0; i < pArray.length; i++) { authorities[i] = new GrantedAuthorityImpl(pArray[i].toString()); } - authorities[pArray.length+1] = new GrantedAuthorityImpl("role_user"); + authorities[pArray.length] = new GrantedAuthorityImpl("role_user"); } return authorities; } public String getPassword() { return password; } public String getUsername() { return user.getUsername(); } public boolean isAccountNonExpired() { return user.isEnabled(); } public boolean isAccountNonLocked() { return user.isEnabled(); } public boolean isCredentialsNonExpired() { return user.isEnabled(); } public boolean isEnabled() { // TODO Auto-generated method stub return user.isEnabled(); } public Attributes getAttributes() { return attributes; } public void setAttributes(Attributes attributes) { this.attributes = attributes; } public Control[] getControls() { return controls; } public void setControls(Control[] controls) { this.controls = controls; } public String getDn() { return userDn; } public void setDn(String dn) { userDn = dn; } public void setAuthorities(GrantedAuthority[] auths) { ArrayList list = new ArrayList(Arrays.asList(auths)); list.add(new GrantedAuthorityImpl("role_user")); authorities = (GrantedAuthority[]) list.toArray(new GrantedAuthority[0]); } public void setPermissions(Set<Permission> set) { permissions = set; } }
true
true
public GrantedAuthority[] getAuthorities() { if (authorities == null) { Object[] pArray = permissions.toArray(); authorities = new GrantedAuthority[pArray.length+1]; for (int i = 0; i < pArray.length; i++) { authorities[i] = new GrantedAuthorityImpl(pArray[i].toString()); } authorities[pArray.length+1] = new GrantedAuthorityImpl("role_user"); } return authorities; }
public GrantedAuthority[] getAuthorities() { if (authorities == null) { Object[] pArray = permissions.toArray(); authorities = new GrantedAuthority[pArray.length+1]; for (int i = 0; i < pArray.length; i++) { authorities[i] = new GrantedAuthorityImpl(pArray[i].toString()); } authorities[pArray.length] = new GrantedAuthorityImpl("role_user"); } return authorities; }
diff --git a/q-web/src/main/java/q/web/weibo/GetWeibo.java b/q-web/src/main/java/q/web/weibo/GetWeibo.java index ffdc6407..e5713da0 100644 --- a/q-web/src/main/java/q/web/weibo/GetWeibo.java +++ b/q-web/src/main/java/q/web/weibo/GetWeibo.java @@ -1,116 +1,118 @@ /** * */ package q.web.weibo; import java.util.HashMap; import java.util.List; import java.util.Map; import q.dao.DaoHelper; import q.dao.FavoriteDao; import q.dao.GroupDao; import q.dao.PeopleDao; import q.dao.WeiboDao; import q.dao.page.WeiboReplyPage; import q.domain.Weibo; import q.domain.WeiboReply; import q.util.CollectionKit; import q.util.IdCreator; import q.web.Resource; import q.web.ResourceContext; import q.web.exception.RequestParameterInvalidException; /** * @author seanlinwang * @email xalinx at gmail dot com * @date Feb 22, 2011 * */ public class GetWeibo extends Resource { private WeiboDao weiboDao; public void setWeiboDao(WeiboDao weiboDao) { this.weiboDao = weiboDao; } private PeopleDao peopleDao; public void setPeopleDao(PeopleDao peopleDao) { this.peopleDao = peopleDao; } private GroupDao groupDao; public void setGroupDao(GroupDao groupDao) { this.groupDao = groupDao; } private FavoriteDao favoriteDao; public void setFavoriteDao(FavoriteDao favoriteDao) { this.favoriteDao = favoriteDao; } /* * (non-Javadoc) * * @see q.web.Resource#execute(q.web.ResourceContext) */ @Override public void execute(ResourceContext context) throws Exception { long weiboId = context.getResourceIdLong(); long loginPeopleId = context.getCookiePeopleId(); Weibo weibo = weiboDao.getWeiboById(weiboId); - DaoHelper.injectWeiboModelWithQuote(weiboDao, weibo); + if(weibo.getQuoteWeiboId() > 0) { + DaoHelper.injectWeiboModelWithQuote(weiboDao, weibo); + } DaoHelper.injectWeiboModelWithPeople(peopleDao, weibo); DaoHelper.injectWeiboModelWithFrom(groupDao, weibo); if (loginPeopleId > 0) { DaoHelper.injectWeiboWithFavorite(favoriteDao, weibo, loginPeopleId); } context.setModel("weibo", weibo); WeiboReplyPage page = new WeiboReplyPage(); page.setQuoteWeiboId(weiboId); int size = context.getInt("size", 10); long startId = context.getIdLong("startId"); page.setSize(size); page.setStartIndex(0); if (startId > 0) { page.setStartId(startId); } List<WeiboReply> replies = weiboDao.getWeiboRepliesByPage(page); if (CollectionKit.isNotEmpty(replies)) { DaoHelper.injectWeiboModelsWithPeople(peopleDao, replies); DaoHelper.injectWeiboModelsWithFrom(groupDao, replies); if (loginPeopleId > 0) { DaoHelper.injectWeiboModelsWithFavorite(favoriteDao, replies, loginPeopleId); } context.setModel("replies", replies); } if (context.isApiRequest()) { Map<String, Object> api = new HashMap<String, Object>(); api.put("weibo", weibo); if (CollectionKit.isNotEmpty(replies)) { api.put("replies", replies); } context.setModel("api", api); } } /* * (non-Javadoc) * * @see q.web.Resource#validate(q.web.ResourceContext) */ @Override public void validate(ResourceContext context) throws Exception { long weiboId = context.getResourceIdLong(); if (IdCreator.isNotValidId(weiboId)) { throw new RequestParameterInvalidException("weibo:invalid"); } } }
true
true
public void execute(ResourceContext context) throws Exception { long weiboId = context.getResourceIdLong(); long loginPeopleId = context.getCookiePeopleId(); Weibo weibo = weiboDao.getWeiboById(weiboId); DaoHelper.injectWeiboModelWithQuote(weiboDao, weibo); DaoHelper.injectWeiboModelWithPeople(peopleDao, weibo); DaoHelper.injectWeiboModelWithFrom(groupDao, weibo); if (loginPeopleId > 0) { DaoHelper.injectWeiboWithFavorite(favoriteDao, weibo, loginPeopleId); } context.setModel("weibo", weibo); WeiboReplyPage page = new WeiboReplyPage(); page.setQuoteWeiboId(weiboId); int size = context.getInt("size", 10); long startId = context.getIdLong("startId"); page.setSize(size); page.setStartIndex(0); if (startId > 0) { page.setStartId(startId); } List<WeiboReply> replies = weiboDao.getWeiboRepliesByPage(page); if (CollectionKit.isNotEmpty(replies)) { DaoHelper.injectWeiboModelsWithPeople(peopleDao, replies); DaoHelper.injectWeiboModelsWithFrom(groupDao, replies); if (loginPeopleId > 0) { DaoHelper.injectWeiboModelsWithFavorite(favoriteDao, replies, loginPeopleId); } context.setModel("replies", replies); } if (context.isApiRequest()) { Map<String, Object> api = new HashMap<String, Object>(); api.put("weibo", weibo); if (CollectionKit.isNotEmpty(replies)) { api.put("replies", replies); } context.setModel("api", api); } }
public void execute(ResourceContext context) throws Exception { long weiboId = context.getResourceIdLong(); long loginPeopleId = context.getCookiePeopleId(); Weibo weibo = weiboDao.getWeiboById(weiboId); if(weibo.getQuoteWeiboId() > 0) { DaoHelper.injectWeiboModelWithQuote(weiboDao, weibo); } DaoHelper.injectWeiboModelWithPeople(peopleDao, weibo); DaoHelper.injectWeiboModelWithFrom(groupDao, weibo); if (loginPeopleId > 0) { DaoHelper.injectWeiboWithFavorite(favoriteDao, weibo, loginPeopleId); } context.setModel("weibo", weibo); WeiboReplyPage page = new WeiboReplyPage(); page.setQuoteWeiboId(weiboId); int size = context.getInt("size", 10); long startId = context.getIdLong("startId"); page.setSize(size); page.setStartIndex(0); if (startId > 0) { page.setStartId(startId); } List<WeiboReply> replies = weiboDao.getWeiboRepliesByPage(page); if (CollectionKit.isNotEmpty(replies)) { DaoHelper.injectWeiboModelsWithPeople(peopleDao, replies); DaoHelper.injectWeiboModelsWithFrom(groupDao, replies); if (loginPeopleId > 0) { DaoHelper.injectWeiboModelsWithFavorite(favoriteDao, replies, loginPeopleId); } context.setModel("replies", replies); } if (context.isApiRequest()) { Map<String, Object> api = new HashMap<String, Object>(); api.put("weibo", weibo); if (CollectionKit.isNotEmpty(replies)) { api.put("replies", replies); } context.setModel("api", api); } }
diff --git a/src/net/sf/gogui/gui/AnalyzeShow.java b/src/net/sf/gogui/gui/AnalyzeShow.java index 429a8fd7..60bd0103 100644 --- a/src/net/sf/gogui/gui/AnalyzeShow.java +++ b/src/net/sf/gogui/gui/AnalyzeShow.java @@ -1,166 +1,166 @@ //---------------------------------------------------------------------------- // $Id$ // $Source$ //---------------------------------------------------------------------------- package net.sf.gogui.gui; import java.util.Vector; import net.sf.gogui.go.Board; import net.sf.gogui.go.GoColor; import net.sf.gogui.go.GoPoint; import net.sf.gogui.go.Move; import net.sf.gogui.gtp.GtpError; import net.sf.gogui.gtp.GtpUtils; //---------------------------------------------------------------------------- /** Show response to an AnalyzeCommand in the GUI. */ public class AnalyzeShow { public static void show(AnalyzeCommand command, GuiBoard guiBoard, Board board, String response) throws GtpError { GoPoint pointArg = command.getPointArg(); Vector pointListArg = command.getPointListArg(); guiBoard.clearAllSelect(); for (int i = 0; i < pointListArg.size(); ++i) guiBoard.setSelect((GoPoint)pointListArg.get(i), true); if (pointArg != null) guiBoard.setSelect(pointArg, true); int type = command.getType(); String title = command.getTitle(); int size = board.getSize(); switch (type) { case AnalyzeCommand.BWBOARD: { String b[][] = GtpUtils.parseStringBoard(response, title, size); guiBoard.showBWBoard(b); guiBoard.repaint(); } break; case AnalyzeCommand.CBOARD: { String b[][] = GtpUtils.parseStringBoard(response, title, size); guiBoard.showColorBoard(b); guiBoard.repaint(); } break; case AnalyzeCommand.DBOARD: { double b[][] = GtpUtils.parseDoubleBoard(response, title, size); guiBoard.showDoubleBoard(b, command.getScale()); guiBoard.repaint(); } break; case AnalyzeCommand.PLIST: { GoPoint list[] = GtpUtils.parsePointList(response, size); guiBoard.showPointList(list); guiBoard.repaint(); } break; case AnalyzeCommand.HPSTRING: case AnalyzeCommand.PSTRING: { GoPoint list[] = GtpUtils.parsePointString(response, size); guiBoard.showPointList(list); guiBoard.repaint(); } break; case AnalyzeCommand.PSPAIRS: { Vector pointList = new Vector(32, 32); Vector stringList = new Vector(32, 32); GtpUtils.parsePointStringList(response, pointList, stringList, size); guiBoard.showPointStringList(pointList, stringList); guiBoard.repaint(); } break; case AnalyzeCommand.SBOARD: { String b[][] = GtpUtils.parseStringBoard(response, title, size); guiBoard.showStringBoard(b); guiBoard.repaint(); } break; case AnalyzeCommand.VAR: { showVariation(guiBoard, response, board.getToMove(), size); } break; case AnalyzeCommand.VARB: { showVariation(guiBoard, response, GoColor.BLACK, size); } break; case AnalyzeCommand.VARC: { showVariation(guiBoard, response, command.getColorArg(), size); } break; case AnalyzeCommand.VARW: { showVariation(guiBoard, response, GoColor.WHITE, size); } break; case AnalyzeCommand.VARP: { GoColor c = getColor(board, pointArg, pointListArg); if (c != GoColor.EMPTY) showVariation(guiBoard, response, c, size); } break; case AnalyzeCommand.VARPO: { GoColor c = getColor(board, pointArg, pointListArg); if (c != GoColor.EMPTY) showVariation(guiBoard, response, c.otherColor(), size); } break; default: - assert(false); + break; } } /** Make constructor unavailable; class is for namespace only. */ private AnalyzeShow() { } private static GoColor getColor(Board board, GoPoint pointArg, Vector pointListArg) { GoColor color = GoColor.EMPTY; if (pointArg != null) color = board.getColor(pointArg); if (color != GoColor.EMPTY) return color; for (int i = 0; i < pointListArg.size(); ++i) { GoPoint point = (GoPoint)pointListArg.get(i); color = board.getColor(point); if (color != GoColor.EMPTY) break; } return color; } private static void showVariation(GuiBoard guiBoard, String response, GoColor color, int size) { Move moves[] = GtpUtils.parseVariation(response, color, size); guiBoard.showVariation(moves); guiBoard.repaint(); } } //----------------------------------------------------------------------------
true
true
public static void show(AnalyzeCommand command, GuiBoard guiBoard, Board board, String response) throws GtpError { GoPoint pointArg = command.getPointArg(); Vector pointListArg = command.getPointListArg(); guiBoard.clearAllSelect(); for (int i = 0; i < pointListArg.size(); ++i) guiBoard.setSelect((GoPoint)pointListArg.get(i), true); if (pointArg != null) guiBoard.setSelect(pointArg, true); int type = command.getType(); String title = command.getTitle(); int size = board.getSize(); switch (type) { case AnalyzeCommand.BWBOARD: { String b[][] = GtpUtils.parseStringBoard(response, title, size); guiBoard.showBWBoard(b); guiBoard.repaint(); } break; case AnalyzeCommand.CBOARD: { String b[][] = GtpUtils.parseStringBoard(response, title, size); guiBoard.showColorBoard(b); guiBoard.repaint(); } break; case AnalyzeCommand.DBOARD: { double b[][] = GtpUtils.parseDoubleBoard(response, title, size); guiBoard.showDoubleBoard(b, command.getScale()); guiBoard.repaint(); } break; case AnalyzeCommand.PLIST: { GoPoint list[] = GtpUtils.parsePointList(response, size); guiBoard.showPointList(list); guiBoard.repaint(); } break; case AnalyzeCommand.HPSTRING: case AnalyzeCommand.PSTRING: { GoPoint list[] = GtpUtils.parsePointString(response, size); guiBoard.showPointList(list); guiBoard.repaint(); } break; case AnalyzeCommand.PSPAIRS: { Vector pointList = new Vector(32, 32); Vector stringList = new Vector(32, 32); GtpUtils.parsePointStringList(response, pointList, stringList, size); guiBoard.showPointStringList(pointList, stringList); guiBoard.repaint(); } break; case AnalyzeCommand.SBOARD: { String b[][] = GtpUtils.parseStringBoard(response, title, size); guiBoard.showStringBoard(b); guiBoard.repaint(); } break; case AnalyzeCommand.VAR: { showVariation(guiBoard, response, board.getToMove(), size); } break; case AnalyzeCommand.VARB: { showVariation(guiBoard, response, GoColor.BLACK, size); } break; case AnalyzeCommand.VARC: { showVariation(guiBoard, response, command.getColorArg(), size); } break; case AnalyzeCommand.VARW: { showVariation(guiBoard, response, GoColor.WHITE, size); } break; case AnalyzeCommand.VARP: { GoColor c = getColor(board, pointArg, pointListArg); if (c != GoColor.EMPTY) showVariation(guiBoard, response, c, size); } break; case AnalyzeCommand.VARPO: { GoColor c = getColor(board, pointArg, pointListArg); if (c != GoColor.EMPTY) showVariation(guiBoard, response, c.otherColor(), size); } break; default: assert(false); } }
public static void show(AnalyzeCommand command, GuiBoard guiBoard, Board board, String response) throws GtpError { GoPoint pointArg = command.getPointArg(); Vector pointListArg = command.getPointListArg(); guiBoard.clearAllSelect(); for (int i = 0; i < pointListArg.size(); ++i) guiBoard.setSelect((GoPoint)pointListArg.get(i), true); if (pointArg != null) guiBoard.setSelect(pointArg, true); int type = command.getType(); String title = command.getTitle(); int size = board.getSize(); switch (type) { case AnalyzeCommand.BWBOARD: { String b[][] = GtpUtils.parseStringBoard(response, title, size); guiBoard.showBWBoard(b); guiBoard.repaint(); } break; case AnalyzeCommand.CBOARD: { String b[][] = GtpUtils.parseStringBoard(response, title, size); guiBoard.showColorBoard(b); guiBoard.repaint(); } break; case AnalyzeCommand.DBOARD: { double b[][] = GtpUtils.parseDoubleBoard(response, title, size); guiBoard.showDoubleBoard(b, command.getScale()); guiBoard.repaint(); } break; case AnalyzeCommand.PLIST: { GoPoint list[] = GtpUtils.parsePointList(response, size); guiBoard.showPointList(list); guiBoard.repaint(); } break; case AnalyzeCommand.HPSTRING: case AnalyzeCommand.PSTRING: { GoPoint list[] = GtpUtils.parsePointString(response, size); guiBoard.showPointList(list); guiBoard.repaint(); } break; case AnalyzeCommand.PSPAIRS: { Vector pointList = new Vector(32, 32); Vector stringList = new Vector(32, 32); GtpUtils.parsePointStringList(response, pointList, stringList, size); guiBoard.showPointStringList(pointList, stringList); guiBoard.repaint(); } break; case AnalyzeCommand.SBOARD: { String b[][] = GtpUtils.parseStringBoard(response, title, size); guiBoard.showStringBoard(b); guiBoard.repaint(); } break; case AnalyzeCommand.VAR: { showVariation(guiBoard, response, board.getToMove(), size); } break; case AnalyzeCommand.VARB: { showVariation(guiBoard, response, GoColor.BLACK, size); } break; case AnalyzeCommand.VARC: { showVariation(guiBoard, response, command.getColorArg(), size); } break; case AnalyzeCommand.VARW: { showVariation(guiBoard, response, GoColor.WHITE, size); } break; case AnalyzeCommand.VARP: { GoColor c = getColor(board, pointArg, pointListArg); if (c != GoColor.EMPTY) showVariation(guiBoard, response, c, size); } break; case AnalyzeCommand.VARPO: { GoColor c = getColor(board, pointArg, pointListArg); if (c != GoColor.EMPTY) showVariation(guiBoard, response, c.otherColor(), size); } break; default: break; } }
diff --git a/Mobile/BukuDroid/src/org/csie/mpp/buku/MainActivity.java b/Mobile/BukuDroid/src/org/csie/mpp/buku/MainActivity.java index 248287b..e40bcda 100644 --- a/Mobile/BukuDroid/src/org/csie/mpp/buku/MainActivity.java +++ b/Mobile/BukuDroid/src/org/csie/mpp/buku/MainActivity.java @@ -1,252 +1,253 @@ package org.csie.mpp.buku; import org.csie.mpp.buku.db.BookEntry; import org.csie.mpp.buku.db.DBHelper; import org.csie.mpp.buku.view.BookshelfManager; import org.csie.mpp.buku.view.BookshelfManager.ViewListener; import org.csie.mpp.buku.view.DialogAction; import org.csie.mpp.buku.view.DialogAction.DialogActionListener; import org.csie.mpp.buku.view.FriendsManager; import org.csie.mpp.buku.view.ViewPageFragment; import org.csie.mpp.buku.view.ViewPagerAdapter; import android.app.Dialog; import android.app.SearchManager; import android.content.Intent; import android.content.pm.ActivityInfo; import android.os.Bundle; import android.provider.SearchRecentSuggestions; import android.support.v4.app.FragmentActivity; import android.support.v4.view.ViewPager; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import android.widget.Toast; import com.facebook.android.SessionEvents; import com.facebook.android.SessionEvents.AuthListener; import com.facebook.android.SessionStore; import com.facebook.android.view.FbLoginButton; import com.markupartist.android.widget.ActionBar; import com.markupartist.android.widget.ActionBar.IntentAction; import com.viewpagerindicator.TitlePageIndicator; public class MainActivity extends FragmentActivity implements DialogActionListener, ViewListener, OnItemClickListener { protected ActionBar actionbar; protected TitlePageIndicator indicator; protected ViewPager viewpager; protected ViewPagerAdapter viewpagerAdapter; protected ViewPageFragment bookshelf, stream, friends; private DBHelper db; private BookshelfManager bookMan; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); /* initialize FB */ SessionStore.restore(App.fb, this); /* initialize ActionBar */ actionbar = (ActionBar)findViewById(R.id.actionbar); actionbar.addAction(new IntentAction(this, new Intent(this, ScanActivity.class), R.drawable.ic_camera, ScanActivity.REQUEST_CODE)); // TODO: add login/share (add action when !App.fb.isSessionValid() == true) if(App.fb.isSessionValid()) actionbar.addAction(new DialogAction(this, R.layout.login, 0, this), 0); /* initialize ViewPageFragments */ viewpagerAdapter = new ViewPagerAdapter(getSupportFragmentManager()); db = new DBHelper(this); bookMan = new BookshelfManager(this, db, this); bookshelf = new ViewPageFragment(getString(R.string.bookshelf), R.layout.bookshelf, bookMan); viewpagerAdapter.addItem(bookshelf); /* initialize ViewPager */ indicator = (TitlePageIndicator)findViewById(R.id.indicator); viewpager = (ViewPager)findViewById(R.id.viewpager); viewpager.setAdapter(viewpagerAdapter); indicator.setViewPager(viewpager); if(App.fb.isSessionValid()) createSessionView(); /* get search bar information */ Intent intent = getIntent(); if (Intent.ACTION_SEARCH.equals(intent.getAction())) { - String query = intent.getStringExtra(SearchManager.QUERY); - SearchRecentSuggestions suggestions = new SearchRecentSuggestions(this, - SuggestionProvider.AUTHORITY, SuggestionProvider.MODE); - suggestions.saveRecentQuery(query, null); - doMySearch(query); + String query = intent.getStringExtra(SearchManager.QUERY); + SearchRecentSuggestions suggestions = new SearchRecentSuggestions( + this, SuggestionProvider.AUTHORITY, SuggestionProvider.MODE + ); + suggestions.saveRecentQuery(query, null); + doMySearch(query); } } private void doMySearch(String query) { Intent intent = new Intent(); intent.setClass(MainActivity.this, SearchResultActivity.class); Bundle bundle = new Bundle(); bundle.putString("query", query); intent.putExtras(bundle); startActivity(intent); return; } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch(requestCode) { case ScanActivity.REQUEST_CODE: if(resultCode == RESULT_OK) { String isbn = data.getStringExtra(ScanActivity.ISBN); startBookActivity(isbn, true); } break; case BookActivity.REQUEST_CODE: if(resultCode == RESULT_OK) { String isbn = data.getStringExtra(ScanActivity.ISBN); bookMan.add(isbn); } break; } App.fb.authorizeCallback(requestCode, resultCode, data); } public void startBookActivity(String isbn, boolean checkDuplicate) { Intent intent = new Intent(this, BookActivity.class); intent.putExtra(BookActivity.ISBN, isbn); intent.putExtra(BookActivity.CHECK_DUPLICATE, checkDuplicate); startActivityForResult(intent, BookActivity.REQUEST_CODE); } @Override public void onDestroy() { super.onDestroy(); db.close(); } private void createSessionView() { stream = new ViewPageFragment(getString(R.string.stream), R.layout.stream); viewpagerAdapter.addItem(stream); friends = new ViewPageFragment(getString(R.string.friends), R.layout.friends, new FriendsManager(this, db)); viewpagerAdapter.addItem(friends); viewpagerAdapter.notifyDataSetChanged(); indicator.setCurrentItem(1); } /* --- OptionsMenu (start) --- */ @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case R.id.menu_link: return true; default: return super.onOptionsItemSelected(item); } } /* --- OptionsMenu (end) --- */ /* --- ContextMenu (start) --- */ private static final int MENU_DELETE = 0; private String[] menuItems; @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { int position = ((AdapterView.AdapterContextMenuInfo)menuInfo).position; if(menuItems == null) menuItems = getResources().getStringArray(R.array.list_item_longclick); for(String menuItem: menuItems) menu.add(menuItem); BookEntry entry = bookMan.get(position); menu.setHeaderTitle(entry.title); } @Override public boolean onContextItemSelected(MenuItem item) { switch(item.getItemId()) { case MENU_DELETE: int position = ((AdapterView.AdapterContextMenuInfo)item.getMenuInfo()).position; BookEntry entry = bookMan.get(position); if(entry.delete(db.getWritableDatabase()) == false) { Toast.makeText(MainActivity.this, getString(R.string.delete_failed) + entry.title, App.TOAST_TIME).show(); Log.e(App.TAG, "Delete failed \"" + entry.isbn + "\"."); } bookMan.remove(entry); break; default: break; } return true; } /* --- ContextMenu (end) --- */ /* --- DialogActionListener (start) --- */ @Override public void onCreate(final Dialog dialog) { SessionEvents.addAuthListener(new AuthListener() { @Override public void onAuthSucceed() { dialog.dismiss(); createSessionView(); actionbar.removeActionAt(0); } @Override public void onAuthFail(String error) { dialog.dismiss(); Toast.makeText(MainActivity.this, R.string.login_failed, App.TOAST_TIME).show(); } }); } @Override public void onDisplay(final Dialog dialog) { FbLoginButton loginButton = (FbLoginButton)dialog.findViewById(R.id.login_button); loginButton.init(this, App.fb, App.FB_APP_PERMS); } /* --- DialogActionListener (end) --- */ /* --- ViewListener (start) --- */ @Override public void onListViewCreated(ListView view) { registerForContextMenu(view); view.setOnItemClickListener(this); } /* --- ViewListener (end) --- */ /* -- OnItemClickListener (start) --- */ @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { startBookActivity(bookMan.get(position).isbn, false); } /* --- OnItemClickListener (end) --- */ }
true
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); /* initialize FB */ SessionStore.restore(App.fb, this); /* initialize ActionBar */ actionbar = (ActionBar)findViewById(R.id.actionbar); actionbar.addAction(new IntentAction(this, new Intent(this, ScanActivity.class), R.drawable.ic_camera, ScanActivity.REQUEST_CODE)); // TODO: add login/share (add action when !App.fb.isSessionValid() == true) if(App.fb.isSessionValid()) actionbar.addAction(new DialogAction(this, R.layout.login, 0, this), 0); /* initialize ViewPageFragments */ viewpagerAdapter = new ViewPagerAdapter(getSupportFragmentManager()); db = new DBHelper(this); bookMan = new BookshelfManager(this, db, this); bookshelf = new ViewPageFragment(getString(R.string.bookshelf), R.layout.bookshelf, bookMan); viewpagerAdapter.addItem(bookshelf); /* initialize ViewPager */ indicator = (TitlePageIndicator)findViewById(R.id.indicator); viewpager = (ViewPager)findViewById(R.id.viewpager); viewpager.setAdapter(viewpagerAdapter); indicator.setViewPager(viewpager); if(App.fb.isSessionValid()) createSessionView(); /* get search bar information */ Intent intent = getIntent(); if (Intent.ACTION_SEARCH.equals(intent.getAction())) { String query = intent.getStringExtra(SearchManager.QUERY); SearchRecentSuggestions suggestions = new SearchRecentSuggestions(this, SuggestionProvider.AUTHORITY, SuggestionProvider.MODE); suggestions.saveRecentQuery(query, null); doMySearch(query); } }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); /* initialize FB */ SessionStore.restore(App.fb, this); /* initialize ActionBar */ actionbar = (ActionBar)findViewById(R.id.actionbar); actionbar.addAction(new IntentAction(this, new Intent(this, ScanActivity.class), R.drawable.ic_camera, ScanActivity.REQUEST_CODE)); // TODO: add login/share (add action when !App.fb.isSessionValid() == true) if(App.fb.isSessionValid()) actionbar.addAction(new DialogAction(this, R.layout.login, 0, this), 0); /* initialize ViewPageFragments */ viewpagerAdapter = new ViewPagerAdapter(getSupportFragmentManager()); db = new DBHelper(this); bookMan = new BookshelfManager(this, db, this); bookshelf = new ViewPageFragment(getString(R.string.bookshelf), R.layout.bookshelf, bookMan); viewpagerAdapter.addItem(bookshelf); /* initialize ViewPager */ indicator = (TitlePageIndicator)findViewById(R.id.indicator); viewpager = (ViewPager)findViewById(R.id.viewpager); viewpager.setAdapter(viewpagerAdapter); indicator.setViewPager(viewpager); if(App.fb.isSessionValid()) createSessionView(); /* get search bar information */ Intent intent = getIntent(); if (Intent.ACTION_SEARCH.equals(intent.getAction())) { String query = intent.getStringExtra(SearchManager.QUERY); SearchRecentSuggestions suggestions = new SearchRecentSuggestions( this, SuggestionProvider.AUTHORITY, SuggestionProvider.MODE ); suggestions.saveRecentQuery(query, null); doMySearch(query); } }
diff --git a/svnkit/src/main/java/org/tmatesoft/svn/core/internal/wc/SVNStatusUtil.java b/svnkit/src/main/java/org/tmatesoft/svn/core/internal/wc/SVNStatusUtil.java index 19eb34476..3e26bbd82 100644 --- a/svnkit/src/main/java/org/tmatesoft/svn/core/internal/wc/SVNStatusUtil.java +++ b/svnkit/src/main/java/org/tmatesoft/svn/core/internal/wc/SVNStatusUtil.java @@ -1,314 +1,317 @@ /* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.wc; import java.io.File; import java.util.Map; import org.tmatesoft.svn.core.SVNDepth; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNLock; import org.tmatesoft.svn.core.SVNNodeKind; import org.tmatesoft.svn.core.SVNProperty; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.internal.util.SVNDate; import org.tmatesoft.svn.core.internal.util.SVNEncodingUtil; import org.tmatesoft.svn.core.internal.util.SVNPathUtil; import org.tmatesoft.svn.core.internal.util.SVNURLUtil; import org.tmatesoft.svn.core.internal.wc.admin.SVNAdminArea; import org.tmatesoft.svn.core.internal.wc.admin.SVNAdminAreaInfo; import org.tmatesoft.svn.core.internal.wc.admin.SVNEntry; import org.tmatesoft.svn.core.internal.wc.admin.SVNWCAccess; import org.tmatesoft.svn.core.io.SVNRepository; import org.tmatesoft.svn.core.wc.ISVNEventHandler; import org.tmatesoft.svn.core.wc.ISVNStatusHandler; import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.core.wc.SVNStatus; import org.tmatesoft.svn.core.wc.SVNStatusType; import org.tmatesoft.svn.core.wc.SVNTreeConflictDescription; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNStatusUtil { public static SVNRevisionStatus getRevisionStatus(final File wcPath, String trailURL, final boolean committed, ISVNEventHandler eventHandler) throws SVNException { SVNWCAccess wcAccess = null; try { wcAccess = SVNWCAccess.newInstance(eventHandler); SVNAdminAreaInfo anchor = wcAccess.openAnchor(wcPath, false, SVNWCAccess.INFINITE_DEPTH); final long[] minRev = { SVNRepository.INVALID_REVISION }; final long[] maxRev = { SVNRepository.INVALID_REVISION }; final boolean[] isSwitched = { false, false, false }; final boolean[] isModified = { false }; final boolean[] isSparseCheckOut = { false }; final SVNURL[] wcURL = { null }; SVNStatusEditor editor = new SVNStatusEditor(null, wcAccess, anchor, false, true, SVNDepth.INFINITY, new ISVNStatusHandler() { public void handleStatus(SVNStatus status) throws SVNException { SVNEntry entry = status.getEntry(); if (entry == null) { return; } if (status.getContentsStatus() != SVNStatusType.STATUS_ADDED) { long itemRev = committed ? entry.getCommittedRevision() : entry.getRevision(); if (!SVNRevision.isValidRevisionNumber(minRev[0]) || itemRev < minRev[0]) { minRev[0] = itemRev; } if (!SVNRevision.isValidRevisionNumber(maxRev[0]) || itemRev > maxRev[0]) { maxRev[0] = itemRev; } } isSwitched[0] |= status.isSwitched(); isModified[0] |= status.getContentsStatus() != SVNStatusType.STATUS_NORMAL; isModified[0] |= status.getPropertiesStatus() != SVNStatusType.STATUS_NORMAL && status.getPropertiesStatus() != SVNStatusType.STATUS_NONE; isSparseCheckOut[0] |= entry.getDepth() != SVNDepth.INFINITY; if (wcPath != null && wcURL[0] == null && wcPath.equals(status.getFile())) { wcURL[0] = entry.getSVNURL(); } } }); editor.closeEdit(); if (!isSwitched[0] && trailURL != null) { if (wcURL[0] == null) { isSwitched[0] = true; } else { String wcURLStr = wcURL[0].toDecodedString(); if (trailURL.length() > wcURLStr.length() || !wcURLStr.endsWith(trailURL)) { isSwitched[0] = true; } } } return new SVNRevisionStatus(minRev[0], maxRev[0], isSwitched[0], isModified[0], isSparseCheckOut[0]); } finally { wcAccess.close(); } } public static SVNStatus getStatus(File path, SVNWCAccess wcAccess) throws SVNException { SVNEntry entry = null; SVNEntry parentEntry = null; SVNAdminArea adminArea = null; if (wcAccess != null) { entry = wcAccess.getEntry(path, false); adminArea = entry != null ? entry.getAdminArea() : null; } File parentPath = path.getParentFile(); if (entry != null && parentPath != null) { SVNAdminArea parentArea = wcAccess.retrieve(parentPath); if (parentArea != null) { parentEntry = wcAccess.getEntry(parentPath, false); } } return assembleStatus(path, adminArea, entry, parentEntry, SVNNodeKind.UNKNOWN, false, true, false, null, null, wcAccess); } public static SVNStatus assembleStatus(File file, SVNAdminArea dir, SVNEntry entry, SVNEntry parentEntry, SVNNodeKind fileKind, boolean special, boolean reportAll, boolean isIgnored, Map repositoryLocks, SVNURL reposRoot, SVNWCAccess wcAccess) throws SVNException { boolean hasProps = false; boolean isTextModified = false; boolean isPropsModified = false; boolean isLocked = false; boolean isSwitched = false; boolean isSpecial = false; boolean isFileExternal = false; SVNStatusType textStatus = SVNStatusType.STATUS_NORMAL; SVNStatusType propStatus = SVNStatusType.STATUS_NONE; SVNLock repositoryLock = null; if (repositoryLocks != null) { SVNURL url = null; if (entry != null && entry.getSVNURL() != null) { url = entry.getSVNURL(); } else if (parentEntry != null && parentEntry.getSVNURL() != null) { url = parentEntry.getSVNURL().appendPath(file.getName(), false); } if (url != null) { repositoryLock = getLock(repositoryLocks, url, reposRoot); } } if (fileKind == SVNNodeKind.UNKNOWN || fileKind == null) { SVNFileType fileType = SVNFileType.getType(file); fileKind = SVNFileType.getNodeKind(fileType); special = !SVNFileUtil.symlinksSupported() ? false : fileType == SVNFileType.SYMLINK; } int wcFormatNumber = dir != null ? dir.getWorkingCopyFormatVersion() : -1; SVNTreeConflictDescription treeConflict = wcAccess.getTreeConflict(file); if (entry == null) { SVNStatus status = new SVNStatus(null, file, SVNNodeKind.UNKNOWN, SVNRevision.UNDEFINED, SVNRevision.UNDEFINED, null, null, SVNStatusType.STATUS_NONE, SVNStatusType.STATUS_NONE, SVNStatusType.STATUS_NONE, SVNStatusType.STATUS_NONE, false, false, false, false, null, null, null, null, null, SVNRevision.UNDEFINED, repositoryLock, null, null, null, wcFormatNumber, treeConflict); status.setDepth(SVNDepth.UNKNOWN); status.setRemoteStatus(SVNStatusType.STATUS_NONE, SVNStatusType.STATUS_NONE, repositoryLock, SVNNodeKind.NONE); status.setRepositoryRootURL(reposRoot); SVNStatusType text = SVNStatusType.STATUS_NONE; SVNFileType fileType = SVNFileType.getType(file); if (fileType != SVNFileType.NONE) { text = isIgnored ? SVNStatusType.STATUS_IGNORED : SVNStatusType.STATUS_UNVERSIONED; } if (fileType == SVNFileType.NONE && treeConflict != null) { text = SVNStatusType.STATUS_MISSING; } status.setContentsStatus(text); - if (status.getURL() != null && status.getRepositoryRelativePath() == null) { + if (status.getURL() != null && status.getRepositoryRelativePath() == null && reposRoot != null) { status.setRepositoryRelativePath(SVNURLUtil.getRelativeURL(reposRoot, status.getURL(), false)); } return status; } if (entry.getKind() == SVNNodeKind.DIR) { if (fileKind == SVNNodeKind.DIR) { if (wcAccess.isMissing(file)) { textStatus = SVNStatusType.STATUS_OBSTRUCTED; } } else if (fileKind != SVNNodeKind.NONE) { textStatus = SVNStatusType.STATUS_OBSTRUCTED; } } if (entry.getExternalFilePath() != null) { isFileExternal = true; } else if (entry.getSVNURL() != null && parentEntry != null && parentEntry.getSVNURL() != null) { String urlName = SVNPathUtil.tail(entry.getSVNURL().getURIEncodedPath()); if (!SVNEncodingUtil.uriEncode(file.getName()).equals(urlName)) { isSwitched = true; } if (!isSwitched && !entry.getSVNURL().removePathTail().equals(parentEntry.getSVNURL())) { isSwitched = true; } } if (textStatus != SVNStatusType.STATUS_OBSTRUCTED) { String name = entry.getName(); if (dir != null && dir.hasProperties(name)) { propStatus = SVNStatusType.STATUS_NORMAL; hasProps = true; } isPropsModified = dir != null && dir.hasPropModifications(name); if (hasProps) { isSpecial = !SVNFileUtil.isWindows && dir != null && dir.getProperties(name).getPropertyValue(SVNProperty.SPECIAL) != null; } if (entry.getKind() == SVNNodeKind.FILE && special == isSpecial) { isTextModified = dir != null && dir.hasTextModifications(name, false); } if (isTextModified) { textStatus = SVNStatusType.STATUS_MODIFIED; } if (isPropsModified) { propStatus = SVNStatusType.STATUS_MODIFIED; } if (entry.getPropRejectFile() != null || entry.getConflictOld() != null || entry.getConflictNew() != null || entry.getConflictWorking() != null) { if (dir != null && dir.hasTextConflict(name)) { textStatus = SVNStatusType.STATUS_CONFLICTED; } if (dir != null && dir.hasPropConflict(name)) { propStatus = SVNStatusType.STATUS_CONFLICTED; } } if (entry.isScheduledForAddition() && textStatus != SVNStatusType.STATUS_CONFLICTED) { textStatus = SVNStatusType.STATUS_ADDED; propStatus = SVNStatusType.STATUS_NONE; } else if (entry.isScheduledForReplacement() && textStatus != SVNStatusType.STATUS_CONFLICTED) { textStatus = SVNStatusType.STATUS_REPLACED; propStatus = SVNStatusType.STATUS_NONE; } else if (entry.isScheduledForDeletion() && textStatus != SVNStatusType.STATUS_CONFLICTED) { textStatus = SVNStatusType.STATUS_DELETED; propStatus = SVNStatusType.STATUS_NONE; } if (entry.isIncomplete() && textStatus != SVNStatusType.STATUS_DELETED && textStatus != SVNStatusType.STATUS_ADDED) { textStatus = SVNStatusType.STATUS_INCOMPLETE; } else if (fileKind == SVNNodeKind.NONE) { if (textStatus != SVNStatusType.STATUS_DELETED) { textStatus = SVNStatusType.STATUS_MISSING; } } else if (fileKind != entry.getKind()) { textStatus = SVNStatusType.STATUS_OBSTRUCTED; } else if ((!isSpecial && special) || (isSpecial && !special)) { textStatus = SVNStatusType.STATUS_OBSTRUCTED; } if (fileKind == SVNNodeKind.DIR && entry.getKind() == SVNNodeKind.DIR) { isLocked = wcAccess.isLocked(file); } } if (!reportAll) { if ((textStatus == SVNStatusType.STATUS_NONE || textStatus == SVNStatusType.STATUS_NORMAL) && (propStatus == SVNStatusType.STATUS_NONE || propStatus == SVNStatusType.STATUS_NORMAL) && !isLocked && !isSwitched && entry.getLockToken() == null && repositoryLock == null && entry.getChangelistName() == null && !isFileExternal && treeConflict == null) { return null; } } SVNLock localLock = null; if (entry.getLockToken() != null) { localLock = new SVNLock(null, entry.getLockToken(), entry.getLockOwner(), entry.getLockComment(), SVNDate.parseDate(entry.getLockCreationDate()), null); } File conflictNew = dir != null ? dir.getFile(entry.getConflictNew()) : null; File conflictOld = dir != null ? dir.getFile(entry.getConflictOld()) : null; File conflictWrk = dir != null ? dir.getFile(entry.getConflictWorking()) : null; File conflictProp = dir != null ? dir.getFile(entry.getPropRejectFile()) : null; SVNStatus status = new SVNStatus(entry.getSVNURL(), file, entry.getKind(), SVNRevision.create(entry.getRevision()), SVNRevision.create(entry.getCommittedRevision()), SVNDate.parseDate(entry.getCommittedDate()), entry.getAuthor(), textStatus, propStatus, SVNStatusType.STATUS_NONE, SVNStatusType.STATUS_NONE, isLocked, entry.isCopied(), isSwitched, isFileExternal, conflictNew, conflictOld, conflictWrk, conflictProp, entry.getCopyFromURL(), SVNRevision.create(entry.getCopyFromRevision()), repositoryLock, localLock, entry.asMap(), entry.getChangelistName(), wcFormatNumber, treeConflict); status.setEntry(entry); status.setDepth(entry.isDirectory() ? entry.getDepth() : SVNDepth.UNKNOWN); + if (reposRoot == null) { + reposRoot = entry.getRepositoryRootURL(); + } status.setRepositoryRootURL(reposRoot); if (reposRoot != null && status.getURL() != null && status.getRepositoryRelativePath() == null) { status.setRepositoryRelativePath(SVNURLUtil.getRelativeURL(reposRoot, status.getURL(), false)); } return status; } public static SVNLock getLock(Map repositoryLocks, SVNURL url, SVNURL reposRoot) { // get decoded path if (reposRoot == null || repositoryLocks == null || repositoryLocks.isEmpty() || url == null) { return null; } String urlString = url.getPath(); String root = reposRoot.getPath(); String path; if (urlString.equals(root)) { path = "/"; } else { path = urlString.substring(root.length()); } return (SVNLock) repositoryLocks.get(path); } }
false
true
public static SVNStatus assembleStatus(File file, SVNAdminArea dir, SVNEntry entry, SVNEntry parentEntry, SVNNodeKind fileKind, boolean special, boolean reportAll, boolean isIgnored, Map repositoryLocks, SVNURL reposRoot, SVNWCAccess wcAccess) throws SVNException { boolean hasProps = false; boolean isTextModified = false; boolean isPropsModified = false; boolean isLocked = false; boolean isSwitched = false; boolean isSpecial = false; boolean isFileExternal = false; SVNStatusType textStatus = SVNStatusType.STATUS_NORMAL; SVNStatusType propStatus = SVNStatusType.STATUS_NONE; SVNLock repositoryLock = null; if (repositoryLocks != null) { SVNURL url = null; if (entry != null && entry.getSVNURL() != null) { url = entry.getSVNURL(); } else if (parentEntry != null && parentEntry.getSVNURL() != null) { url = parentEntry.getSVNURL().appendPath(file.getName(), false); } if (url != null) { repositoryLock = getLock(repositoryLocks, url, reposRoot); } } if (fileKind == SVNNodeKind.UNKNOWN || fileKind == null) { SVNFileType fileType = SVNFileType.getType(file); fileKind = SVNFileType.getNodeKind(fileType); special = !SVNFileUtil.symlinksSupported() ? false : fileType == SVNFileType.SYMLINK; } int wcFormatNumber = dir != null ? dir.getWorkingCopyFormatVersion() : -1; SVNTreeConflictDescription treeConflict = wcAccess.getTreeConflict(file); if (entry == null) { SVNStatus status = new SVNStatus(null, file, SVNNodeKind.UNKNOWN, SVNRevision.UNDEFINED, SVNRevision.UNDEFINED, null, null, SVNStatusType.STATUS_NONE, SVNStatusType.STATUS_NONE, SVNStatusType.STATUS_NONE, SVNStatusType.STATUS_NONE, false, false, false, false, null, null, null, null, null, SVNRevision.UNDEFINED, repositoryLock, null, null, null, wcFormatNumber, treeConflict); status.setDepth(SVNDepth.UNKNOWN); status.setRemoteStatus(SVNStatusType.STATUS_NONE, SVNStatusType.STATUS_NONE, repositoryLock, SVNNodeKind.NONE); status.setRepositoryRootURL(reposRoot); SVNStatusType text = SVNStatusType.STATUS_NONE; SVNFileType fileType = SVNFileType.getType(file); if (fileType != SVNFileType.NONE) { text = isIgnored ? SVNStatusType.STATUS_IGNORED : SVNStatusType.STATUS_UNVERSIONED; } if (fileType == SVNFileType.NONE && treeConflict != null) { text = SVNStatusType.STATUS_MISSING; } status.setContentsStatus(text); if (status.getURL() != null && status.getRepositoryRelativePath() == null) { status.setRepositoryRelativePath(SVNURLUtil.getRelativeURL(reposRoot, status.getURL(), false)); } return status; } if (entry.getKind() == SVNNodeKind.DIR) { if (fileKind == SVNNodeKind.DIR) { if (wcAccess.isMissing(file)) { textStatus = SVNStatusType.STATUS_OBSTRUCTED; } } else if (fileKind != SVNNodeKind.NONE) { textStatus = SVNStatusType.STATUS_OBSTRUCTED; } } if (entry.getExternalFilePath() != null) { isFileExternal = true; } else if (entry.getSVNURL() != null && parentEntry != null && parentEntry.getSVNURL() != null) { String urlName = SVNPathUtil.tail(entry.getSVNURL().getURIEncodedPath()); if (!SVNEncodingUtil.uriEncode(file.getName()).equals(urlName)) { isSwitched = true; } if (!isSwitched && !entry.getSVNURL().removePathTail().equals(parentEntry.getSVNURL())) { isSwitched = true; } } if (textStatus != SVNStatusType.STATUS_OBSTRUCTED) { String name = entry.getName(); if (dir != null && dir.hasProperties(name)) { propStatus = SVNStatusType.STATUS_NORMAL; hasProps = true; } isPropsModified = dir != null && dir.hasPropModifications(name); if (hasProps) { isSpecial = !SVNFileUtil.isWindows && dir != null && dir.getProperties(name).getPropertyValue(SVNProperty.SPECIAL) != null; } if (entry.getKind() == SVNNodeKind.FILE && special == isSpecial) { isTextModified = dir != null && dir.hasTextModifications(name, false); } if (isTextModified) { textStatus = SVNStatusType.STATUS_MODIFIED; } if (isPropsModified) { propStatus = SVNStatusType.STATUS_MODIFIED; } if (entry.getPropRejectFile() != null || entry.getConflictOld() != null || entry.getConflictNew() != null || entry.getConflictWorking() != null) { if (dir != null && dir.hasTextConflict(name)) { textStatus = SVNStatusType.STATUS_CONFLICTED; } if (dir != null && dir.hasPropConflict(name)) { propStatus = SVNStatusType.STATUS_CONFLICTED; } } if (entry.isScheduledForAddition() && textStatus != SVNStatusType.STATUS_CONFLICTED) { textStatus = SVNStatusType.STATUS_ADDED; propStatus = SVNStatusType.STATUS_NONE; } else if (entry.isScheduledForReplacement() && textStatus != SVNStatusType.STATUS_CONFLICTED) { textStatus = SVNStatusType.STATUS_REPLACED; propStatus = SVNStatusType.STATUS_NONE; } else if (entry.isScheduledForDeletion() && textStatus != SVNStatusType.STATUS_CONFLICTED) { textStatus = SVNStatusType.STATUS_DELETED; propStatus = SVNStatusType.STATUS_NONE; } if (entry.isIncomplete() && textStatus != SVNStatusType.STATUS_DELETED && textStatus != SVNStatusType.STATUS_ADDED) { textStatus = SVNStatusType.STATUS_INCOMPLETE; } else if (fileKind == SVNNodeKind.NONE) { if (textStatus != SVNStatusType.STATUS_DELETED) { textStatus = SVNStatusType.STATUS_MISSING; } } else if (fileKind != entry.getKind()) { textStatus = SVNStatusType.STATUS_OBSTRUCTED; } else if ((!isSpecial && special) || (isSpecial && !special)) { textStatus = SVNStatusType.STATUS_OBSTRUCTED; } if (fileKind == SVNNodeKind.DIR && entry.getKind() == SVNNodeKind.DIR) { isLocked = wcAccess.isLocked(file); } } if (!reportAll) { if ((textStatus == SVNStatusType.STATUS_NONE || textStatus == SVNStatusType.STATUS_NORMAL) && (propStatus == SVNStatusType.STATUS_NONE || propStatus == SVNStatusType.STATUS_NORMAL) && !isLocked && !isSwitched && entry.getLockToken() == null && repositoryLock == null && entry.getChangelistName() == null && !isFileExternal && treeConflict == null) { return null; } } SVNLock localLock = null; if (entry.getLockToken() != null) { localLock = new SVNLock(null, entry.getLockToken(), entry.getLockOwner(), entry.getLockComment(), SVNDate.parseDate(entry.getLockCreationDate()), null); } File conflictNew = dir != null ? dir.getFile(entry.getConflictNew()) : null; File conflictOld = dir != null ? dir.getFile(entry.getConflictOld()) : null; File conflictWrk = dir != null ? dir.getFile(entry.getConflictWorking()) : null; File conflictProp = dir != null ? dir.getFile(entry.getPropRejectFile()) : null; SVNStatus status = new SVNStatus(entry.getSVNURL(), file, entry.getKind(), SVNRevision.create(entry.getRevision()), SVNRevision.create(entry.getCommittedRevision()), SVNDate.parseDate(entry.getCommittedDate()), entry.getAuthor(), textStatus, propStatus, SVNStatusType.STATUS_NONE, SVNStatusType.STATUS_NONE, isLocked, entry.isCopied(), isSwitched, isFileExternal, conflictNew, conflictOld, conflictWrk, conflictProp, entry.getCopyFromURL(), SVNRevision.create(entry.getCopyFromRevision()), repositoryLock, localLock, entry.asMap(), entry.getChangelistName(), wcFormatNumber, treeConflict); status.setEntry(entry); status.setDepth(entry.isDirectory() ? entry.getDepth() : SVNDepth.UNKNOWN); status.setRepositoryRootURL(reposRoot); if (reposRoot != null && status.getURL() != null && status.getRepositoryRelativePath() == null) { status.setRepositoryRelativePath(SVNURLUtil.getRelativeURL(reposRoot, status.getURL(), false)); } return status; }
public static SVNStatus assembleStatus(File file, SVNAdminArea dir, SVNEntry entry, SVNEntry parentEntry, SVNNodeKind fileKind, boolean special, boolean reportAll, boolean isIgnored, Map repositoryLocks, SVNURL reposRoot, SVNWCAccess wcAccess) throws SVNException { boolean hasProps = false; boolean isTextModified = false; boolean isPropsModified = false; boolean isLocked = false; boolean isSwitched = false; boolean isSpecial = false; boolean isFileExternal = false; SVNStatusType textStatus = SVNStatusType.STATUS_NORMAL; SVNStatusType propStatus = SVNStatusType.STATUS_NONE; SVNLock repositoryLock = null; if (repositoryLocks != null) { SVNURL url = null; if (entry != null && entry.getSVNURL() != null) { url = entry.getSVNURL(); } else if (parentEntry != null && parentEntry.getSVNURL() != null) { url = parentEntry.getSVNURL().appendPath(file.getName(), false); } if (url != null) { repositoryLock = getLock(repositoryLocks, url, reposRoot); } } if (fileKind == SVNNodeKind.UNKNOWN || fileKind == null) { SVNFileType fileType = SVNFileType.getType(file); fileKind = SVNFileType.getNodeKind(fileType); special = !SVNFileUtil.symlinksSupported() ? false : fileType == SVNFileType.SYMLINK; } int wcFormatNumber = dir != null ? dir.getWorkingCopyFormatVersion() : -1; SVNTreeConflictDescription treeConflict = wcAccess.getTreeConflict(file); if (entry == null) { SVNStatus status = new SVNStatus(null, file, SVNNodeKind.UNKNOWN, SVNRevision.UNDEFINED, SVNRevision.UNDEFINED, null, null, SVNStatusType.STATUS_NONE, SVNStatusType.STATUS_NONE, SVNStatusType.STATUS_NONE, SVNStatusType.STATUS_NONE, false, false, false, false, null, null, null, null, null, SVNRevision.UNDEFINED, repositoryLock, null, null, null, wcFormatNumber, treeConflict); status.setDepth(SVNDepth.UNKNOWN); status.setRemoteStatus(SVNStatusType.STATUS_NONE, SVNStatusType.STATUS_NONE, repositoryLock, SVNNodeKind.NONE); status.setRepositoryRootURL(reposRoot); SVNStatusType text = SVNStatusType.STATUS_NONE; SVNFileType fileType = SVNFileType.getType(file); if (fileType != SVNFileType.NONE) { text = isIgnored ? SVNStatusType.STATUS_IGNORED : SVNStatusType.STATUS_UNVERSIONED; } if (fileType == SVNFileType.NONE && treeConflict != null) { text = SVNStatusType.STATUS_MISSING; } status.setContentsStatus(text); if (status.getURL() != null && status.getRepositoryRelativePath() == null && reposRoot != null) { status.setRepositoryRelativePath(SVNURLUtil.getRelativeURL(reposRoot, status.getURL(), false)); } return status; } if (entry.getKind() == SVNNodeKind.DIR) { if (fileKind == SVNNodeKind.DIR) { if (wcAccess.isMissing(file)) { textStatus = SVNStatusType.STATUS_OBSTRUCTED; } } else if (fileKind != SVNNodeKind.NONE) { textStatus = SVNStatusType.STATUS_OBSTRUCTED; } } if (entry.getExternalFilePath() != null) { isFileExternal = true; } else if (entry.getSVNURL() != null && parentEntry != null && parentEntry.getSVNURL() != null) { String urlName = SVNPathUtil.tail(entry.getSVNURL().getURIEncodedPath()); if (!SVNEncodingUtil.uriEncode(file.getName()).equals(urlName)) { isSwitched = true; } if (!isSwitched && !entry.getSVNURL().removePathTail().equals(parentEntry.getSVNURL())) { isSwitched = true; } } if (textStatus != SVNStatusType.STATUS_OBSTRUCTED) { String name = entry.getName(); if (dir != null && dir.hasProperties(name)) { propStatus = SVNStatusType.STATUS_NORMAL; hasProps = true; } isPropsModified = dir != null && dir.hasPropModifications(name); if (hasProps) { isSpecial = !SVNFileUtil.isWindows && dir != null && dir.getProperties(name).getPropertyValue(SVNProperty.SPECIAL) != null; } if (entry.getKind() == SVNNodeKind.FILE && special == isSpecial) { isTextModified = dir != null && dir.hasTextModifications(name, false); } if (isTextModified) { textStatus = SVNStatusType.STATUS_MODIFIED; } if (isPropsModified) { propStatus = SVNStatusType.STATUS_MODIFIED; } if (entry.getPropRejectFile() != null || entry.getConflictOld() != null || entry.getConflictNew() != null || entry.getConflictWorking() != null) { if (dir != null && dir.hasTextConflict(name)) { textStatus = SVNStatusType.STATUS_CONFLICTED; } if (dir != null && dir.hasPropConflict(name)) { propStatus = SVNStatusType.STATUS_CONFLICTED; } } if (entry.isScheduledForAddition() && textStatus != SVNStatusType.STATUS_CONFLICTED) { textStatus = SVNStatusType.STATUS_ADDED; propStatus = SVNStatusType.STATUS_NONE; } else if (entry.isScheduledForReplacement() && textStatus != SVNStatusType.STATUS_CONFLICTED) { textStatus = SVNStatusType.STATUS_REPLACED; propStatus = SVNStatusType.STATUS_NONE; } else if (entry.isScheduledForDeletion() && textStatus != SVNStatusType.STATUS_CONFLICTED) { textStatus = SVNStatusType.STATUS_DELETED; propStatus = SVNStatusType.STATUS_NONE; } if (entry.isIncomplete() && textStatus != SVNStatusType.STATUS_DELETED && textStatus != SVNStatusType.STATUS_ADDED) { textStatus = SVNStatusType.STATUS_INCOMPLETE; } else if (fileKind == SVNNodeKind.NONE) { if (textStatus != SVNStatusType.STATUS_DELETED) { textStatus = SVNStatusType.STATUS_MISSING; } } else if (fileKind != entry.getKind()) { textStatus = SVNStatusType.STATUS_OBSTRUCTED; } else if ((!isSpecial && special) || (isSpecial && !special)) { textStatus = SVNStatusType.STATUS_OBSTRUCTED; } if (fileKind == SVNNodeKind.DIR && entry.getKind() == SVNNodeKind.DIR) { isLocked = wcAccess.isLocked(file); } } if (!reportAll) { if ((textStatus == SVNStatusType.STATUS_NONE || textStatus == SVNStatusType.STATUS_NORMAL) && (propStatus == SVNStatusType.STATUS_NONE || propStatus == SVNStatusType.STATUS_NORMAL) && !isLocked && !isSwitched && entry.getLockToken() == null && repositoryLock == null && entry.getChangelistName() == null && !isFileExternal && treeConflict == null) { return null; } } SVNLock localLock = null; if (entry.getLockToken() != null) { localLock = new SVNLock(null, entry.getLockToken(), entry.getLockOwner(), entry.getLockComment(), SVNDate.parseDate(entry.getLockCreationDate()), null); } File conflictNew = dir != null ? dir.getFile(entry.getConflictNew()) : null; File conflictOld = dir != null ? dir.getFile(entry.getConflictOld()) : null; File conflictWrk = dir != null ? dir.getFile(entry.getConflictWorking()) : null; File conflictProp = dir != null ? dir.getFile(entry.getPropRejectFile()) : null; SVNStatus status = new SVNStatus(entry.getSVNURL(), file, entry.getKind(), SVNRevision.create(entry.getRevision()), SVNRevision.create(entry.getCommittedRevision()), SVNDate.parseDate(entry.getCommittedDate()), entry.getAuthor(), textStatus, propStatus, SVNStatusType.STATUS_NONE, SVNStatusType.STATUS_NONE, isLocked, entry.isCopied(), isSwitched, isFileExternal, conflictNew, conflictOld, conflictWrk, conflictProp, entry.getCopyFromURL(), SVNRevision.create(entry.getCopyFromRevision()), repositoryLock, localLock, entry.asMap(), entry.getChangelistName(), wcFormatNumber, treeConflict); status.setEntry(entry); status.setDepth(entry.isDirectory() ? entry.getDepth() : SVNDepth.UNKNOWN); if (reposRoot == null) { reposRoot = entry.getRepositoryRootURL(); } status.setRepositoryRootURL(reposRoot); if (reposRoot != null && status.getURL() != null && status.getRepositoryRelativePath() == null) { status.setRepositoryRelativePath(SVNURLUtil.getRelativeURL(reposRoot, status.getURL(), false)); } return status; }
diff --git a/Graph3r/src/com/touchmenotapps/Graph3r/bar/BarGraphView.java b/Graph3r/src/com/touchmenotapps/Graph3r/bar/BarGraphView.java index c7c97df..df08994 100644 --- a/Graph3r/src/com/touchmenotapps/Graph3r/bar/BarGraphView.java +++ b/Graph3r/src/com/touchmenotapps/Graph3r/bar/BarGraphView.java @@ -1,480 +1,482 @@ package com.touchmenotapps.Graph3r.bar; /** * @Description The BarGraphView class implements all variation of Bar Graph, like * Simple Bar Graph, Stacked Bar Graph and Grouped Bar Graph. * */ import java.util.ArrayList; import com.touchmenotapps.Graph3r.Graph; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.LinearGradient; import android.graphics.Paint; import android.graphics.Shader; import android.graphics.Rect; import android.graphics.Paint.Align; import android.util.Log; import android.view.MotionEvent; import android.view.ScaleGestureDetector; import android.view.View; import android.widget.Toast; /** * * @author Arindam Nath * */ public class BarGraphView extends View { private BarGraphRenderer mRenderer; private ScaleGestureDetector mScaleDetector; private float mScaleFactor; private BarGraphHelperFunctions mFunctions; private ArrayList<BarGraphObject> barGraphObject = new ArrayList<BarGraphObject>(); private ArrayList<Double> data = new ArrayList<Double>(); private ArrayList<int[]> color = new ArrayList<int[]>(); private ArrayList<String> stackGroupLabels = new ArrayList<String>(); private int graphWidth; private int graphHeight; private int graphOriginX; private int graphOriginY; private int xAxisLabelRotation; private ArrayList<String> barLabels = new ArrayList<String>(); private int graphGrouping; private int xAxisLabelDistance; private boolean graphIsScaling = false; private boolean graphIsDragged = false; private Paint stackBarTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG); private Paint barTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG); private Paint xAxesLabelTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG); private Paint xAxesSecondGroupPaint = new Paint(Paint.ANTI_ALIAS_FLAG); // These two variables keep track of the X and Y coordinate of the finger // when it first // touches the screen private float startX = 0f; private float startY = 0f; // These two variables keep track of the amount we need to translate the // canvas along the X // and the Y coordinate private float translateX = 0f; private float translateY = 0f; // These two variables keep track of the amount we translated the X and Y // coordinates, the last time we // panned. private float previousTranslateX = 0f; private float previousTranslateY = 0f; /** * * @param context */ public BarGraphView(Context context, BarGraphRenderer renderer) { super(context); mRenderer = renderer; mFunctions = new BarGraphHelperFunctions(); mScaleDetector = new ScaleGestureDetector(context, new ScaleListener()); initializeGraphRenderer(); } private void initializeGraphRenderer() { /** Set the paint properties **/ stackBarTextPaint.setColor(Color.BLACK); stackBarTextPaint.setTextAlign(Align.CENTER); xAxesLabelTextPaint.setColor(Color.BLACK); xAxesLabelTextPaint.setTextAlign(Align.CENTER); barTextPaint.setColor(Color.BLACK); barTextPaint.setTextAlign(Align.CENTER); xAxesSecondGroupPaint.setColor(Color.BLACK); /** Set the default sizes based on mode. **/ if (!mRenderer.isRunningOnTablet()) { xAxisLabelDistance = 10; barTextPaint.setTextSize(10); stackBarTextPaint.setTextSize(10); xAxesSecondGroupPaint.setTextSize(10); } else { xAxisLabelDistance = 35; barTextPaint.setTextSize(20); stackBarTextPaint.setTextSize(20); xAxesSecondGroupPaint.setTextSize(15); } /** Set the other graph data **/ this.mScaleFactor = mRenderer.getScaleFactor(); this.data = mRenderer.getPlotData(); this.color = mRenderer.getPlotColor(); this.barLabels = mRenderer.getBarLabels(); this.graphWidth = mRenderer.getGraphWidth(); this.graphHeight = mRenderer.getGraphHeight(); this.graphOriginX = mRenderer.getGraphOriginX(); this.graphOriginY = mRenderer.getGraphOriginY(); this.stackGroupLabels = mRenderer.getStackGroupLabels(); this.graphGrouping = mRenderer.getGraphGrouping(); /** X axes label properties **/ xAxesLabelTextPaint.setTextSize(mRenderer.getXAxisLabelSize()); this.xAxisLabelRotation = mRenderer.getXAxisLabelRotation(); } @Override public boolean onTouchEvent(MotionEvent event) { if (mRenderer.getGraphIsClickable() && !graphIsScaling && !graphIsDragged) { int eventX = (int) event.getX(); int eventY = (int) event.getY(); switch (event.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_UP: Log.i("Bar Graph", "Val X: " + eventX + " Val Y: " + eventY); graphIsDragged = false; for (int counter = 0; counter < barGraphObject.size(); counter++) { if (barGraphObject.get(counter).isInBounds(eventX, eventY)) { Toast.makeText(getContext(), "Clicked " + barGraphObject.get(counter).getValue(), Toast.LENGTH_LONG).show(); break; } else Log.i("Bar Graph", "Blank Click"); } break; } invalidate(); } if (mRenderer.getGraphIsPannable()) { switch (event.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_UP: graphIsDragged = false; // All fingers went up, so let�s save the value of translateX // and translateY into previousTranslateX and // previousTranslate previousTranslateX = translateX; previousTranslateY = translateY; break; case MotionEvent.ACTION_DOWN: // We assign the current X and Y coordinate of the finger to // startX and startY minus the previously translated // amount for each coordinates This works even when we are // translating the first time because the initial // values for these two variables is zero. startX = event.getX() - previousTranslateX; startY = event.getY() - previousTranslateY; break; case MotionEvent.ACTION_MOVE: translateX = event.getX() - startX; translateY = event.getY() - startY; // We cannot use startX and startY directly because we have // adjusted their values using the previous translation values. // This is why we need to add those values to startX and startY // so that we can get the actual coordinates of the finger. double distance = Math .sqrt(Math.pow(event.getX() - (startX + previousTranslateX), 2) + Math.pow(event.getY() - (startY + previousTranslateY), 2)); if (distance > 0) { graphIsDragged = true; distance *= mScaleFactor; } break; } invalidate(); } if (mRenderer.getGraphIsZoomable()) { mScaleDetector.onTouchEvent(event); } return true; } @Override public void onDraw(Canvas canvas) { super.onDraw(canvas); Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); // set the right hand extent of graph int _width = (graphOriginX + graphWidth); if (getWidth() - _width < 10) _width = getWidth() - 20; // set the top extent of graph int _height = (int) (getHeight() - graphOriginY - graphHeight); if (_height < 20) _height = 20; int originX = graphOriginX; // set the left hand extent int originY = getHeight() - graphOriginY; // set the bottom extent float padding; if (mRenderer.getStyle() == Graph.STYLE_BAR_NORMAL || mRenderer.getStyle() == Graph.STYLE_BAR_GROUPED) padding = (float) (((float) (_width - originX) / (float) data .size()) * 0.20); else padding = (float) (((float) (_width - originX) / (float) ((float) (data .size()) / (float) graphGrouping)) * 0.20); int maxVal = ((int) (mFunctions.getMaximumSeriesValue(data, graphGrouping, mRenderer.getStyle()) / 10) + 1) * 10; // value is equal to this much height float ratio = (float) ((float) (originY - _height) / (float) maxVal); /** Draw X Axis **/ if (mRenderer.getDrawXAxis()) { paint.setColor(mRenderer.getXAxisColor()); Rect xAxis = new Rect(originX, originY - 1, _width, originY); canvas.drawRect(xAxis, paint); } /** Draw Y Axis **/ if (mRenderer.getDrawYAxis()) { paint.setColor(mRenderer.getYAxisColor()); Rect yAxis = new Rect(originX, (int) (_height), originX + 1, originY); canvas.drawRect(yAxis, paint); } /** Draw grid parallel to X-Axis **/ if (mRenderer.getDrawGridLines()) { mFunctions.drawXAxisGrid(canvas, mRenderer.getXAxisColor(), mRenderer.getYAxisLabelSize(), originX, originY, _width, maxVal, ratio, 10); //TODO Get number of grid lines input from user } /** Draw Y-axis label **/ mFunctions.drawYAxisLabel(canvas, mRenderer, originX, originY, _height, getHeight(), maxVal, mRenderer.isRunningOnTablet()); /** Scale the canvas **/ canvas.save(); + /** Clip canvas **/ + canvas.clipRect(originX, (int) (_height), _width, originY, android.graphics.Region.Op.REPLACE); /** Set canvas zoom **/ canvas.scale(mScaleFactor, mScaleFactor, originX, originY); - //canvas.clipRect(originX, (int) (_height), _width, originY, android.graphics.Region.Op.REPLACE); /** Set canvas translate **/ canvas.translate(translateX / mScaleFactor, 0); int tempX = originX + (int) padding; int heightBar; int barLabelsCounter = 0; /** Draw the bar and the labels **/ switch (mRenderer.getStyle()) { case Graph.STYLE_BAR_NORMAL: for (int counter = 0; counter < data.size(); counter++) { heightBar = (int) (((originY - (_height)) - (data.get(counter) * ratio)) + (_height)); paint.setShader(new LinearGradient(tempX, heightBar, (int) (tempX + padding * 4), originY, color.get(counter % color.size())[0], color.get(counter % color.size())[1], Shader.TileMode.MIRROR)); Rect bar = new Rect(tempX, heightBar, (int) (tempX + padding * 4), originY); canvas.drawRect(bar, paint); /** Add it to the items array **/ canvas.drawText(data.get(counter) + "", tempX + padding * 2, heightBar - 5, barTextPaint); barGraphObject.add(new BarGraphObject(bar, String.valueOf(data .get(counter)))); /** Rotate the text if needed **/ canvas.save(); canvas.rotate(xAxisLabelRotation, tempX + padding * 2, (originY + xAxisLabelDistance)); canvas.drawText(barLabels.get(counter), tempX + padding * 2, originY + xAxisLabelDistance, xAxesLabelTextPaint); canvas.restore(); tempX = (int) (tempX + padding * 5); } break; case Graph.STYLE_BAR_GROUPED: for (int counter = 0; counter < data.size(); counter++) { if (counter > 0) if (counter % graphGrouping == 0) tempX = (int) (tempX + padding * (graphGrouping + 4)); else tempX = (int) (tempX + padding * 4); heightBar = (int) (((originY - (_height)) - (data.get(counter) * ratio)) + (_height)); paint.setShader(new LinearGradient(tempX, heightBar, (int) (tempX + padding * 4), originY, color.get((counter % graphGrouping) % color.size())[0], color.get((counter % graphGrouping) % color.size())[1], Shader.TileMode.CLAMP)); Rect bar = new Rect(tempX, heightBar, (int) (tempX + padding * 4), originY); canvas.drawRect(bar, paint); /** Add it to the items array **/ canvas.drawText(data.get(counter) + "", tempX + padding * 2, heightBar - 5, barTextPaint); barGraphObject.add(new BarGraphObject(bar, String.valueOf(data .get(counter)))); // TODO Add item to control x axis text label color if (counter % graphGrouping == 0) { canvas.save(); canvas.rotate(0); canvas.rotate(xAxisLabelRotation, (float) (tempX + 2.5 * graphGrouping * padding), (originY + xAxisLabelDistance)); canvas.drawText(barLabels.get(barLabelsCounter++), (float) (tempX + 2.5 * graphGrouping * padding), originY + xAxisLabelDistance, xAxesLabelTextPaint); canvas.restore(); } } break; case Graph.STYLE_BAR_STACKED: int temp = 0; for (int counter = 0; counter < data.size(); counter++) { if (counter > 0 && counter % graphGrouping == 0) { tempX = (int) (tempX + padding * 5); temp = 0; } if (counter % graphGrouping == 0) heightBar = (int) ((originY) - (data.get(counter) * ratio)); else heightBar = (int) ((temp) - (data.get(counter) * ratio)); paint.setShader(new LinearGradient(tempX, heightBar, (int) (tempX + padding * 4), (temp == 0) ? originY : temp, color.get((counter % graphGrouping) % color.size())[0], color.get((counter % graphGrouping) % color.size())[1], Shader.TileMode.MIRROR)); Rect bar = new Rect(tempX, heightBar, (int) (tempX + padding * 4), (temp == 0) ? originY : temp); temp = heightBar; canvas.drawRect(bar, paint); /** Add it to the items array **/ barGraphObject.add(new BarGraphObject(bar, String.valueOf(data .get(counter)))); canvas.drawText(data.get(counter) + "", tempX + padding * 2, heightBar + (mRenderer.getXAxisLabelSize() + 2), stackBarTextPaint); if (counter % graphGrouping == 0) { canvas.save(); canvas.rotate(xAxisLabelRotation, (float) (tempX + 2 * padding), (originY + xAxisLabelDistance)); canvas.drawText(barLabels.get(barLabelsCounter++), (float) (tempX + 2 * padding), originY + xAxisLabelDistance, xAxesLabelTextPaint); canvas.restore(); } } break; case Graph.STYLE_BAR_STACK_GROUPED: int currentSecondXLabel = 0; float currentSecondXLabelValue = 0; int stackGroupTemp = 0; for (int counter = 0; counter < data.size(); counter++) { // Setting third grouping factor, X axes labels if (counter > 0 && counter % 8 == 0) { canvas.save(); if (currentSecondXLabel == 0) canvas.drawText( stackGroupLabels.get(currentSecondXLabel++), (float) (currentSecondXLabelValue / 1.5), originY + xAxisLabelDistance + 15, xAxesSecondGroupPaint); else canvas.drawText( stackGroupLabels.get(currentSecondXLabel++), currentSecondXLabelValue, originY + xAxisLabelDistance + 15, xAxesSecondGroupPaint); canvas.restore(); } // Drawing the stacks if (counter > 0 && counter % graphGrouping == 0) { tempX = (int) (tempX + padding * 5); stackGroupTemp = 0; } if (counter % graphGrouping == 0) heightBar = (int) ((originY) - (data.get(counter) * ratio)); else heightBar = (int) ((stackGroupTemp) - (data.get(counter) * ratio)); paint.setShader(new LinearGradient(tempX, heightBar, (int) (tempX + padding * 4), (stackGroupTemp == 0) ? originY : stackGroupTemp, color.get((counter % graphGrouping) % color.size())[0], color.get((counter % graphGrouping) % color.size())[1], Shader.TileMode.MIRROR)); Rect bar = new Rect(tempX, heightBar, (int) (tempX + padding * 4), (stackGroupTemp == 0) ? originY : stackGroupTemp); stackGroupTemp = heightBar; canvas.drawRect(bar, paint); /** Add it to the items array **/ barGraphObject.add(new BarGraphObject(bar, String.valueOf(data .get(counter)))); canvas.drawText(data.get(counter) + "", tempX + padding * 2, heightBar + (mRenderer.getXAxisLabelSize() + 2), stackBarTextPaint); if (counter % graphGrouping == 0) { canvas.save(); canvas.rotate(xAxisLabelRotation, (float) (tempX + 2 * padding), (originY + xAxisLabelDistance)); canvas.drawText(barLabels.get(barLabelsCounter++), (float) (tempX + 2 * padding), originY + xAxisLabelDistance, xAxesLabelTextPaint); canvas.restore(); if (counter > 0 && counter % 6 == 0) { currentSecondXLabelValue = (float) (tempX + 2 * padding); } } } break; } // Restore canvas after zooming and translating canvas.restore(); + invalidate(); } private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener { @Override public boolean onScaleBegin(ScaleGestureDetector detector) { graphIsScaling = true; return super.onScaleBegin(detector); } @Override public boolean onScale(ScaleGestureDetector detector) { mScaleFactor *= detector.getScaleFactor(); // Don't let the object get too small or too large. mScaleFactor = Math.max( Math.min(mScaleFactor, mRenderer.getMaxZoom()), mRenderer.getMinZoom()); invalidate(); return true; } @Override public void onScaleEnd(ScaleGestureDetector detector) { graphIsScaling = false; super.onScaleEnd(detector); } } }
false
true
public void onDraw(Canvas canvas) { super.onDraw(canvas); Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); // set the right hand extent of graph int _width = (graphOriginX + graphWidth); if (getWidth() - _width < 10) _width = getWidth() - 20; // set the top extent of graph int _height = (int) (getHeight() - graphOriginY - graphHeight); if (_height < 20) _height = 20; int originX = graphOriginX; // set the left hand extent int originY = getHeight() - graphOriginY; // set the bottom extent float padding; if (mRenderer.getStyle() == Graph.STYLE_BAR_NORMAL || mRenderer.getStyle() == Graph.STYLE_BAR_GROUPED) padding = (float) (((float) (_width - originX) / (float) data .size()) * 0.20); else padding = (float) (((float) (_width - originX) / (float) ((float) (data .size()) / (float) graphGrouping)) * 0.20); int maxVal = ((int) (mFunctions.getMaximumSeriesValue(data, graphGrouping, mRenderer.getStyle()) / 10) + 1) * 10; // value is equal to this much height float ratio = (float) ((float) (originY - _height) / (float) maxVal); /** Draw X Axis **/ if (mRenderer.getDrawXAxis()) { paint.setColor(mRenderer.getXAxisColor()); Rect xAxis = new Rect(originX, originY - 1, _width, originY); canvas.drawRect(xAxis, paint); } /** Draw Y Axis **/ if (mRenderer.getDrawYAxis()) { paint.setColor(mRenderer.getYAxisColor()); Rect yAxis = new Rect(originX, (int) (_height), originX + 1, originY); canvas.drawRect(yAxis, paint); } /** Draw grid parallel to X-Axis **/ if (mRenderer.getDrawGridLines()) { mFunctions.drawXAxisGrid(canvas, mRenderer.getXAxisColor(), mRenderer.getYAxisLabelSize(), originX, originY, _width, maxVal, ratio, 10); //TODO Get number of grid lines input from user } /** Draw Y-axis label **/ mFunctions.drawYAxisLabel(canvas, mRenderer, originX, originY, _height, getHeight(), maxVal, mRenderer.isRunningOnTablet()); /** Scale the canvas **/ canvas.save(); /** Set canvas zoom **/ canvas.scale(mScaleFactor, mScaleFactor, originX, originY); //canvas.clipRect(originX, (int) (_height), _width, originY, android.graphics.Region.Op.REPLACE); /** Set canvas translate **/ canvas.translate(translateX / mScaleFactor, 0); int tempX = originX + (int) padding; int heightBar; int barLabelsCounter = 0; /** Draw the bar and the labels **/ switch (mRenderer.getStyle()) { case Graph.STYLE_BAR_NORMAL: for (int counter = 0; counter < data.size(); counter++) { heightBar = (int) (((originY - (_height)) - (data.get(counter) * ratio)) + (_height)); paint.setShader(new LinearGradient(tempX, heightBar, (int) (tempX + padding * 4), originY, color.get(counter % color.size())[0], color.get(counter % color.size())[1], Shader.TileMode.MIRROR)); Rect bar = new Rect(tempX, heightBar, (int) (tempX + padding * 4), originY); canvas.drawRect(bar, paint); /** Add it to the items array **/ canvas.drawText(data.get(counter) + "", tempX + padding * 2, heightBar - 5, barTextPaint); barGraphObject.add(new BarGraphObject(bar, String.valueOf(data .get(counter)))); /** Rotate the text if needed **/ canvas.save(); canvas.rotate(xAxisLabelRotation, tempX + padding * 2, (originY + xAxisLabelDistance)); canvas.drawText(barLabels.get(counter), tempX + padding * 2, originY + xAxisLabelDistance, xAxesLabelTextPaint); canvas.restore(); tempX = (int) (tempX + padding * 5); } break; case Graph.STYLE_BAR_GROUPED: for (int counter = 0; counter < data.size(); counter++) { if (counter > 0) if (counter % graphGrouping == 0) tempX = (int) (tempX + padding * (graphGrouping + 4)); else tempX = (int) (tempX + padding * 4); heightBar = (int) (((originY - (_height)) - (data.get(counter) * ratio)) + (_height)); paint.setShader(new LinearGradient(tempX, heightBar, (int) (tempX + padding * 4), originY, color.get((counter % graphGrouping) % color.size())[0], color.get((counter % graphGrouping) % color.size())[1], Shader.TileMode.CLAMP)); Rect bar = new Rect(tempX, heightBar, (int) (tempX + padding * 4), originY); canvas.drawRect(bar, paint); /** Add it to the items array **/ canvas.drawText(data.get(counter) + "", tempX + padding * 2, heightBar - 5, barTextPaint); barGraphObject.add(new BarGraphObject(bar, String.valueOf(data .get(counter)))); // TODO Add item to control x axis text label color if (counter % graphGrouping == 0) { canvas.save(); canvas.rotate(0); canvas.rotate(xAxisLabelRotation, (float) (tempX + 2.5 * graphGrouping * padding), (originY + xAxisLabelDistance)); canvas.drawText(barLabels.get(barLabelsCounter++), (float) (tempX + 2.5 * graphGrouping * padding), originY + xAxisLabelDistance, xAxesLabelTextPaint); canvas.restore(); } } break; case Graph.STYLE_BAR_STACKED: int temp = 0; for (int counter = 0; counter < data.size(); counter++) { if (counter > 0 && counter % graphGrouping == 0) { tempX = (int) (tempX + padding * 5); temp = 0; } if (counter % graphGrouping == 0) heightBar = (int) ((originY) - (data.get(counter) * ratio)); else heightBar = (int) ((temp) - (data.get(counter) * ratio)); paint.setShader(new LinearGradient(tempX, heightBar, (int) (tempX + padding * 4), (temp == 0) ? originY : temp, color.get((counter % graphGrouping) % color.size())[0], color.get((counter % graphGrouping) % color.size())[1], Shader.TileMode.MIRROR)); Rect bar = new Rect(tempX, heightBar, (int) (tempX + padding * 4), (temp == 0) ? originY : temp); temp = heightBar; canvas.drawRect(bar, paint); /** Add it to the items array **/ barGraphObject.add(new BarGraphObject(bar, String.valueOf(data .get(counter)))); canvas.drawText(data.get(counter) + "", tempX + padding * 2, heightBar + (mRenderer.getXAxisLabelSize() + 2), stackBarTextPaint); if (counter % graphGrouping == 0) { canvas.save(); canvas.rotate(xAxisLabelRotation, (float) (tempX + 2 * padding), (originY + xAxisLabelDistance)); canvas.drawText(barLabels.get(barLabelsCounter++), (float) (tempX + 2 * padding), originY + xAxisLabelDistance, xAxesLabelTextPaint); canvas.restore(); } } break; case Graph.STYLE_BAR_STACK_GROUPED: int currentSecondXLabel = 0; float currentSecondXLabelValue = 0; int stackGroupTemp = 0; for (int counter = 0; counter < data.size(); counter++) { // Setting third grouping factor, X axes labels if (counter > 0 && counter % 8 == 0) { canvas.save(); if (currentSecondXLabel == 0) canvas.drawText( stackGroupLabels.get(currentSecondXLabel++), (float) (currentSecondXLabelValue / 1.5), originY + xAxisLabelDistance + 15, xAxesSecondGroupPaint); else canvas.drawText( stackGroupLabels.get(currentSecondXLabel++), currentSecondXLabelValue, originY + xAxisLabelDistance + 15, xAxesSecondGroupPaint); canvas.restore(); } // Drawing the stacks if (counter > 0 && counter % graphGrouping == 0) { tempX = (int) (tempX + padding * 5); stackGroupTemp = 0; } if (counter % graphGrouping == 0) heightBar = (int) ((originY) - (data.get(counter) * ratio)); else heightBar = (int) ((stackGroupTemp) - (data.get(counter) * ratio)); paint.setShader(new LinearGradient(tempX, heightBar, (int) (tempX + padding * 4), (stackGroupTemp == 0) ? originY : stackGroupTemp, color.get((counter % graphGrouping) % color.size())[0], color.get((counter % graphGrouping) % color.size())[1], Shader.TileMode.MIRROR)); Rect bar = new Rect(tempX, heightBar, (int) (tempX + padding * 4), (stackGroupTemp == 0) ? originY : stackGroupTemp); stackGroupTemp = heightBar; canvas.drawRect(bar, paint); /** Add it to the items array **/ barGraphObject.add(new BarGraphObject(bar, String.valueOf(data .get(counter)))); canvas.drawText(data.get(counter) + "", tempX + padding * 2, heightBar + (mRenderer.getXAxisLabelSize() + 2), stackBarTextPaint); if (counter % graphGrouping == 0) { canvas.save(); canvas.rotate(xAxisLabelRotation, (float) (tempX + 2 * padding), (originY + xAxisLabelDistance)); canvas.drawText(barLabels.get(barLabelsCounter++), (float) (tempX + 2 * padding), originY + xAxisLabelDistance, xAxesLabelTextPaint); canvas.restore(); if (counter > 0 && counter % 6 == 0) { currentSecondXLabelValue = (float) (tempX + 2 * padding); } } } break; } // Restore canvas after zooming and translating canvas.restore(); }
public void onDraw(Canvas canvas) { super.onDraw(canvas); Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); // set the right hand extent of graph int _width = (graphOriginX + graphWidth); if (getWidth() - _width < 10) _width = getWidth() - 20; // set the top extent of graph int _height = (int) (getHeight() - graphOriginY - graphHeight); if (_height < 20) _height = 20; int originX = graphOriginX; // set the left hand extent int originY = getHeight() - graphOriginY; // set the bottom extent float padding; if (mRenderer.getStyle() == Graph.STYLE_BAR_NORMAL || mRenderer.getStyle() == Graph.STYLE_BAR_GROUPED) padding = (float) (((float) (_width - originX) / (float) data .size()) * 0.20); else padding = (float) (((float) (_width - originX) / (float) ((float) (data .size()) / (float) graphGrouping)) * 0.20); int maxVal = ((int) (mFunctions.getMaximumSeriesValue(data, graphGrouping, mRenderer.getStyle()) / 10) + 1) * 10; // value is equal to this much height float ratio = (float) ((float) (originY - _height) / (float) maxVal); /** Draw X Axis **/ if (mRenderer.getDrawXAxis()) { paint.setColor(mRenderer.getXAxisColor()); Rect xAxis = new Rect(originX, originY - 1, _width, originY); canvas.drawRect(xAxis, paint); } /** Draw Y Axis **/ if (mRenderer.getDrawYAxis()) { paint.setColor(mRenderer.getYAxisColor()); Rect yAxis = new Rect(originX, (int) (_height), originX + 1, originY); canvas.drawRect(yAxis, paint); } /** Draw grid parallel to X-Axis **/ if (mRenderer.getDrawGridLines()) { mFunctions.drawXAxisGrid(canvas, mRenderer.getXAxisColor(), mRenderer.getYAxisLabelSize(), originX, originY, _width, maxVal, ratio, 10); //TODO Get number of grid lines input from user } /** Draw Y-axis label **/ mFunctions.drawYAxisLabel(canvas, mRenderer, originX, originY, _height, getHeight(), maxVal, mRenderer.isRunningOnTablet()); /** Scale the canvas **/ canvas.save(); /** Clip canvas **/ canvas.clipRect(originX, (int) (_height), _width, originY, android.graphics.Region.Op.REPLACE); /** Set canvas zoom **/ canvas.scale(mScaleFactor, mScaleFactor, originX, originY); /** Set canvas translate **/ canvas.translate(translateX / mScaleFactor, 0); int tempX = originX + (int) padding; int heightBar; int barLabelsCounter = 0; /** Draw the bar and the labels **/ switch (mRenderer.getStyle()) { case Graph.STYLE_BAR_NORMAL: for (int counter = 0; counter < data.size(); counter++) { heightBar = (int) (((originY - (_height)) - (data.get(counter) * ratio)) + (_height)); paint.setShader(new LinearGradient(tempX, heightBar, (int) (tempX + padding * 4), originY, color.get(counter % color.size())[0], color.get(counter % color.size())[1], Shader.TileMode.MIRROR)); Rect bar = new Rect(tempX, heightBar, (int) (tempX + padding * 4), originY); canvas.drawRect(bar, paint); /** Add it to the items array **/ canvas.drawText(data.get(counter) + "", tempX + padding * 2, heightBar - 5, barTextPaint); barGraphObject.add(new BarGraphObject(bar, String.valueOf(data .get(counter)))); /** Rotate the text if needed **/ canvas.save(); canvas.rotate(xAxisLabelRotation, tempX + padding * 2, (originY + xAxisLabelDistance)); canvas.drawText(barLabels.get(counter), tempX + padding * 2, originY + xAxisLabelDistance, xAxesLabelTextPaint); canvas.restore(); tempX = (int) (tempX + padding * 5); } break; case Graph.STYLE_BAR_GROUPED: for (int counter = 0; counter < data.size(); counter++) { if (counter > 0) if (counter % graphGrouping == 0) tempX = (int) (tempX + padding * (graphGrouping + 4)); else tempX = (int) (tempX + padding * 4); heightBar = (int) (((originY - (_height)) - (data.get(counter) * ratio)) + (_height)); paint.setShader(new LinearGradient(tempX, heightBar, (int) (tempX + padding * 4), originY, color.get((counter % graphGrouping) % color.size())[0], color.get((counter % graphGrouping) % color.size())[1], Shader.TileMode.CLAMP)); Rect bar = new Rect(tempX, heightBar, (int) (tempX + padding * 4), originY); canvas.drawRect(bar, paint); /** Add it to the items array **/ canvas.drawText(data.get(counter) + "", tempX + padding * 2, heightBar - 5, barTextPaint); barGraphObject.add(new BarGraphObject(bar, String.valueOf(data .get(counter)))); // TODO Add item to control x axis text label color if (counter % graphGrouping == 0) { canvas.save(); canvas.rotate(0); canvas.rotate(xAxisLabelRotation, (float) (tempX + 2.5 * graphGrouping * padding), (originY + xAxisLabelDistance)); canvas.drawText(barLabels.get(barLabelsCounter++), (float) (tempX + 2.5 * graphGrouping * padding), originY + xAxisLabelDistance, xAxesLabelTextPaint); canvas.restore(); } } break; case Graph.STYLE_BAR_STACKED: int temp = 0; for (int counter = 0; counter < data.size(); counter++) { if (counter > 0 && counter % graphGrouping == 0) { tempX = (int) (tempX + padding * 5); temp = 0; } if (counter % graphGrouping == 0) heightBar = (int) ((originY) - (data.get(counter) * ratio)); else heightBar = (int) ((temp) - (data.get(counter) * ratio)); paint.setShader(new LinearGradient(tempX, heightBar, (int) (tempX + padding * 4), (temp == 0) ? originY : temp, color.get((counter % graphGrouping) % color.size())[0], color.get((counter % graphGrouping) % color.size())[1], Shader.TileMode.MIRROR)); Rect bar = new Rect(tempX, heightBar, (int) (tempX + padding * 4), (temp == 0) ? originY : temp); temp = heightBar; canvas.drawRect(bar, paint); /** Add it to the items array **/ barGraphObject.add(new BarGraphObject(bar, String.valueOf(data .get(counter)))); canvas.drawText(data.get(counter) + "", tempX + padding * 2, heightBar + (mRenderer.getXAxisLabelSize() + 2), stackBarTextPaint); if (counter % graphGrouping == 0) { canvas.save(); canvas.rotate(xAxisLabelRotation, (float) (tempX + 2 * padding), (originY + xAxisLabelDistance)); canvas.drawText(barLabels.get(barLabelsCounter++), (float) (tempX + 2 * padding), originY + xAxisLabelDistance, xAxesLabelTextPaint); canvas.restore(); } } break; case Graph.STYLE_BAR_STACK_GROUPED: int currentSecondXLabel = 0; float currentSecondXLabelValue = 0; int stackGroupTemp = 0; for (int counter = 0; counter < data.size(); counter++) { // Setting third grouping factor, X axes labels if (counter > 0 && counter % 8 == 0) { canvas.save(); if (currentSecondXLabel == 0) canvas.drawText( stackGroupLabels.get(currentSecondXLabel++), (float) (currentSecondXLabelValue / 1.5), originY + xAxisLabelDistance + 15, xAxesSecondGroupPaint); else canvas.drawText( stackGroupLabels.get(currentSecondXLabel++), currentSecondXLabelValue, originY + xAxisLabelDistance + 15, xAxesSecondGroupPaint); canvas.restore(); } // Drawing the stacks if (counter > 0 && counter % graphGrouping == 0) { tempX = (int) (tempX + padding * 5); stackGroupTemp = 0; } if (counter % graphGrouping == 0) heightBar = (int) ((originY) - (data.get(counter) * ratio)); else heightBar = (int) ((stackGroupTemp) - (data.get(counter) * ratio)); paint.setShader(new LinearGradient(tempX, heightBar, (int) (tempX + padding * 4), (stackGroupTemp == 0) ? originY : stackGroupTemp, color.get((counter % graphGrouping) % color.size())[0], color.get((counter % graphGrouping) % color.size())[1], Shader.TileMode.MIRROR)); Rect bar = new Rect(tempX, heightBar, (int) (tempX + padding * 4), (stackGroupTemp == 0) ? originY : stackGroupTemp); stackGroupTemp = heightBar; canvas.drawRect(bar, paint); /** Add it to the items array **/ barGraphObject.add(new BarGraphObject(bar, String.valueOf(data .get(counter)))); canvas.drawText(data.get(counter) + "", tempX + padding * 2, heightBar + (mRenderer.getXAxisLabelSize() + 2), stackBarTextPaint); if (counter % graphGrouping == 0) { canvas.save(); canvas.rotate(xAxisLabelRotation, (float) (tempX + 2 * padding), (originY + xAxisLabelDistance)); canvas.drawText(barLabels.get(barLabelsCounter++), (float) (tempX + 2 * padding), originY + xAxisLabelDistance, xAxesLabelTextPaint); canvas.restore(); if (counter > 0 && counter % 6 == 0) { currentSecondXLabelValue = (float) (tempX + 2 * padding); } } } break; } // Restore canvas after zooming and translating canvas.restore(); invalidate(); }
diff --git a/src/edu/unh/cs/tact/Checker.java b/src/edu/unh/cs/tact/Checker.java index d73006a..43c58d6 100644 --- a/src/edu/unh/cs/tact/Checker.java +++ b/src/edu/unh/cs/tact/Checker.java @@ -1,141 +1,141 @@ // Copyright © 2012 Steve McCoy under the MIT license. package edu.unh.cs.tact; import java.util.*; import static java.util.Collections.*; import java.lang.ref.*; import java.lang.reflect.*; public class Checker{ private static Map<Object, WeakReference<Thread>> owners = synchronizedMap(new WeakHashMap<Object, WeakReference<Thread>>()); private static Map<Object, Object> runtimeGuarded = synchronizedMap(new WeakHashMap<Object, Object>()); public static void check(Object o){ if(o == null) return; Thread ct = Thread.currentThread(); Object guard = runtimeGuarded.get(o); if(guard != null){ if(!Thread.holdsLock(guard)) throw new IllegalAccessError(String.format( - "BAD unguarded-access [this] (%s -> %s)", + "BAD unguarded-access [general] (%s -> %s)", o, Thread.currentThread())); } WeakReference<Thread> ref = owners.get(o); if(ref == null){ owners.put(o, new WeakReference<Thread>(ct)); //System.err.printf("OK claim \"%s\" -> %s\n", o, ct); return; } Thread owner = ref.get(); if(owner == null) throw new IllegalAccessError(String.format("BAD re-thread \"%s\" -> %s\n", o, ct)); if(owner.equals(ct)){ //System.err.printf("OK access (%s -> %s)\n", o, ct); return; } throw new IllegalAccessError(String.format("BAD access (%s -> %s)\n", o, ct)); } public static void guardByThis(Object o){ if(o == null) return; if(!Thread.holdsLock(o)) throw new IllegalAccessError(String.format( "BAD unguarded-access [this] (%s -> %s)", o, Thread.currentThread())); } public static void guardByStatic(Object o, String guard){ if(o == null) return; int fieldPos = guard.lastIndexOf('.'); if(fieldPos == -1 || fieldPos == guard.length()-1) throw new AssertionError("Bad guard name: \""+guard+"\""); String className = guard.substring(0, fieldPos); String field = guard.substring(fieldPos+1); Object g = null; try{ Class<?> c = Class.forName(className); Field f = c.getDeclaredField(field); boolean acc = f.isAccessible(); f.setAccessible(true); g = f.get(null); f.setAccessible(acc); }catch(ClassNotFoundException e){ throw new RuntimeException(e); }catch(NoSuchFieldException e){ throw new RuntimeException(e); }catch(IllegalAccessException e){ throw new RuntimeException(e); } if(!Thread.holdsLock(g)) throw new IllegalAccessError(String.format( "BAD unguarded-access [static] (%s -> %s)", o, Thread.currentThread())); } public static void release(Object o){ if(o == null) return; Thread ct = Thread.currentThread(); WeakReference<Thread> ref = owners.get(o); if(ref == null) throw new IllegalAccessError( String.format("BAD release-unowned (%s <- %s)", o, ct)); Thread owner = ref.get(); if(owner == null){ //System.err.printf("OK release-again (%s <- %s)", o, ct); return; } if(owner.equals(ct)){ owners.remove(o); //System.err.printf("OK release (%s <- %s)\n", o, ct); return; } throw new IllegalAccessError(String.format("BAD release (%s <- %s)\n", o, ct)); } public static void guardBy(Object o, Object guard){ Object oldGuard = runtimeGuarded.put(o, guard); if(oldGuard != null && !oldGuard.equals(guard)) throw new IllegalAccessError(String.format("BAD new-guard (%s, %s -> %s)", o, oldGuard, guard)); } public static void releaseAndStart(Runnable r){ Thread t = new Thread(r); giveTo(r, t); t.start(); } public static void releaseAndStart(Thread t){ giveTo(t, t); t.start(); } private static synchronized void giveTo(Object o, Thread t){ release(o); owners.put(o, new WeakReference<Thread>(t)); } }
true
true
public static void check(Object o){ if(o == null) return; Thread ct = Thread.currentThread(); Object guard = runtimeGuarded.get(o); if(guard != null){ if(!Thread.holdsLock(guard)) throw new IllegalAccessError(String.format( "BAD unguarded-access [this] (%s -> %s)", o, Thread.currentThread())); } WeakReference<Thread> ref = owners.get(o); if(ref == null){ owners.put(o, new WeakReference<Thread>(ct)); //System.err.printf("OK claim \"%s\" -> %s\n", o, ct); return; } Thread owner = ref.get(); if(owner == null) throw new IllegalAccessError(String.format("BAD re-thread \"%s\" -> %s\n", o, ct)); if(owner.equals(ct)){ //System.err.printf("OK access (%s -> %s)\n", o, ct); return; } throw new IllegalAccessError(String.format("BAD access (%s -> %s)\n", o, ct)); }
public static void check(Object o){ if(o == null) return; Thread ct = Thread.currentThread(); Object guard = runtimeGuarded.get(o); if(guard != null){ if(!Thread.holdsLock(guard)) throw new IllegalAccessError(String.format( "BAD unguarded-access [general] (%s -> %s)", o, Thread.currentThread())); } WeakReference<Thread> ref = owners.get(o); if(ref == null){ owners.put(o, new WeakReference<Thread>(ct)); //System.err.printf("OK claim \"%s\" -> %s\n", o, ct); return; } Thread owner = ref.get(); if(owner == null) throw new IllegalAccessError(String.format("BAD re-thread \"%s\" -> %s\n", o, ct)); if(owner.equals(ct)){ //System.err.printf("OK access (%s -> %s)\n", o, ct); return; } throw new IllegalAccessError(String.format("BAD access (%s -> %s)\n", o, ct)); }
diff --git a/netbeans-gradle-default-models/src/main/groovy/org/netbeans/gradle/model/BuildOperationArgs.java b/netbeans-gradle-default-models/src/main/groovy/org/netbeans/gradle/model/BuildOperationArgs.java index 7a27578c..d3917d0e 100644 --- a/netbeans-gradle-default-models/src/main/groovy/org/netbeans/gradle/model/BuildOperationArgs.java +++ b/netbeans-gradle-default-models/src/main/groovy/org/netbeans/gradle/model/BuildOperationArgs.java @@ -1,103 +1,103 @@ package org.netbeans.gradle.model; import java.io.File; import java.io.InputStream; import java.io.OutputStream; import org.gradle.tooling.LongRunningOperation; import org.gradle.tooling.ProgressListener; public final class BuildOperationArgs { private OutputStream standardOutput; private OutputStream standardError; private InputStream standardInput; private File javaHome; private String[] jvmArguments; private String[] arguments; private ProgressListener[] progressListeners = new ProgressListener[0]; public OutputStream getStandardOutput() { return standardOutput; } public void setStandardOutput(OutputStream standardOutput) { this.standardOutput = standardOutput; } public OutputStream getStandardError() { return standardError; } public void setStandardError(OutputStream standardError) { this.standardError = standardError; } public InputStream getStandardInput() { return standardInput; } public void setStandardInput(InputStream standardInput) { this.standardInput = standardInput; } public File getJavaHome() { return javaHome; } public void setJavaHome(File javaHome) { this.javaHome = javaHome; } public String[] getJvmArguments() { return jvmArguments != null ? jvmArguments.clone() : null; } public void setJvmArguments(String... jvmArguments) { this.jvmArguments = jvmArguments != null ? jvmArguments.clone() : null; } public String[] getArguments() { return arguments != null ? arguments.clone() : null; } public void setArguments(String... arguments) { this.arguments = arguments != null ? arguments.clone() : null; } public ProgressListener[] getProgressListeners() { return progressListeners.clone(); } public void setProgressListeners(ProgressListener[] progressListeners) { this.progressListeners = progressListeners.clone(); } public void setupLongRunningOP(LongRunningOperation op) { if (javaHome != null) { op.setJavaHome(javaHome); } - if (arguments == null) { + if (arguments != null) { op.withArguments(arguments.clone()); } if (jvmArguments != null) { op.setJvmArguments(jvmArguments.clone()); } if (standardOutput != null) { op.setStandardOutput(standardOutput); } if (standardError != null) { op.setStandardError(standardError); } if (standardInput != null) { op.setStandardInput(standardInput); } for (ProgressListener listener: progressListeners) { op.addProgressListener(listener); } } }
true
true
public void setupLongRunningOP(LongRunningOperation op) { if (javaHome != null) { op.setJavaHome(javaHome); } if (arguments == null) { op.withArguments(arguments.clone()); } if (jvmArguments != null) { op.setJvmArguments(jvmArguments.clone()); } if (standardOutput != null) { op.setStandardOutput(standardOutput); } if (standardError != null) { op.setStandardError(standardError); } if (standardInput != null) { op.setStandardInput(standardInput); } for (ProgressListener listener: progressListeners) { op.addProgressListener(listener); } }
public void setupLongRunningOP(LongRunningOperation op) { if (javaHome != null) { op.setJavaHome(javaHome); } if (arguments != null) { op.withArguments(arguments.clone()); } if (jvmArguments != null) { op.setJvmArguments(jvmArguments.clone()); } if (standardOutput != null) { op.setStandardOutput(standardOutput); } if (standardError != null) { op.setStandardError(standardError); } if (standardInput != null) { op.setStandardInput(standardInput); } for (ProgressListener listener: progressListeners) { op.addProgressListener(listener); } }
diff --git a/src/main/java/shibauth/confluence/authentication/shibboleth/RemoteUserAuthenticator.java b/src/main/java/shibauth/confluence/authentication/shibboleth/RemoteUserAuthenticator.java index 8a621af..affca3e 100644 --- a/src/main/java/shibauth/confluence/authentication/shibboleth/RemoteUserAuthenticator.java +++ b/src/main/java/shibauth/confluence/authentication/shibboleth/RemoteUserAuthenticator.java @@ -1,1184 +1,1192 @@ /* Copyright (c) 2008, Shibboleth Authenticator for Confluence Team 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 Shibboleth Authenticator for Confluence Team 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. */ /* * Modified 2009-09-29 call super.login() if REMOTE_USER wasn't set to enable local Confluence login (SHBL-24) [Juhani Gurney] * Modified 2009-01-22 to make use of ShibLoginFilter (SHBL-16), make updateLastLogin as optional [Bruc Liong] * Modified 2009-01-05 to revamp the mapping processing mechanism to handle regex, purging roles, etc (SHBL-6) [Bruc Liong] * Modified 2008-12-03 to encorporate patch from Vladimir Mencl for SHBL-8 related to CONF-12158 (DefaultUserAccessor checks permissions before adding membership in 2.7 and later) * Modified 2008-07-29 to fix UTF-8 encoding [Helsinki University], made UTF-8 fix optional [Duke University] * Modified 2008-01-07 to add role mapping from shibboleth attribute (role) to confluence group membership. [Macquarie University - MELCOE - MAMS], refactor config loading, constants, utility method, and added configuration VO [Duke University] * Modified 2007-05-21 additional checks/logging and some small refactoring. Changed to use UserAccessor so should work with Confluence 2.3+ [Duke University] * Original version by Georgetown University. Original version (v1.0) can be found here: https://svn.middleware.georgetown.edu/confluence/remoteAuthn */ package shibauth.confluence.authentication.shibboleth; //~--- JDK imports ------------------------------------------------------------ import com.atlassian.confluence.user.ConfluenceAuthenticator; import com.atlassian.confluence.user.UserAccessor; import com.atlassian.seraph.config.SecurityConfig; import com.atlassian.user.Group; import com.atlassian.user.User; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.atlassian.spring.container.ContainerManager; import com.atlassian.user.EntityException; import com.atlassian.user.GroupManager; import com.atlassian.confluence.user.UserPreferencesKeys; import com.opensymphony.module.propertyset.PropertyException; import com.atlassian.user.search.page.Pager; import com.atlassian.confluence.event.events.security.LoginEvent; import com.atlassian.confluence.event.events.security.LoginFailedEvent; import com.atlassian.seraph.auth.AuthenticatorException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.security.Principal; import java.io.File; import java.util.Arrays; import java.util.Collection; import java.util.Enumeration; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Date; /** * An authenticator that uses the REMOTE_USER header as proof of authentication. * <p/> * Configuration properties are looked for in * <i>/remoteUserAuthenticator.properties</i> on the classpath. This file * may contain the following properties: * <ul> * <li><strong>convert.to.utf8</strong> - Convert all incoming header values to UTF-8</li> * <li><strong>create.users</strong> - Indicates whether accounts should be * created for individuals the first they are encountered * (acceptable values: true/false)</li> * <li><strong>update.info</strong> - Indicates whether existing accounts * should have their name and email address information * updated when the user logs in (acceptable values: true/false)</li> * <li><strong>default.roles</strong> - The default roles newly created * accounts will be given (format: comma seperated list)</li> * <li><strong>purge.roles</strong> - Roles to be purged automatically of users * who don't have attributes to regain membership anymore (comma/semicolon * separated regex)</li> * <li><strong>reload.config</strong> - Automatically reload config when * change</li> * <li><strong>header.fullname</strong> - The name of the HTTP header that * will carry the full name of the user</li> * <li><strong>header.email</strong> - The name of the HTTP header that will * carry the email address for the user</li> * * <li><strong>update.roles</strong> - Indicates whether the existing accounts * should have their roles updated based on the header information. note: old * roles are not removed if the header doesn't contain it. (Acceptable values: * true/false. Default to false)</li> * * <li><strong>dynamicroles.auto_create_role</strong> - should new roles be * automatically created in confluence (and users assigned to it). Default to false * * <li><strong>dynamicroles.header.XXX</strong> - XXX is the name of the * HTTP header that will carry user's role information. Lists the mapper * names that are supposed to handle these roles. Mapper labels separated by * comma or semicolon. If this entry is empty or not existing, then no dynamic * role mapping loaded for this particular header. Example: * dynamicroles.header.SHIB-EP-ENTITLEMENT = mapper1, label5</li> * <li><strong>dynamicroles.mapper.YYY </strong> - YYY is the label name for the * mapper. This mapper is responsible of matching the input and processing * value transformation on the input. The output of the mapper is the role * supplied to confluence.See further examples in properties * file for details. * <ul><li><strong>match</strong> - regex for the mapper to match against * the given input</li> * <li><strong>casesensitive</strong> - should the matching performed by 'match' * be case sensitive. Default to true</li> * <li><strong>transform</strong> - a fix string replacement of the input * (e.g. the group or groups). when not specified, it will simply takes the * input value. roles as the result of matching input (separated by comma or * semicolon). parts of initial input can be used here in the form * of $0, $1...$N where $0 represents the whole input string, $1...N represent * regex groupings as used in 'match' regex</li> * </ul> * Example: <br/> * dynamicroles.mapper.label5.match = some\:example\:(.+)\:role-(.*) <br/> * dynamicroles.mapper.label5.transform = $1, $2, confluence-$2 * </li> * </ul> */ public class RemoteUserAuthenticator extends ConfluenceAuthenticator { //~--- static fields ------------------------------------------------------ /** * Serial version UID */ private static final long serialVersionUID = -5608187140008286795L; /** * Logger */ private final static Log log = LogFactory.getLog(RemoteUserAuthenticator.class); private static ShibAuthConfiguration config; /** See SHBL-8, CONF-12158, and http://confluence.atlassian.com/download/attachments/192312/ConfluenceGroupJoiningAuthenticator.java?version=1 */ private GroupManager groupManager = null; //~--- static initializers ------------------------------------------------ /** * Initialize properties from property file */ static { //TODO: use UI to configure if possible //TODO: use Spring to configure config loader, etc. config = ShibAuthConfigLoader.getShibAuthConfiguration(null); } /** * Check if the configuration file should be reloaded and reload the configuration. */ private void checkReloadConfig() { if (config.isReloadConfig() && (config.getConfigFile() != null)) { if (System.currentTimeMillis() < config.getConfigFileLastChecked() + config. getReloadConfigCheckInterval()) { return; } long configFileLastModified = new File(config.getConfigFile()). lastModified(); if (configFileLastModified != config.getConfigFileLastModified()) { log.debug("Config file has been changed, reloading"); config = ShibAuthConfigLoader.getShibAuthConfiguration(config); } else { log.debug("Config file has not been changed, not reloading"); config.setConfigFileLastChecked(System.currentTimeMillis()); } } } //~--- methods ------------------------------------------------------------ /** * Assigns a user to the roles. * * @param user the user to assign to the roles. */ private void assignUserToRoles(User user, Collection roles) { if (roles.size() == 0) { if (log.isDebugEnabled()) { log.debug("No roles specified, not adding any roles..."); } } else { //if (log.isDebugEnabled()) { // log.debug("Assigning roles to user " + user.getName()); //} String role; Group group; for (Iterator it = roles.iterator(); it.hasNext();) { role = it.next().toString().trim(); if (role.length() == 0) { continue; } if (log.isDebugEnabled()) { log.debug("Assigning " + user.getName() + " to role " + role); } try { group = getGroupManager().getGroup(role); if (group == null) { if (config.isAutoCreateGroup()) { if (getGroupManager().isCreative()) { group = getGroupManager().createGroup(role); } else { log.warn( "Cannot create role '" + role + "' due to permission issue."); continue; } } else { log.debug( "Skipping autocreation of role '" + role + "'."); continue; //no point of attempting to allocate user } } if (getGroupManager().hasMembership(group, user)) { log.debug("Skipping " + user.getName() + " to role " + role + " - already a member"); } else { getGroupManager().addMembership(group, user); } } catch (Exception e) { log.error( "Attempted to add user " + user + " to role " + role + " but the role does not exist.", e); } } } } /** * Purge user from roles it no longer should have (based on current Shibboleth attributes). * Remove the user from all roles listed in purgeRoles that are not * included in the current list of roles the user would get assigned to * based on the Shibboleth attributes received. * * @param user the user to assign to the roles. * @param rolesToKeep keep these roles, otherwise everything else * mentioned in the purgeMappings can go. */ private void purgeUserRoles(User user, Collection rolesToKeep) { if ((config.getPurgeMappings().size() == 0)) { if (log.isDebugEnabled()) { log.debug( "No roles to purge specified, not purging any roles..."); } } else { Pager p = null; if (log.isDebugEnabled()) { log.debug("Purging roles from user " + user.getName()); } try { //get intersection of rolesInConfluence and rolesToKeep p = getGroupManager().getGroups(user); if (p.isEmpty()) { log.debug("No roles available to be purged for this user."); return; } } catch (EntityException ex) { log.error("Fail to fetch user's group list, no roles purged.", ex); } Collection purgeMappers = config.getPurgeMappings(); for (Iterator it = p.iterator(); it.hasNext();) { Group group = (Group) it.next(); String role = group.getName(); //log.debug("Checking group "+role+" for purging."); if (!StringUtil.containsStringIgnoreCase(rolesToKeep,role)) { //run through the purgeMappers for this role for (Iterator it2 = purgeMappers.iterator(); it2.hasNext();) { GroupMapper mapper = (GroupMapper) it2.next(); //max only 1 group output String output = mapper.process(role); if (output != null) { try { log.debug( "Removing user " + user.getName() + " from role " + role); getGroupManager().removeMembership(group, user); break; //dont bother to continue with other purge mappers } catch (Throwable e) { log.error( "Error encountered in removing user " + user. getName() + " from role " + role, e); } } } } else { log.debug("Keeping role " + role + " for user " + user. getName()); } } } } /** * Change userid to lower case. * * @param userid userid to be changed * @return lower case version of it */ private String convertUsername(String userid) { if (userid != null) { userid = userid.toLowerCase(); } return userid; } /** * Creates a new user if the configuration allows it. * * @param userid user name for the new user * @return the new user */ private Principal createUser(String userid) { UserAccessor userAccessor = getUserAccessor(); Principal user = null; if (config.isCreateUsers()) { if (log.isInfoEnabled()) { log.info("Creating user account for " + userid); } try { user = userAccessor.createUser(userid); } catch (Throwable t) { // Note: just catching EntityException like we used to do didn't // seem to cover Confluence massive with Oracle if (log.isDebugEnabled()) { log.debug( "Error creating user " + userid + ". Will ignore and try to get the user (maybe it was already created)", t); } user = getUser(userid); if (user == null) { log.error( "Error creating user " + userid + ". Got null user after attempted to create user (so it probably was not a duplicate).", t); } } } else { if (log.isDebugEnabled()) { log.debug( "Configuration does NOT allow for creation of new user accounts, authentication will fail for " + userid); } } return user; } private void updateUser(Principal user, String fullName, String emailAddress) { UserAccessor userAccessor = getUserAccessor(); // If we have new values for name or email, update the user object if ((user != null) && (user instanceof User)) { User userToUpdate = (User) user; boolean updated = false; // SHBL-26: patch from Michael Gettes to skip read-only users (for example: user from LDAP, etc.) if (userAccessor.isReadOnly(userToUpdate)) { if (log.isDebugEnabled()) { log.debug("not updating user, because user is read-only"); } return; } if ((fullName != null) && !fullName.equals( userToUpdate.getFullName())) { if (log.isDebugEnabled()) { log.debug("updating user fullName to '" + fullName + "'"); } userToUpdate.setFullName(fullName); updated = true; } else { if (log.isDebugEnabled()) { log.debug( "new user fullName is same as old one: '" + fullName + "'"); } } if ((emailAddress != null) && !emailAddress.equals(userToUpdate. getEmail())) { if (log.isDebugEnabled()) { log.debug( "updating user emailAddress to '" + emailAddress + "'"); } userToUpdate.setEmail(emailAddress); updated = true; } else { if (log.isDebugEnabled()) { log.debug( "new user emailAddress is same as old one: '" + emailAddress + "'"); } } if (updated) { try { userAccessor.saveUser(userToUpdate); } catch (Throwable t) { log.error("Couldn't update user " + userToUpdate.getName(), t); } } } } /** * Updates last login and previous login dates. Originally contributed by Erkki Aalto and written by Jesse Lahtinen of (Finland) Technical University (http://www.tkk.fi) in SHBL-14. * Note bug in USER-254. * Further, this is optional if you are using ShibLoginFilter */ private void updateLastLogin(Principal principal) { //Set last login date // synchronize on the user name -- it's quite alright to update the property sets of two different users // in seperate concurrent transactions, but two concurrent transactions updateing the same user's property // set dies. //synchronized (userid.intern()) { // note: made a few slight changes to code- Gary. UserAccessor userAccessor = getUserAccessor(); User user = (User) principal; String userId = user.getName(); // TODO: Shouldn't synchronize, because that wouldn't help in a Confluence cluster (diff JVMs) for Confluence Enterprise/Confluence Massive. This should be added as a Confluence bug. synchronized (userId) { try { Date previousLoginDate = userAccessor.getPropertySet(user). getDate(UserPreferencesKeys.PROPERTY_USER_LAST_LOGIN_DATE); if (previousLoginDate != null) { try { userAccessor.getPropertySet(user).remove( UserPreferencesKeys.PROPERTY_USER_LAST_LOGIN_DATE); userAccessor.getPropertySet(user).setDate( UserPreferencesKeys.PROPERTY_USER_LAST_LOGIN_DATE, new Date()); userAccessor.getPropertySet(user).remove( UserPreferencesKeys.PROPERTY_USER_PREVIOUS_LOGIN_DATE); userAccessor.getPropertySet(user).setDate( UserPreferencesKeys.PROPERTY_USER_PREVIOUS_LOGIN_DATE, previousLoginDate); } catch (PropertyException ee) { log.error( "Problem updating last login date/previous login date for user '" + userId + "'", ee); } } else { try { userAccessor.getPropertySet(user).remove( UserPreferencesKeys.PROPERTY_USER_LAST_LOGIN_DATE); userAccessor.getPropertySet(user).setDate( UserPreferencesKeys.PROPERTY_USER_LAST_LOGIN_DATE, new Date()); userAccessor.getPropertySet(user).remove( UserPreferencesKeys.PROPERTY_USER_PREVIOUS_LOGIN_DATE); userAccessor.getPropertySet(user).setDate( UserPreferencesKeys.PROPERTY_USER_PREVIOUS_LOGIN_DATE, new Date()); } catch (PropertyException ee) { log.error( "There was a problem updating last login date/previous login date for user '" + userId + "'", ee); } } } catch (Exception e) { log.error( "Can not retrieve the user ('" + userId + "') to set its Last-Login-Date!", e); } catch (Throwable t) { log.error( "Error while setting the user ('" + userId + "') Last-Login-Date!", t); } } } //~--- get methods -------------------------------------------------------- private String getEmailAddress(HttpServletRequest request) { String emailAddress = null; if (config.getEmailHeaderName()!=null) { // assumes it is first value in list, if header is defined multiple times. Otherwise would need to call getHeaders() String headerValue = request.getHeader(config.getEmailHeaderName()); // the Shibboleth SP sends multiple values as single value, separated by comma or semicolon List values = StringUtil. toListOfNonEmptyStringsDelimitedByCommaOrSemicolon(headerValue); if (values != null && values.size() > 0) { // use the first email in the list emailAddress = (String) values.get(0); if (log.isDebugEnabled()) { log.debug("Got emailAddress '" + emailAddress + "' for header '" + config. getEmailHeaderName() + "'"); } if (config.isConvertToUTF8()) { String tmp = StringUtil.convertToUTF8(emailAddress); if (tmp != null) { emailAddress = tmp; if (log.isDebugEnabled()) { log.debug("emailAddress converted to UTF-8 '" + emailAddress + "' for header '" + config. getEmailHeaderName() + "'"); } } } } if ((emailAddress != null) && (emailAddress.length() > 0)) { emailAddress = emailAddress.toLowerCase(); } } else { if (log.isDebugEnabled()) { log.debug("user email address header name in config was null/not specified"); } } return emailAddress; } private String getFullName(HttpServletRequest request, String userid) { String fullName = null; if (config.getFullNameHeaderName()!=null) { // assumes it is first value in list, if header is defined multiple times. Otherwise would need to call getHeaders() String headerValue = request.getHeader(config.getFullNameHeaderName()); // the Shibboleth SP sends multiple values as single value, separated by comma or semicolon List values = StringUtil. toListOfNonEmptyStringsDelimitedByCommaOrSemicolon(headerValue); if (values != null && values.size() > 0) { if (log.isDebugEnabled()) { log.debug("Original value of full name header '" + config. getFullNameHeaderName() + "' was '" + headerValue + "'"); } // use the first full name in the list //fullName = (String) values.get(1) + " " + (String) values.get(0); if (config.getFullNameMappings() == null || config.getFullNameMappings().size() == 0) { // default if no fullname mappings is to just use the first header value fullName = (String) values.get(0); } else { fullName = createFullNameUsingMapping(headerValue, values); } if (log.isDebugEnabled()) { log.debug("Got fullName '" + fullName + "' for header '" + config. getFullNameHeaderName() + "'"); } if (config.isConvertToUTF8()) { String tmp = StringUtil.convertToUTF8(fullName); if (tmp != null) { fullName = tmp; if (log.isDebugEnabled()) { log.debug("fullName converted to UTF-8 '" + fullName + "' for header '" + config. getFullNameHeaderName() + "'"); } } } } else { if (log.isDebugEnabled()) { log.debug("user full name header name in config was null/not specified"); } } } if ((fullName == null) || (fullName.length() == 0)) { if (log.isDebugEnabled()) { log.debug("User full name was null or empty. Defaulting full name to user id"); } fullName = userid; } return fullName; } /** * This will populate accumulated (containing all roles discovered). * */ private void getRolesFromHeader(HttpServletRequest request, Set accumulatedRoles) { Set attribHeaders = config.getGroupMappingKeys(); // check if we're interested in some headers if (attribHeaders.isEmpty()) { return; } // log headers (this is helpful to users for debugging what is sent in) if (log.isDebugEnabled()) { StringBuffer sb = new StringBuffer("HTTP Headers: "); boolean concat = false; for (Enumeration en = request.getHeaderNames(); en.hasMoreElements(); ) { if (concat) { sb.append(", "); } String headerName = en.nextElement().toString(); sb.append("'" + headerName + "' = '" + request.getHeader(headerName) + "'"); concat = true; } log.debug(sb.toString()); } //process the headers by looking up only those list of registered headers for (Iterator headerIt = attribHeaders.iterator(); headerIt.hasNext();) { String headerName = headerIt.next().toString(); for (Enumeration en = request.getHeaders(headerName); en. hasMoreElements();) { String headerValue = en.nextElement().toString(); //shib sends values in semicolon separated, so split it up too List headerValues = StringUtil. toListOfNonEmptyStringsDelimitedByCommaOrSemicolon( headerValue); for (int j = 0; j < headerValues.size(); j++) { headerValue = (String) headerValues.get(j); if (config.isConvertToUTF8()) { String tmp = StringUtil.convertToUTF8(headerValue); if (tmp != null) { headerValue = tmp; } } log.debug("Processing dynamicroles header=" + headerName + ", value=" + headerValue); Collection mappers = config.getGroupMappings(headerName); boolean found = false; for (Iterator mapperIt = mappers.iterator(); mapperIt. hasNext();) { GroupMapper mapper = (GroupMapper) mapperIt.next(); //we may get multiple groups returned by a single matched //e.g. matching "XXX" --> "A, B, C" String[] results = (String[]) StringUtil. toListOfNonEmptyStringsDelimitedByCommaOrSemicolon( mapper.process(headerValue)).toArray(new String[0]); for (int i = 0; i < results.length; i++) { String result = results[i]; if (result.length() != 0) { if (!accumulatedRoles.contains(result)) { if(config.isOutputToLowerCase()) result = result.toLowerCase(); accumulatedRoles.add(result); log.debug("Found role mapping from '" + headerValue + "' to '" + result + "'"); } found = true; } } } if (!found) { log.debug( "No mapper capable of processing role value=" + headerValue); } } } } } // converting reliance on getUser(request,response) to use login() instead. // the logic flow: // 1) Seraph Login filter, which is based on username/password kicks in (declared at web.xml) // 2) it bails out altogether and identified user as invalid (without calling any of login(request,response) declared here // 3) Seraph Security filter kicks in (declared at web.xml) // 4) it calls getUser(request,response) and assign roles to known user // hence, getUser(request,response) will only be called from Seraph SecurityFilter // this pluggin uses ShibLoginFilter to make sure login is performed, however in the case ShibLoginFilter is // not configured, it will still work ;) /** * @see com.atlassian.confluence.user.ConfluenceAuthenticator#login( * javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse, * java.lang.String username, * java.lang.String password, * boolean cookie) * * Check if user has been authenticated by Shib. Username, password, and cookie are totally ignored. */ public boolean login(HttpServletRequest request, HttpServletResponse response, String username, String password, boolean cookie) throws AuthenticatorException{ if (log.isDebugEnabled()) { log.debug( "Request made to " + request.getRequestURL() + " triggered this AuthN check"); } HttpSession httpSession = request.getSession(); Principal user = null; // for those interested on the events String remoteIP = request.getRemoteAddr(); String remoteHost = request.getRemoteHost(); // Check if the user is already logged in if (httpSession.getAttribute(ConfluenceAuthenticator.LOGGED_IN_KEY) != null) { user = (Principal) httpSession.getAttribute( ConfluenceAuthenticator.LOGGED_IN_KEY); if (log.isDebugEnabled()) { log.debug(user.getName() + " already logged in, returning."); } return true; } // Since they aren't logged in, get the user name from // the REMOTE_USER header String userid = createSafeUserid(request.getRemoteUser()); if ((userid == null) || (userid.length() <= 0)) { if (log.isDebugEnabled()) { log.debug( "Remote user was null or empty, calling super.login() to perform local login"); } // Calling super.login to try local login if username and password are set // However, this won't work if ShibLoginFilter is used if (username != null && password != null) { if (log.isDebugEnabled()) log.debug("Trying local login for user "+username); return super.login(request, response, username, password, cookie); } } // Now that we know we will be trying to log the user in, // let's see if we should reload the config file first checkReloadConfig(); // Convert username to all lowercase userid = convertUsername(userid); // Pull name and address from headers String fullName = getFullName(request, userid); String emailAddress = getEmailAddress(request); // Try to get the user's account based on the user name user = getUser(userid); boolean newUser = false; // User didn't exist or was problem getting it. we'll try to create it // if we can, otherwise will try to get it again. if (user == null) { user = createUser(userid); if (user != null) { newUser = true; updateUser(user, fullName, emailAddress); //username will only be null if called from getUser() if (username == null && config.isUpdateLastLogin()) updateLastLogin(user); } } else { if (config.isUpdateInfo()) { updateUser(user, fullName, emailAddress); //username will only be null if called from getUser() if (username == null && config.isUpdateLastLogin()) updateLastLogin(user); } } if (config.isUpdateRoles() || newUser) { Set roles = new HashSet(); //fill up the roles getRolesFromHeader(request, roles); assignUserToRoles((User) user, config.getDefaultRoles()); assignUserToRoles((User) user, roles); //make sure we don't purge default roles either roles.addAll(config.getDefaultRoles()); purgeUserRoles((User) user, roles); } // Now that we have the user's account, add it to the session and return if (log.isDebugEnabled()) { log.debug("Logging in user " + user.getName()); } httpSession.setAttribute( ConfluenceAuthenticator.LOGGED_IN_KEY, user); httpSession.setAttribute( ConfluenceAuthenticator.LOGGED_OUT_KEY, null); getEventManager().publishEvent(new LoginEvent(this, user.getName(), httpSession.getId(), remoteHost, remoteIP)); return true; } public Principal getUser(HttpServletRequest request, HttpServletResponse response) { if (config.isUsingShibLoginFilter()) { return getUserForShibLoginFilter(request, response); } return getUserForAtlassianLoginFilter(request, response); } /** * Changes provided by colleague of Hans-Ulrich Pieper of Freie Universität Berlin * */ public Principal getUserForAtlassianLoginFilter(HttpServletRequest request, HttpServletResponse response) { if (log.isDebugEnabled()) { log.debug( "Request made to " + request.getRequestURL() + " triggered this AuthN check"); } HttpSession httpSession = request.getSession(); Principal user = null; // for those interested on the events String remoteIP = request.getRemoteAddr(); String remoteHost = request.getRemoteHost(); // Check if the user is already logged in if (httpSession.getAttribute(ConfluenceAuthenticator.LOGGED_IN_KEY) != null) { user = (Principal) httpSession.getAttribute( ConfluenceAuthenticator.LOGGED_IN_KEY); if (log.isDebugEnabled()) { log.debug(user.getName() + " already logged in, returning."); } return user; } // Since they aren't logged in, get the user name from // the REMOTE_USER header String userid = createSafeUserid(request.getRemoteUser()); if ((userid == null) || (userid.length() <= 0)) { if (log.isDebugEnabled()) { log.debug( "Remote user was null or empty, can not perform authentication"); } getEventManager().publishEvent(new LoginFailedEvent(this, "NoShibUsername", httpSession.getId(), remoteHost, remoteIP)); return null; } // Now that we know we will be trying to log the user in, // let's see if we should reload the config file first checkReloadConfig(); // Convert username to all lowercase userid = convertUsername(userid); // Pull name and address from headers String fullName = getFullName(request, userid); String emailAddress = getEmailAddress(request); // Try to get the user's account based on the user name user = getUser(userid); boolean newUser = false; // User didn't exist or was problem getting it. we'll try to create it // if we can, otherwise will try to get it again. if (user == null) { user = createUser(userid); if (user != null) { newUser = true; updateUser(user, fullName, emailAddress); + } else { + // If user is still null, probably we're using an + // external user database like LDAP. Either REMOTE_USER + // isn't present there or is being filtered out, e.g. + // by userSearchFilter + if (log.isDebugEnabled()) { + log.debug( + "User does not exist and cannot create"); + } + getEventManager().publishEvent(new LoginFailedEvent(this, "CannotCreateUser", httpSession.getId(), remoteHost, remoteIP)); - //username will only be null if called from getUser() - //if (username == null && config.isUpdateLastLogin()) - // updateLastLogin(user); + return null; } } else { if (config.isUpdateInfo()) { updateUser(user, fullName, emailAddress); //username will only be null if called from getUser() //if (username == null && config.isUpdateLastLogin()) // updateLastLogin(user); } } // TODO: All of this needs serious refactoring! // If config.isCreateUsers() == false, it would NPE later, so we // return null indicating that the login failed. Thanks to // Adam Cohen for noticing this and to Bruce Liong for helping // to contribute a quick fix, modified by Gary Weaver. (SHBL-34) if (user == null) { if (log.isDebugEnabled()) { log.debug("Login attempt by '" + userid + "' failed."); } return null; } if (config.isUpdateRoles() || newUser) { Set roles = new HashSet(); //fill up the roles getRolesFromHeader(request, roles); assignUserToRoles((User) user, config.getDefaultRoles()); assignUserToRoles((User) user, roles); //make sure we don't purge default roles either roles.addAll(config.getDefaultRoles()); purgeUserRoles((User) user, roles); } // Now that we have the user's account, add it to the session and return if (log.isDebugEnabled()) { log.debug("Logging in user " + user.getName()); } httpSession.setAttribute( ConfluenceAuthenticator.LOGGED_IN_KEY, user); httpSession.setAttribute( ConfluenceAuthenticator.LOGGED_OUT_KEY, null); getEventManager().publishEvent(new LoginEvent(this, user.getName(), httpSession.getId(), remoteHost, remoteIP)); //return true; return user; } private String createSafeUserid(String originalRemoteuser){ //possible to have multiple mappers defined, but //only 1 will produce the desired outcome Set possibleRemoteUsers = new HashSet(); Collection mappers = config.getRemoteUserMappings(); for (Iterator mapperIt = mappers.iterator(); mapperIt.hasNext();) { GroupMapper mapper = (GroupMapper) mapperIt.next(); String[] results = (String[]) StringUtil. toListOfNonEmptyStringsDelimitedByCommaOrSemicolon( mapper.process(originalRemoteuser)).toArray(new String[0]); if(results.length != 0) possibleRemoteUsers.addAll(Arrays.asList(results)); } if(possibleRemoteUsers.isEmpty()){ log.debug("Remote user is returned as is, mappers do not matched."); return originalRemoteuser; } if(log.isDebugEnabled() && possibleRemoteUsers.size() > 1){ log.debug("Remote user has been transformed, but there are too many results, choosing one that seems suitable"); } //just get a random one String output = possibleRemoteUsers.iterator().next().toString(); return remoteUserCharsReplacement(output); } //if remoteuser.replace is specified, process it //it has the format of pair-wise value, occurences of 1st entry regex is replaced //with what specified on the second entry //the list is comma or semi-colon separated (which means //pretty obvious a comma or semi-colon can't be used in the content replacement) private String remoteUserCharsReplacement(String remoteUser){ Iterator it = config.getRemoteUserReplacementChars(); while(it.hasNext()){ String replaceFromRegex = it.next().toString(); //someone didn't fill up pair-wise entry, ignore this regex if(!it.hasNext()){ if(replaceFromRegex.length() != 0) log.debug("Character replacements specified for Remote User regex is incomplete, make sure the entries are pair-wise, skipping..."); break; } String replacement = it.next().toString(); //we are not going to replace empty string, so skip it if(replaceFromRegex.length()==0){ log.debug("Empty string is found in Remote User replaceFrom regex, skipping..."); continue; } try{ remoteUser = remoteUser.replaceAll(replaceFromRegex, replacement); }catch(Exception e){ log.warn("Fail to replace certain character entries in \"Remote User\" matching regex=\""+replaceFromRegex+"\", ignoring..."); log.debug("Fail to replace certain character entries in Remote User",e); } } return remoteUser; } private String createFullNameUsingMapping(String originalFullNameHeaderValue, List values){ //possible to have multiple mappers defined, but //only 1 will produce the desired outcome Set possibleFullNames = new HashSet(); Collection mappers = config.getFullNameMappings(); for (Iterator mapperIt = mappers.iterator(); mapperIt.hasNext();) { GroupMapper mapper = (GroupMapper) mapperIt.next(); String[] results = (String[]) StringUtil. toListOfNonEmptyStringsDelimitedByCommaOrSemicolon( mapper.process(originalFullNameHeaderValue)).toArray(new String[0]); if(results.length != 0) possibleFullNames.addAll(Arrays.asList(results)); } if(possibleFullNames.isEmpty()){ log.debug("Full Name header value is returned as is, mappers do not match, so will use first value in list."); return (String) values.get(0); } if(log.isDebugEnabled() && possibleFullNames.size() > 1){ log.debug("Full name has been transformed, but there are too many results, choosing one that seems suitable"); } //just get a random one String output = possibleFullNames.iterator().next().toString(); return fullNameCharsReplacement(output); } //if fullname.replace is specified, process it //it has the format of pair-wise value, occurences of 1st entry regex is replaced //with what specified on the second entry //the list is comma or semi-colon separated (which means //pretty obvious a comma or semi-colon can't be used in the content replacement) private String fullNameCharsReplacement(String fullName){ Iterator it = config.getFullNameReplacementChars(); while(it.hasNext()){ String replaceFromRegex = it.next().toString(); //someone didn't fill up pair-wise entry, ignore this regex if(!it.hasNext()){ if(replaceFromRegex.length() != 0) log.debug("Character replacements specified for Full Name regex is incomplete, make sure the entries are pair-wise, skipping..."); break; } String replacement = it.next().toString(); //we are not going to replace empty string, so skip it if(replaceFromRegex.length()==0){ log.debug("Empty string is found in Full Name replaceFrom regex, skipping..."); continue; } try{ fullName = fullName.replaceAll(replaceFromRegex, replacement); }catch(Exception e){ log.warn("Fail to replace certain character entries in \"Remote User\" matching regex=\""+replaceFromRegex+"\", ignoring..."); log.debug("Fail to replace certain character entries in Remote User",e); } } return fullName; } /** * @see com.atlassian.seraph.auth.Authenticator#getUser( * javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) * * @param request * @param response * * @return */ public Principal getUserForShibLoginFilter(HttpServletRequest request, HttpServletResponse response) { // If using ShibLoginFilter, see SHBL-24 - Authentication with local accounts should be supported if (log.isDebugEnabled()) { log.debug( "Request made to " + request.getRequestURL() + " triggered this AuthN2 check"); } HttpSession httpSession = request.getSession(false); Principal user; // Check if the user is already logged in if ((httpSession != null) && (httpSession.getAttribute( ConfluenceAuthenticator.LOGGED_IN_KEY) != null)) { user = (Principal) httpSession.getAttribute( ConfluenceAuthenticator.LOGGED_IN_KEY); if (log.isDebugEnabled()) { log.debug(user.getName() + " already logged in, returning."); } return user; } //worst case scenario, this is executed when user has not logged in previously //perhaps admin forgot to change web.xml to use ShibLoginFilter ? try{ boolean authenticated = login(request,response,null,null,false); if (!authenticated) { return null; } }catch(Throwable t){ log.error("Failed to authenticate user", t); return null; } return getUser(request,response); } /** * This is the Atlassian-suggested way of handling the issue noticed by Vladimir Mencl in Confluence 2.9.2 (but not in 2.9) where * addMembership(...) was failing, and apparently it failed because it was expecting that GroupManager was not returning an instance. * I don't think we have a spring config (bean defined in spring config) for this authenticator yet, so wouldn't be set by that or autowiring I guess. * The solution provided by Vladimir Mencl and referred to by Matt Ryall in CONF-12158 is similar to that of the older ConfluenceGroupJoiningAuthenticator.java * provided with Confluence that Matt attached here: http://confluence.atlassian.com/download/attachments/192312/ConfluenceGroupJoiningAuthenticator.java?version=1 * See also SHBL-8. Thanks much to Vladimir Mencl for this patch. */ public GroupManager getGroupManager() { if (groupManager == null) { groupManager = (GroupManager) ContainerManager.getComponent( "groupManager"); } return groupManager; } public void setGroupManager(GroupManager groupManager) { this.groupManager = groupManager; } }
false
true
public Principal getUserForAtlassianLoginFilter(HttpServletRequest request, HttpServletResponse response) { if (log.isDebugEnabled()) { log.debug( "Request made to " + request.getRequestURL() + " triggered this AuthN check"); } HttpSession httpSession = request.getSession(); Principal user = null; // for those interested on the events String remoteIP = request.getRemoteAddr(); String remoteHost = request.getRemoteHost(); // Check if the user is already logged in if (httpSession.getAttribute(ConfluenceAuthenticator.LOGGED_IN_KEY) != null) { user = (Principal) httpSession.getAttribute( ConfluenceAuthenticator.LOGGED_IN_KEY); if (log.isDebugEnabled()) { log.debug(user.getName() + " already logged in, returning."); } return user; } // Since they aren't logged in, get the user name from // the REMOTE_USER header String userid = createSafeUserid(request.getRemoteUser()); if ((userid == null) || (userid.length() <= 0)) { if (log.isDebugEnabled()) { log.debug( "Remote user was null or empty, can not perform authentication"); } getEventManager().publishEvent(new LoginFailedEvent(this, "NoShibUsername", httpSession.getId(), remoteHost, remoteIP)); return null; } // Now that we know we will be trying to log the user in, // let's see if we should reload the config file first checkReloadConfig(); // Convert username to all lowercase userid = convertUsername(userid); // Pull name and address from headers String fullName = getFullName(request, userid); String emailAddress = getEmailAddress(request); // Try to get the user's account based on the user name user = getUser(userid); boolean newUser = false; // User didn't exist or was problem getting it. we'll try to create it // if we can, otherwise will try to get it again. if (user == null) { user = createUser(userid); if (user != null) { newUser = true; updateUser(user, fullName, emailAddress); //username will only be null if called from getUser() //if (username == null && config.isUpdateLastLogin()) // updateLastLogin(user); } } else { if (config.isUpdateInfo()) { updateUser(user, fullName, emailAddress); //username will only be null if called from getUser() //if (username == null && config.isUpdateLastLogin()) // updateLastLogin(user); } } // TODO: All of this needs serious refactoring! // If config.isCreateUsers() == false, it would NPE later, so we // return null indicating that the login failed. Thanks to // Adam Cohen for noticing this and to Bruce Liong for helping // to contribute a quick fix, modified by Gary Weaver. (SHBL-34) if (user == null) { if (log.isDebugEnabled()) { log.debug("Login attempt by '" + userid + "' failed."); } return null; } if (config.isUpdateRoles() || newUser) { Set roles = new HashSet(); //fill up the roles getRolesFromHeader(request, roles); assignUserToRoles((User) user, config.getDefaultRoles()); assignUserToRoles((User) user, roles); //make sure we don't purge default roles either roles.addAll(config.getDefaultRoles()); purgeUserRoles((User) user, roles); } // Now that we have the user's account, add it to the session and return if (log.isDebugEnabled()) { log.debug("Logging in user " + user.getName()); } httpSession.setAttribute( ConfluenceAuthenticator.LOGGED_IN_KEY, user); httpSession.setAttribute( ConfluenceAuthenticator.LOGGED_OUT_KEY, null); getEventManager().publishEvent(new LoginEvent(this, user.getName(), httpSession.getId(), remoteHost, remoteIP)); //return true; return user; }
public Principal getUserForAtlassianLoginFilter(HttpServletRequest request, HttpServletResponse response) { if (log.isDebugEnabled()) { log.debug( "Request made to " + request.getRequestURL() + " triggered this AuthN check"); } HttpSession httpSession = request.getSession(); Principal user = null; // for those interested on the events String remoteIP = request.getRemoteAddr(); String remoteHost = request.getRemoteHost(); // Check if the user is already logged in if (httpSession.getAttribute(ConfluenceAuthenticator.LOGGED_IN_KEY) != null) { user = (Principal) httpSession.getAttribute( ConfluenceAuthenticator.LOGGED_IN_KEY); if (log.isDebugEnabled()) { log.debug(user.getName() + " already logged in, returning."); } return user; } // Since they aren't logged in, get the user name from // the REMOTE_USER header String userid = createSafeUserid(request.getRemoteUser()); if ((userid == null) || (userid.length() <= 0)) { if (log.isDebugEnabled()) { log.debug( "Remote user was null or empty, can not perform authentication"); } getEventManager().publishEvent(new LoginFailedEvent(this, "NoShibUsername", httpSession.getId(), remoteHost, remoteIP)); return null; } // Now that we know we will be trying to log the user in, // let's see if we should reload the config file first checkReloadConfig(); // Convert username to all lowercase userid = convertUsername(userid); // Pull name and address from headers String fullName = getFullName(request, userid); String emailAddress = getEmailAddress(request); // Try to get the user's account based on the user name user = getUser(userid); boolean newUser = false; // User didn't exist or was problem getting it. we'll try to create it // if we can, otherwise will try to get it again. if (user == null) { user = createUser(userid); if (user != null) { newUser = true; updateUser(user, fullName, emailAddress); } else { // If user is still null, probably we're using an // external user database like LDAP. Either REMOTE_USER // isn't present there or is being filtered out, e.g. // by userSearchFilter if (log.isDebugEnabled()) { log.debug( "User does not exist and cannot create"); } getEventManager().publishEvent(new LoginFailedEvent(this, "CannotCreateUser", httpSession.getId(), remoteHost, remoteIP)); return null; } } else { if (config.isUpdateInfo()) { updateUser(user, fullName, emailAddress); //username will only be null if called from getUser() //if (username == null && config.isUpdateLastLogin()) // updateLastLogin(user); } } // TODO: All of this needs serious refactoring! // If config.isCreateUsers() == false, it would NPE later, so we // return null indicating that the login failed. Thanks to // Adam Cohen for noticing this and to Bruce Liong for helping // to contribute a quick fix, modified by Gary Weaver. (SHBL-34) if (user == null) { if (log.isDebugEnabled()) { log.debug("Login attempt by '" + userid + "' failed."); } return null; } if (config.isUpdateRoles() || newUser) { Set roles = new HashSet(); //fill up the roles getRolesFromHeader(request, roles); assignUserToRoles((User) user, config.getDefaultRoles()); assignUserToRoles((User) user, roles); //make sure we don't purge default roles either roles.addAll(config.getDefaultRoles()); purgeUserRoles((User) user, roles); } // Now that we have the user's account, add it to the session and return if (log.isDebugEnabled()) { log.debug("Logging in user " + user.getName()); } httpSession.setAttribute( ConfluenceAuthenticator.LOGGED_IN_KEY, user); httpSession.setAttribute( ConfluenceAuthenticator.LOGGED_OUT_KEY, null); getEventManager().publishEvent(new LoginEvent(this, user.getName(), httpSession.getId(), remoteHost, remoteIP)); //return true; return user; }
diff --git a/persistence/persistence-parent/src/main/java/com/redshape/persistence/entities/DtoUtils.java b/persistence/persistence-parent/src/main/java/com/redshape/persistence/entities/DtoUtils.java index fed18a8f..abe8b8ab 100644 --- a/persistence/persistence-parent/src/main/java/com/redshape/persistence/entities/DtoUtils.java +++ b/persistence/persistence-parent/src/main/java/com/redshape/persistence/entities/DtoUtils.java @@ -1,558 +1,558 @@ package com.redshape.persistence.entities; import com.redshape.persistence.DaoContextHolder; import com.redshape.persistence.dao.DAOException; import com.redshape.persistence.dao.DAOFacade; import com.redshape.persistence.dao.IDAO; import com.redshape.persistence.utils.ISessionManager; import com.redshape.utils.Commons; import com.redshape.utils.beans.Property; import com.redshape.utils.beans.PropertyUtils; import org.apache.log4j.Logger; import java.beans.IntrospectionException; import java.util.*; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.LinkedBlockingQueue; /** * @author Cyril A. Karpenko <[email protected]> * @package com.redshape.persistence.entities * @date 2/6/12 {4:04 PM} */ public final class DtoUtils { private static class Deferred { private Object target; private Property property; private Object object; private boolean toDTO; public Deferred(Object target, Property targetProperty, Object object, boolean toDTO) { Commons.checkNotNull(target); Commons.checkNotNull(targetProperty); this.target = target; this.property = targetProperty; this.object = object; this.toDTO = toDTO; } public String getName() { return this.property.getName(); } public Object getObject() { return object; } public void initialize( Object value ) throws IntrospectionException { try { this.property.set( this.target, value ); } catch ( Exception e ) { throw new IntrospectionException( e.getMessage() ); } } public boolean isToDTO() { return toDTO; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Deferred)) return false; Deferred deferred = (Deferred) o; if ( this.isToDTO() != deferred.isToDTO() ) { return false; } if (property != null ? !property.getName().equals(deferred.property.getName()) : deferred.property != null) return false; if (target != null ? !target.equals(deferred.target) : deferred.target != null) return false; return true; } @Override public String toString() { return String.format("%s { %s = %s }", this.target.getClass().getCanonicalName(), this.property.getName(), this.object.toString() ); } @Override public int hashCode() { int result = target != null ? target.hashCode() : 0; result = 31 * result + (property.getName() != null ? property.getName().hashCode() : 0); return result; } } private static class Counter { private static final int MAX_STACK_SIZE = 100; private int entranceCounter; public int value() { return entranceCounter; } public void reset() { this.entranceCounter = 0; } public void enter() { Commons.checkArgument( entranceCounter < MAX_STACK_SIZE, "Illegal counter state"); entranceCounter++; } public void leave() { Commons.checkArgument( entranceCounter < MAX_STACK_SIZE, "Illegal counter state"); Commons.checkArgument( entranceCounter > 0, "Illegal counter state"); entranceCounter--; } public boolean isBalanced() { return entranceCounter == 0; } } private static final Logger log = Logger.getLogger(DtoUtils.class); private static final ThreadLocal<Object> notInitializedValue = new ThreadLocal<Object>(); private static final ThreadLocal<Counter> fromCounter = new ThreadLocal<Counter>(); private static final ThreadLocal<Counter> toCounter = new ThreadLocal<Counter>(); private static final ThreadLocal<Integer> maxDepth = new ThreadLocal<Integer>(); private static final ThreadLocal<Collection<Deferred>> deferred = new ThreadLocal<Collection<Deferred>>(); private static final ThreadLocal<Collection<Object>> processing = new ThreadLocal<Collection<Object>>(); private static final ThreadLocal<Map<IDtoCapable, IDTO>> cache = new ThreadLocal<Map<IDtoCapable, IDTO>>(); private static final ThreadLocal<Map<IEntity, IEntity>> reverseCache = new ThreadLocal<Map<IEntity, IEntity>>(); public static final void notInitializedValue( Object value ) { notInitializedValue.set(value); } private static final Object notInitializedValue() { return notInitializedValue.get(); } public static final void maxDepth( Integer value ) { maxDepth.set(value); } private static final Integer maxDepth() { return Commons.select( maxDepth.get(), 2 ); } private static final Counter toCounter() { if ( toCounter.get() == null ) { toCounter.set( new Counter() ); } return toCounter.get(); } private static final Counter fromCounter() { if ( fromCounter.get() == null ) { fromCounter.set( new Counter() ); } return fromCounter.get(); } private static final Map<IDtoCapable, IDTO> cache() { if ( cache.get() == null ) { cache.set( new HashMap<IDtoCapable, IDTO>() ); } return cache.get(); } private static final Map<IEntity, IEntity> reverseCache() { if ( reverseCache.get() == null ) { reverseCache.set( new HashMap<IEntity, IEntity>() ); } return reverseCache.get(); } private static final Collection<Object> processing() { if ( processing.get() == null ) { processing.set( new HashSet<Object>() ); } return processing.get(); } private static final Collection<Deferred> deferred() { if ( deferred.get() == null ) { deferred.set( new HashSet<Deferred>() ); } return deferred.get(); } private static void resetReverseCache() { reverseCache().clear(); } private static void resetCache() { cache().clear(); } protected static void processDeferred( boolean toDto ) { for ( Deferred deferred : deferred() ) { try { if ( deferred.isToDTO() && toDto ) { deferred.initialize( cache().get(deferred.getObject()) ); } else if ( !toDto ) { deferred.initialize( reverseCache().get(deferred.getObject()) ); } } catch ( IntrospectionException e ) { log.error("Unable to process deferred initialization on property " + deferred.getName(), e ); } } processing().clear(); } protected static void saveDeferred( Deferred def ) { for ( Deferred deferred : deferred() ) { if ( def.equals(deferred) ) { return; } } deferred().add(def); } protected static boolean toPreCheck( IEntity entity ) { Commons.checkNotNull(DaoContextHolder.instance().getContext(), "Global context not wired"); if ( entity == null ) { return false; } if ( entity.isDto() ) { return false; } if ( toCounter().value() > maxDepth() ) { return false; } return true; } protected static boolean fromPreCheck( IEntity entity ) { Commons.checkNotNull(DaoContextHolder.instance().getContext(), "Global context not wired"); if ( entity == null ) { return false; } if ( !entity.isDto() ) { return false; } return true; } public static <T extends IEntity> T fromDTO( IEntity entity ) { try { /** * Can be represented as aspect */ if ( fromCounter().isBalanced() ) { if ( !fromPreCheck(entity) ) { if ( entity == null ) { return null; } else if ( !entity.isDto() ) { return (T) entity; } } fromCounter().enter(); openSession(); } else { fromCounter().enter(); if ( !fromPreCheck(entity) ) { if ( entity == null ) { return null; } else if ( !entity.isDto() ) { return (T) entity; } } } final IDTO dto = (IDTO) entity; IEntity result = null; Class<? extends IEntity> entityClazz = dto.getEntityClass(); if ( entityClazz == null ) { throw new IllegalStateException("<null>"); } if ( entityClazz.isInterface() ) { entityClazz = DaoContextHolder.instance().getContext().getBean( entityClazz ).getClass(); } if ( dto.getId() != null ) { DAOFacade facade = DaoContextHolder.instance().getContext().getBean(DAOFacade.class); IDAO<? extends IEntity> dao = facade.getDAO(entityClazz); Commons.checkNotNull(dao, "DAO for " + entityClazz.getCanonicalName() + " is not registered"); result = dao.findById( dto.getId() ); } else { try { result = entityClazz.newInstance(); } catch ( Throwable e ) { throw new DAOException( e.getMessage(), e ); } } reverseCache().put(dto, result = fromDTO(result, dto)); return (T) result; } catch ( Throwable e ) { throw new IllegalStateException( e.getMessage(), e ); } finally { if ( !fromCounter().isBalanced() ) { fromCounter().leave(); } if ( fromCounter().isBalanced() ) { processDeferred(false); try { // @FIXME: Issue must be investigated // closeSession(); } catch ( Throwable e ) {} resetReverseCache(); } } } private static boolean isProcessing( Object object ) { for ( Object processing : processing() ) { if ( processing.equals( object ) ) { return true; } } return false; } protected static IEntity fromDTO( IEntity entity, IEntity dto ) throws DAOException { try { Collection<Property> entityProperties = PropertyUtils.getInstance().getProperties(entity.getClass()); Collection<Property> dtoProperties = PropertyUtils.getInstance().getProperties(dto.getClass()); for ( Property property : entityProperties ) { for ( Property dtoProperty : dtoProperties ) { try { if ( !dtoProperty.getName().equals( property.getName() ) ) { continue; } Object value = dtoProperty.get(dto); if ( value == entity ) { value = null; } Object originalValue = null; if ( value != null ) { if ( value instanceof IDTO ) { if ( !isProcessing(value) ) { processing().add( originalValue = value); } else { saveDeferred( new Deferred(entity, property, value, false ) ); continue; } value = DtoUtils.fromDTO( (IEntity) value ); } else if ( isListType(value) ) { value = processList(value, true); } } if ( originalValue != null ) { processing().remove(originalValue); } property.set( entity, value ); break; } catch ( Throwable e ) { log.error( e.getMessage(), e ); } } } return entity; } catch ( IntrospectionException e ) { throw new DAOException( e.getMessage(), e ); } } protected static Collection<?> processList( Object value, boolean fromDTO ) throws DAOException { Collection result; Class<?> valueClazz = value.getClass(); if ( List.class.isAssignableFrom(valueClazz) ) { result = new ArrayList(); } else if ( Set.class.isAssignableFrom(valueClazz) ) { result = new HashSet(); } else if ( Queue.class.isAssignableFrom(valueClazz) ) { result = new LinkedBlockingQueue(); } else if ( Deque.class.isAssignableFrom(valueClazz) ) { result = new LinkedBlockingDeque(); } else { result = new HashSet(); } if ( !fromDTO && toCounter().value() >= maxDepth() ) { return result; } boolean entitiesCollection = true; for ( Object part : (Collection) value ) { if ( part == null ) { continue; } if ( entitiesCollection && part instanceof IEntity ) { IEntity item = (IEntity) part; if ( fromDTO ) { if ( item.isDto() ) { item = fromDTO( (IEntity) part); } } else { if (!item.isDto() && (item instanceof IDtoCapable) ) { item = DtoUtils.<IDTO, IDtoCapable<IDTO>>toDTO( (IDtoCapable) item ); } } if ( item == null ) { continue; } result.add( item ); entitiesCollection = true; } else { result.add( part ); entitiesCollection = false; } } return result; } protected static boolean isListType( Object value ) { return Collection.class.isAssignableFrom(value.getClass()); } public static <T extends IDTO, V extends IDtoCapable<T>> T toDTO( V entity ) { try { if ( toCounter().isBalanced() ) { Commons.checkNotNull(DaoContextHolder.instance().getContext(), "Global context not wired"); if ( !toPreCheck( (IEntity) entity) ) { if ( entity == null ) { return null; } else if ( entity instanceof IDTO ) { return (T) entity; } } toCounter().enter(); openSession(); } else { toCounter().enter(); if ( !toPreCheck( (IEntity) entity) ) { if ( entity instanceof IDTO ) { return (T) entity; } else { return (T) notInitializedValue(); } } } if ( ((IEntity) entity).getId() != null ) { entity = (V) getSessionManager().refresh( (IEntity) entity); } T dto = entity.createDTO(); cache().put(entity, dto); Commons.checkNotNull(dto); for ( Property property : PropertyUtils.getInstance().getProperties(entity.getClass()) ) { for ( Property dtoProperty : PropertyUtils.getInstance().getProperties(dto.getClass()) ) { try { if ( !dtoProperty.getName().equals( property.getName() ) ) { continue; } Object value = property.get(entity); if ( value == entity ) { value = null; } Object originalValue = null; if ( value != null ) { if ( value instanceof IDtoCapable ) { if ( !processing().contains(value) ) { processing().add( originalValue = value ); } else { saveDeferred( new Deferred(dto, dtoProperty, value, true) ); continue; } value = ( (IDtoCapable) value ).toDTO(); } else if ( isListType(value) ) { value = processList(value, false); } } if ( originalValue != null ) { processing().remove(originalValue); } dtoProperty.set( dto, value ); } catch ( Throwable e ) { log.error( e.getMessage(), e ); } } } return dto; } catch ( Throwable e ) { cache().remove(entity); throw new IllegalStateException( e.getMessage(), e ); } finally { if ( !toCounter().isBalanced() ) { toCounter().leave(); - } else if ( toCounter().isBalanced() ) { + } else { processDeferred(true); resetCache(); } } } protected static ISessionManager getSessionManager() { return DaoContextHolder.instance().getContext().getBean(ISessionManager.class); } protected static void openSession() throws DAOException { getSessionManager().open(); } protected static void closeSession() throws DAOException { getSessionManager().close(); } }
true
true
public static <T extends IDTO, V extends IDtoCapable<T>> T toDTO( V entity ) { try { if ( toCounter().isBalanced() ) { Commons.checkNotNull(DaoContextHolder.instance().getContext(), "Global context not wired"); if ( !toPreCheck( (IEntity) entity) ) { if ( entity == null ) { return null; } else if ( entity instanceof IDTO ) { return (T) entity; } } toCounter().enter(); openSession(); } else { toCounter().enter(); if ( !toPreCheck( (IEntity) entity) ) { if ( entity instanceof IDTO ) { return (T) entity; } else { return (T) notInitializedValue(); } } } if ( ((IEntity) entity).getId() != null ) { entity = (V) getSessionManager().refresh( (IEntity) entity); } T dto = entity.createDTO(); cache().put(entity, dto); Commons.checkNotNull(dto); for ( Property property : PropertyUtils.getInstance().getProperties(entity.getClass()) ) { for ( Property dtoProperty : PropertyUtils.getInstance().getProperties(dto.getClass()) ) { try { if ( !dtoProperty.getName().equals( property.getName() ) ) { continue; } Object value = property.get(entity); if ( value == entity ) { value = null; } Object originalValue = null; if ( value != null ) { if ( value instanceof IDtoCapable ) { if ( !processing().contains(value) ) { processing().add( originalValue = value ); } else { saveDeferred( new Deferred(dto, dtoProperty, value, true) ); continue; } value = ( (IDtoCapable) value ).toDTO(); } else if ( isListType(value) ) { value = processList(value, false); } } if ( originalValue != null ) { processing().remove(originalValue); } dtoProperty.set( dto, value ); } catch ( Throwable e ) { log.error( e.getMessage(), e ); } } } return dto; } catch ( Throwable e ) { cache().remove(entity); throw new IllegalStateException( e.getMessage(), e ); } finally { if ( !toCounter().isBalanced() ) { toCounter().leave(); } else if ( toCounter().isBalanced() ) { processDeferred(true); resetCache(); } } }
public static <T extends IDTO, V extends IDtoCapable<T>> T toDTO( V entity ) { try { if ( toCounter().isBalanced() ) { Commons.checkNotNull(DaoContextHolder.instance().getContext(), "Global context not wired"); if ( !toPreCheck( (IEntity) entity) ) { if ( entity == null ) { return null; } else if ( entity instanceof IDTO ) { return (T) entity; } } toCounter().enter(); openSession(); } else { toCounter().enter(); if ( !toPreCheck( (IEntity) entity) ) { if ( entity instanceof IDTO ) { return (T) entity; } else { return (T) notInitializedValue(); } } } if ( ((IEntity) entity).getId() != null ) { entity = (V) getSessionManager().refresh( (IEntity) entity); } T dto = entity.createDTO(); cache().put(entity, dto); Commons.checkNotNull(dto); for ( Property property : PropertyUtils.getInstance().getProperties(entity.getClass()) ) { for ( Property dtoProperty : PropertyUtils.getInstance().getProperties(dto.getClass()) ) { try { if ( !dtoProperty.getName().equals( property.getName() ) ) { continue; } Object value = property.get(entity); if ( value == entity ) { value = null; } Object originalValue = null; if ( value != null ) { if ( value instanceof IDtoCapable ) { if ( !processing().contains(value) ) { processing().add( originalValue = value ); } else { saveDeferred( new Deferred(dto, dtoProperty, value, true) ); continue; } value = ( (IDtoCapable) value ).toDTO(); } else if ( isListType(value) ) { value = processList(value, false); } } if ( originalValue != null ) { processing().remove(originalValue); } dtoProperty.set( dto, value ); } catch ( Throwable e ) { log.error( e.getMessage(), e ); } } } return dto; } catch ( Throwable e ) { cache().remove(entity); throw new IllegalStateException( e.getMessage(), e ); } finally { if ( !toCounter().isBalanced() ) { toCounter().leave(); } else { processDeferred(true); resetCache(); } } }
diff --git a/com.mobilesorcery.sdk.html5/src/com/mobilesorcery/sdk/html5/debug/ReloadVirtualMachine.java b/com.mobilesorcery.sdk.html5/src/com/mobilesorcery/sdk/html5/debug/ReloadVirtualMachine.java index e74ea09a..f6117bbd 100644 --- a/com.mobilesorcery.sdk.html5/src/com/mobilesorcery/sdk/html5/debug/ReloadVirtualMachine.java +++ b/com.mobilesorcery.sdk.html5/src/com/mobilesorcery/sdk/html5/debug/ReloadVirtualMachine.java @@ -1,467 +1,467 @@ package com.mobilesorcery.sdk.html5.debug; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeoutException; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.IPath; import org.eclipse.debug.core.DebugException; import org.eclipse.debug.core.ILaunch; import org.eclipse.debug.core.model.IThread; import org.eclipse.wst.jsdt.debug.core.jsdi.BooleanValue; import org.eclipse.wst.jsdt.debug.core.jsdi.NullValue; import org.eclipse.wst.jsdt.debug.core.jsdi.NumberValue; import org.eclipse.wst.jsdt.debug.core.jsdi.ScriptReference; import org.eclipse.wst.jsdt.debug.core.jsdi.StringValue; import org.eclipse.wst.jsdt.debug.core.jsdi.UndefinedValue; import org.eclipse.wst.jsdt.debug.core.jsdi.VirtualMachine; import org.eclipse.wst.jsdt.debug.core.jsdi.event.EventQueue; import org.eclipse.wst.jsdt.debug.core.jsdi.request.EventRequestManager; import org.eclipse.wst.jsdt.debug.core.model.IJavaScriptDebugTarget; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import com.mobilesorcery.sdk.core.CoreMoSyncPlugin; import com.mobilesorcery.sdk.core.MoSyncProject; import com.mobilesorcery.sdk.core.MoSyncTool; import com.mobilesorcery.sdk.html5.Html5Plugin; import com.mobilesorcery.sdk.html5.debug.hotreplace.FileRedefinable; import com.mobilesorcery.sdk.html5.debug.hotreplace.FunctionRedefinable; import com.mobilesorcery.sdk.html5.debug.hotreplace.ProjectRedefinable; import com.mobilesorcery.sdk.html5.debug.jsdt.ReloadBooleanValue; import com.mobilesorcery.sdk.html5.debug.jsdt.ReloadDropToFrame; import com.mobilesorcery.sdk.html5.debug.jsdt.ReloadEventQueue; import com.mobilesorcery.sdk.html5.debug.jsdt.ReloadEventRequestManager; import com.mobilesorcery.sdk.html5.debug.jsdt.ReloadNullValue; import com.mobilesorcery.sdk.html5.debug.jsdt.ReloadNumberValue; import com.mobilesorcery.sdk.html5.debug.jsdt.ReloadStackFrame; import com.mobilesorcery.sdk.html5.debug.jsdt.ReloadStringValue; import com.mobilesorcery.sdk.html5.debug.jsdt.ReloadThreadReference; import com.mobilesorcery.sdk.html5.debug.jsdt.ReloadUndefinedValue; import com.mobilesorcery.sdk.html5.debug.jsdt.SimpleScriptReference; import com.mobilesorcery.sdk.html5.live.ILiveServerListener; import com.mobilesorcery.sdk.html5.live.JSODDServer; public class ReloadVirtualMachine implements VirtualMachine, ILiveServerListener { private final JSODDServer server; private List threads = new ArrayList(); private final ReloadEventRequestManager requestMgr; private ReloadEventQueue eventQueue; private final NullValue nullValue; private final ReloadUndefinedValue undefValue; private int currentSessionId = JSODDServer.NO_SESSION; private IProject project; private ReloadThreadReference mainThread; private boolean isTerminated = false; private ProjectRedefinable baseline; private ILaunch launch; private IJavaScriptDebugTarget debugTarget; private String remoteAddr; private HashMap<Class, Boolean> redefineSupport = new HashMap<Class, Boolean>(); public ReloadVirtualMachine(int port) throws Exception { // TODO: PORT server = Html5Plugin.getDefault().getReloadServer(); // JUST ONE MAIN THREAD mainThread = new ReloadThreadReference(this); threads.add(mainThread); resetThreads(); // By default we support function redefines. redefineSupport.put(FunctionRedefinable.class, Boolean.TRUE); redefineSupport.put(FileRedefinable.class, Html5Plugin.getDefault().shouldFetchRemotely()); requestMgr = new ReloadEventRequestManager(this); eventQueue = new ReloadEventQueue(this, requestMgr); nullValue = new ReloadNullValue(this); undefValue = new ReloadUndefinedValue(this); server.addListener(this); server.startServer(this); server.registerVM(this); } private void resetThreads() { mainThread.markSuspended(false, false); } private void resetEventQueue() { if (eventQueue != null) { eventQueue.close(); List exitRequests = requestMgr.threadExitRequests(); for (Object exitRequest : exitRequests) { // Don't reactivate this yet! // eventQueue.received(ReloadEventQueue.CUSTOM_EVENT, new // ReloadThreadExitEvent(this, mainThread, null, (EventRequest) // exitRequest)); } } } public void setCurrentSessionId(int sessionId) { this.currentSessionId = sessionId; } @Override public void resume() { server.resume(currentSessionId); } public void step(int stepType) { server.step(currentSessionId, stepType); } @Override public void suspend() { mainThread.suspend(); } public void suspend(boolean isThread) { server.suspend(currentSessionId); } public void reset(int newSessionId, MoSyncProject project, String remoteAddr) { resetThreads(); if (currentSessionId != JSODDServer.NO_SESSION) { server.reset(currentSessionId); resetEventQueue(); } setCurrentSessionId(newSessionId); this.project = project.getWrappedProject(); this.remoteAddr = remoteAddr; } @Override public synchronized void terminate() { try { server.terminate(currentSessionId); server.removeListener(this); server.stopServer(this); } catch (Exception e) { CoreMoSyncPlugin.getDefault().log(e); } finally { eventQueue.close(); isTerminated = true; } } @Override public String name() { return "Reload"; } @Override public String description() { return "TODO"; } @Override public String version() { return MoSyncTool.getDefault() .getVersionInfo(MoSyncTool.BINARY_VERSION); } @Override public List allThreads() { return threads; } @Override public List allScripts() { ArrayList<ScriptReference> result = new ArrayList<ScriptReference>(); // Before the project has been initialized, we just send all the scripts // in the workspace... ArrayList<IProject> projects = new ArrayList<IProject>(); if (project != null) { projects.add(project); } else { projects.addAll(Arrays.asList(ResourcesPlugin.getWorkspace() .getRoot().getProjects())); } for (IProject project : projects) { JSODDSupport jsoddSupport = Html5Plugin.getDefault() .getJSODDSupport(project); if (jsoddSupport != null) { Set<IPath> allFiles = jsoddSupport.getAllFiles(); for (IPath file : allFiles) { SimpleScriptReference ref = new SimpleScriptReference(this, file); result.add(ref); } } } return result; } public IProject getProject() { return project; } @Override public void dispose() { terminate(); } @Override public UndefinedValue mirrorOfUndefined() { return undefValue; } @Override public NullValue mirrorOfNull() { return nullValue; } @Override public BooleanValue mirrorOf(boolean bool) { return new ReloadBooleanValue(this, bool); } @Override public NumberValue mirrorOf(Number number) { return new ReloadNumberValue(this, number); } @Override public StringValue mirrorOf(String string) { return new ReloadStringValue(this, string); } @Override public EventRequestManager eventRequestManager() { return requestMgr; } @Override public EventQueue eventQueue() { return eventQueue; } /** * Evaluates an expression in the current scope. * * @param expression * The JavaScript expression to evaluate * @return The result of the evaluation * @throws InterruptedException * If the waiting thread was interrupted, for example by a * terminate request. * @throws TimeoutException * If the client failed to respond within a specified timeout. */ public Object evaluate(String expression) throws InterruptedException, TimeoutException { return evaluate(expression, null); } /** * Evaluates an expression at a specified stack depth * * @param expression * The JavaScript expression to evaluate * @param stackDepth * The stackdepth to perform the evaluation, or {@code null} to * use the current scope. * @return The result of the evaluation * @throws InterruptedException * If the waiting thread was interrupted, for example by a * terminate request. * @throws TimeoutException * If the client failed to respond within a specified timeout. */ public Object evaluate(String expression, Integer stackDepth) throws InterruptedException, TimeoutException { return server.evaluate(currentSessionId, expression, stackDepth); } /** * Clears and resets all breakpoints on target. */ public void refreshBreakpoints() { // TODO: Clear per file instead. server.refreshBreakpoints(currentSessionId); } /** * Issues a reload request to the client. * * @param resourcePath * The resource to reload. A {@code null} value will cause a full * reload of the app. * @param resourcePath * The resource to upload, relative to the project's HTML5 * location * @param reloadHint * If applicable; whether to reload the page * @return {@code true} If this virtual machine accepted the file for * updating. */ public boolean update(IFile resource) { boolean doUpdate = resource != null && resource.getProject().equals(project); if (doUpdate) { server.update(currentSessionId, resource); } return doUpdate; } public void reload() { server.reload(currentSessionId); if (debugTarget.isSuspended()) { try { debugTarget.resume(); } catch (DebugException e) { CoreMoSyncPlugin.getDefault().log(e); } } } /** * Updates a function reference on the client. * * @param key * @param source */ public void updateFunction(String key, String source) { server.updateFunction(currentSessionId, key, source); } @Override public void received(String command, JSONObject json) { // TODO!!! Session id - now all will suspend. // TODID -- filtering is done in the eventqueue. For now. // MAIN THREAD ReloadThreadReference thread = (ReloadThreadReference) threads.get(0); boolean isClientSuspend = Boolean.parseBoolean("" + json.get("suspended")); - if (thread.isSuspended() && !isClientSuspend) { + if (debugTarget.isSuspended() && thread.isSuspended() && !isClientSuspend) { return; } thread.markSuspended(true); JSONArray array = (JSONArray) json.get("stack"); ReloadStackFrame[] frames = new ReloadStackFrame[array.size()]; for (int i = 0; i < array.size(); i++) { ReloadStackFrame frame = new ReloadStackFrame(this, json, i); // Stack traces are reported in the reverse order. frames[array.size() - 1 - i] = frame; } if (frames.length == 0) { frames = new ReloadStackFrame[1]; frames[0] = new ReloadStackFrame(this, json, -1); } thread.setFrames(frames); // suspend(); eventQueue.received(command, json); } public LocalVariableScope getLocalVariableScope(ScriptReference ref, int line) { // TODO: Faster? if (ref instanceof SimpleScriptReference) { IFile file = ((SimpleScriptReference) ref).getFile(); JSODDSupport jsoddSupport = Html5Plugin.getDefault() .getJSODDSupport(file.getProject()); LocalVariableScope scope = jsoddSupport.getScope(file, line); if (scope != null) { return scope; } } return null; } public int getCurrentSessionId() { return currentSessionId; } @Override public String toString() { return "JavaScript On-Device Debug VM, session id #" + getCurrentSessionId(); } public void setCurrentLocation(String location) { mainThread.setCurrentLocation(location); } public boolean isTerminated() { return isTerminated; } public ReloadThreadReference mainThread() { return mainThread; } public void dropToFrame(int dropToFrame) throws DebugException { IThread[] threads = getJavaScriptDebugTarget().getThreads(); for (int i = 0; i < threads.length; i++) { IThread thread = threads[i]; ReloadDropToFrame.dropToFrame(thread, dropToFrame); } } public IJavaScriptDebugTarget getJavaScriptDebugTarget() { return debugTarget; } public ProjectRedefinable getBaseline() { if (baseline == null) { JSODDSupport jsoddSupport = Html5Plugin.getDefault() .getJSODDSupport(project); if (jsoddSupport != null) { setBaseline(jsoddSupport.getBaseline()); } } return baseline; } public void setBaseline(ProjectRedefinable baseline) { this.baseline = baseline; } public void setLaunch(ILaunch launch) { this.launch = launch; } public void setDebugTarget(IJavaScriptDebugTarget debugTarget) { this.debugTarget = debugTarget; } @Override public void timeout(ReloadVirtualMachine vm) { // Ignore. } public String getRemoteAddr() { return remoteAddr; } public boolean canRedefine(IRedefinable redefinable) { synchronized (redefineSupport) { for (Map.Entry<Class, Boolean> supportsThis : redefineSupport.entrySet()) { if (redefinable != null && supportsThis.getValue() && supportsThis.getKey().isAssignableFrom( redefinable.getClass())) { return true; } } } return false; } public void setRedefineSupport(Class redefinables, boolean hasSupport) { redefineSupport.put(redefinables, hasSupport); } }
true
true
public void received(String command, JSONObject json) { // TODO!!! Session id - now all will suspend. // TODID -- filtering is done in the eventqueue. For now. // MAIN THREAD ReloadThreadReference thread = (ReloadThreadReference) threads.get(0); boolean isClientSuspend = Boolean.parseBoolean("" + json.get("suspended")); if (thread.isSuspended() && !isClientSuspend) { return; } thread.markSuspended(true); JSONArray array = (JSONArray) json.get("stack"); ReloadStackFrame[] frames = new ReloadStackFrame[array.size()]; for (int i = 0; i < array.size(); i++) { ReloadStackFrame frame = new ReloadStackFrame(this, json, i); // Stack traces are reported in the reverse order. frames[array.size() - 1 - i] = frame; } if (frames.length == 0) { frames = new ReloadStackFrame[1]; frames[0] = new ReloadStackFrame(this, json, -1); } thread.setFrames(frames); // suspend(); eventQueue.received(command, json); }
public void received(String command, JSONObject json) { // TODO!!! Session id - now all will suspend. // TODID -- filtering is done in the eventqueue. For now. // MAIN THREAD ReloadThreadReference thread = (ReloadThreadReference) threads.get(0); boolean isClientSuspend = Boolean.parseBoolean("" + json.get("suspended")); if (debugTarget.isSuspended() && thread.isSuspended() && !isClientSuspend) { return; } thread.markSuspended(true); JSONArray array = (JSONArray) json.get("stack"); ReloadStackFrame[] frames = new ReloadStackFrame[array.size()]; for (int i = 0; i < array.size(); i++) { ReloadStackFrame frame = new ReloadStackFrame(this, json, i); // Stack traces are reported in the reverse order. frames[array.size() - 1 - i] = frame; } if (frames.length == 0) { frames = new ReloadStackFrame[1]; frames[0] = new ReloadStackFrame(this, json, -1); } thread.setFrames(frames); // suspend(); eventQueue.received(command, json); }
diff --git a/SWADroid/src/es/ugr/swad/swadroid/modules/downloads/DownloadsManager.java b/SWADroid/src/es/ugr/swad/swadroid/modules/downloads/DownloadsManager.java index 68590185..cdd14a08 100644 --- a/SWADroid/src/es/ugr/swad/swadroid/modules/downloads/DownloadsManager.java +++ b/SWADroid/src/es/ugr/swad/swadroid/modules/downloads/DownloadsManager.java @@ -1,643 +1,647 @@ /* * This file is part of SWADroid. * * Copyright (C) 2012 Helena Rodriguez Gijon <[email protected]> * * SWADroid is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SWADroid is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with SWADroid. If not, see <http://www.gnu.org/licenses/>. */ package es.ugr.swad.swadroid.modules.downloads; import java.util.ArrayList; import java.util.Date; import java.util.List; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.os.Environment; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.GridView; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.Spinner; import android.widget.TextView; import android.widget.ArrayAdapter; import es.ugr.swad.swadroid.Constants; import es.ugr.swad.swadroid.R; import es.ugr.swad.swadroid.gui.MenuActivity; import es.ugr.swad.swadroid.model.Group; import es.ugr.swad.swadroid.model.GroupType; import es.ugr.swad.swadroid.modules.GroupTypes; import es.ugr.swad.swadroid.modules.Groups; /** * Activity to navigate through the directory tree of documents and to manage * the downloads of documents * * @author Helena Rodriguez Gijon <[email protected]> * @author Juan Miguel Boyero Corral <[email protected]> * */ public class DownloadsManager extends MenuActivity { /** * Class that contains the directory tree and gives information of each * level * */ private DirectoryNavigator navigator; /** * Specifies whether to display the documents or the shared area of the * subject 1 specifies documents area 2 specifies shared area * */ private int downloadsAreaCode = 0; /** * Specifies chosen group to show its documents * 0 - * */ private long chosenGroupCode = 0; /** * String that contains the xml files recevied from the web service * */ private String tree = null; /** * Downloads tag name for Logcat */ public static final String TAG = Constants.APP_TAG + " Downloads"; /** * List of group of the selected course to which the user belongs * */ private List<Group> myGroups; /** * Indicates if the groups has been requested * */ private boolean groupsRequested = false; /** * Indicates whether the refresh button was pressed * */ private boolean refresh = false; private ImageButton updateButton; private ProgressBar progressbar; private TextView noConnectionText; private GridView grid; private ImageView moduleIcon = null; private TextView moduleText = null; private TextView currentPathText; String chosenNodeName = null; /** * fileSize stores the size of the last file name chosen to be downloaded * */ private long fileSize = 0; /** * Indicates the selected position in the groups spinner * by default the whole course is selected * */ private int groupPosition = 0; /** * Indicates if the menu no connection is visible * */ private boolean noConnectionView = false; /** * Indicates that the current state should be saved in case the activity is brought to background * */ private boolean saveState = false; /** * Indicates if the state before the activity was brought to background has o not connection * */ private boolean previousConnection = false; @Override protected void onStart() { super.onStart(); List<Group> allGroups = dbHelper.getGroups(Constants.getSelectedCourseCode()); int nGroups = allGroups.size(); if(!saveState){ if(nGroups != 0 || groupsRequested){ //groupsRequested is used to avoid continue requests of groups on courses that have not any group. myGroups = getFilteredGroups(); //only groups where the user is enrolled. int nMyGroups = myGroups.size(); this.loadGroupsSpinner(myGroups); // the tree request must be explicit only when there are not any groups(where the user is enrolled), and therefore any Spinner. //in case there are groups(where the user is enrolled), it will be a spinner, and the tree request will be automatic made by OnItemSelectedListener if(nMyGroups == 0 && tree == null) requestDirectoryTree(); }else{ Intent activity = new Intent(getBaseContext(),GroupTypes.class); activity.putExtra("courseCode", Constants.getSelectedCourseCode()); startActivityForResult(activity,Constants.GROUPTYPES_REQUEST_CODE); } }else{ myGroups = getFilteredGroups(); this.loadGroupsSpinner(myGroups); if(previousConnection){ setMainView(); }else{ setNoConnectionView(); } } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if(savedInstanceState != null){ this.saveState = savedInstanceState.getBoolean("saveState", false); if(saveState){ this.groupsRequested = true; this.previousConnection = savedInstanceState.getBoolean("previousConnection", false); this.chosenGroupCode = savedInstanceState.getLong("chosenGroupCode",0); this.groupPosition = savedInstanceState.getInt("groupPosition",0); if(previousConnection){ this.tree = savedInstanceState.getString("tree"); String path = savedInstanceState.getString("path"); this.navigator = new DirectoryNavigator(this.tree); if(path.compareTo("/") !=0){ int firstBar = path.indexOf('/',0); int nextBar = path.indexOf('/', firstBar+1); while(nextBar != -1){ String dir = path.substring(firstBar+1, nextBar); this.navigator.goToSubDirectory(dir); firstBar = nextBar; nextBar = path.indexOf('/', firstBar+1); } } } } } setContentView(R.layout.navigation); downloadsAreaCode = getIntent().getIntExtra("downloadsAreaCode", Constants.DOCUMENTS_AREA_CODE); //set the module bar if (downloadsAreaCode == Constants.DOCUMENTS_AREA_CODE) { moduleIcon = (ImageView) this.findViewById(R.id.moduleIcon); moduleIcon.setBackgroundResource(R.drawable.folder); moduleText = (TextView) this.findViewById(R.id.moduleName); moduleText.setText(R.string.documentsDownloadModuleLabel); } else { // SHARE_AREA_CODE moduleIcon = (ImageView) this.findViewById(R.id.moduleIcon); moduleIcon.setBackgroundResource(R.drawable.folder_users); moduleText = (TextView) this.findViewById(R.id.moduleName); moduleText.setText(R.string.sharedsDownloadModuleLabel); } noConnectionText = (TextView) this.findViewById(R.id.noConnectionText); grid = (GridView) this.findViewById(R.id.gridview); grid.setOnItemClickListener((new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id) { //TextView text = (TextView) v.findViewById(R.id.icon_text); //chosenNodeName = text.getText().toString(); //DirectoryItem node = navigator.getDirectoryItem(chosenNodeName); DirectoryItem node = navigator.getDirectoryItem(position); if(node.getFileCode() == -1) //it is a directory therefore navigates into it updateView(navigator.goToSubDirectory(position)); //updateView(navigator.goToSubDirectory(chosenNodeName)); else{ //it is a files therefore gets its information through web service GETFILE chosenNodeName = node.getName(); AlertDialog fileInfoDialog = createFileInfoDialog(node.getName(),node.getSize(),node.getTime(),node.getPublisher(),node.getFileCode()); fileInfoDialog.show(); } } })); ImageButton homeButton = (ImageButton) this .findViewById(R.id.home_button); homeButton.setOnClickListener((new OnClickListener() { @Override public void onClick(View v) { - updateView(navigator.goToRoot()); + if(navigator != null) { + updateView(navigator.goToRoot()); + } } })); ImageButton parentButton = (ImageButton) this .findViewById(R.id.parent_button); parentButton.setOnClickListener((new OnClickListener() { @Override public void onClick(View v) { - updateView(navigator.goToParentDirectory()); + if(navigator != null) { + updateView(navigator.goToParentDirectory()); + } } })); progressbar = (ProgressBar) this.findViewById(R.id.progress_refresh); progressbar.setVisibility(View.GONE); updateButton = (ImageButton)this.findViewById(R.id.refresh); updateButton.setVisibility(View.VISIBLE); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putBoolean("saveState", this.saveState); if(this.saveState){ outState.putBoolean("previousConnection", this.previousConnection); outState.putLong("chosenGroupCode", this.chosenGroupCode); outState.putInt("groupPosition", this.groupPosition); if(this.previousConnection){ outState.putString("tree", this.tree); outState.putString("path", this.navigator.getPath()); } } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == Activity.RESULT_OK) { switch (requestCode) { // After get the list of courses, a dialog is launched to choice the // course case Constants.DIRECTORY_TREE_REQUEST_CODE: tree = data.getStringExtra("tree"); if (!refresh){ setMainView(); }else { refresh = false; updateButton.setVisibility(View.VISIBLE); progressbar.setVisibility(View.GONE); if(!noConnectionView) refresh(); else setMainView(); } break; case Constants.GETFILE_REQUEST_CODE: Log.d(TAG, "Correct get file"); //if the sd card is not busy, the file can be downloaded if (this.checkMediaAvailability() == 2){ Log.i(TAG, "External storage is available"); String url = data.getExtras().getString("link"); downloadFile(getDirectoryPath(),url,fileSize); //Toast.makeText(this, chosenNodeName +" "+ this.getResources().getString(R.string.notificationDownloadTitle) , Toast.LENGTH_LONG).show(); }else{ //if the sd card is busy, it shows a alert dialog Log.i(TAG, "External storage is NOT available"); AlertDialog.Builder builder = new AlertDialog.Builder(this); AlertDialog dialog; builder.setTitle(R.string.sdCardBusyTitle); builder.setMessage(R.string.sdCardBusy); builder.setIcon(android.R.drawable.ic_dialog_alert); builder.setNeutralButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); } }); dialog = builder.create(); dialog.show(); } break; case Constants.GROUPS_REQUEST_CODE: groupsRequested = true; myGroups = getFilteredGroups(); //only groups where the user is enrolled. this.loadGroupsSpinner(myGroups); if(myGroups.size() == 0) requestDirectoryTree(); break; case Constants.GROUPTYPES_REQUEST_CODE: Intent activity = new Intent(getBaseContext(),Groups.class); activity.putExtra("courseCode", Constants.getSelectedCourseCode()); startActivityForResult(activity,Constants.GROUPS_REQUEST_CODE); break; } }else{ setNoConnectionView(); if (refresh){ refresh = false; updateButton.setVisibility(View.VISIBLE); progressbar.setVisibility(View.GONE); } } } /** * Having connection is mandatory for the Download Module. * Therefore when there is not connection, the grid of nodes is disabled and instead it is showed an info messages * */ private void setNoConnectionView(){ noConnectionView = true; noConnectionText.setVisibility(View.VISIBLE); grid.setVisibility(View.GONE); this.findViewById(R.id.courseSelectedText).setVisibility(View.VISIBLE); this.findViewById(R.id.groupSpinner).setVisibility(View.GONE); TextView courseNameText = (TextView) this.findViewById(R.id.courseSelectedText); courseNameText.setText(Constants.getSelectedCourseShortName()); this.saveState = true; this.previousConnection = false; } /** * This method set the grid of nodes visible and paints the directory tree in its root node * */ private void setMainView() { noConnectionText.setVisibility(View.GONE); grid.setVisibility(View.VISIBLE); noConnectionView = false; currentPathText = (TextView) this.findViewById(R.id.path); ArrayList<DirectoryItem> items; if(!(this.saveState && this.previousConnection)){ navigator = new DirectoryNavigator(tree); items = (ArrayList<DirectoryItem>) navigator .goToRoot(); }else{ items = (ArrayList<DirectoryItem>) navigator.goToCurrentDirectory(); } currentPathText.setText(navigator.getPath()); grid.setAdapter(new NodeAdapter(this, items)); //this is used for the activity restart in case it was taken background this.saveState = true; this.previousConnection = true; } /** * This method is called after the new file tree is received when the refresh button is pressed * */ private void refresh() { navigator.refresh(tree); } /** * When the user moves into a new directory, this method updates the set of new directories and files and paints it * */ private void updateView(ArrayList<DirectoryItem> items) { currentPathText.setText(navigator.getPath()); ((NodeAdapter) grid.getAdapter()).change(items); } /** * Get the list of the groups of the course with a documents zone to whom the user belongs * */ private List<Group> getFilteredGroups(){ List<Group> currentGroups = dbHelper.getGroups(Constants.getSelectedCourseCode()); //remove groups that do not have a file zone assigned int j = 0; while(j < currentGroups.size()){ if(currentGroups.get(j).getDocumentsArea() != 0 && currentGroups.get(j).isMember()) ++j; else currentGroups.remove(j); } return currentGroups; } /** * If there are not groups to which the user belong in the database, it makes the request * */ private void loadGroupsSpinner(List<Group> currentGroups){ if(!currentGroups.isEmpty() ){ //there are groups in the selected course, therefore the groups spinner should be loaded this.findViewById(R.id.courseSelectedText).setVisibility(View.GONE); Spinner groupsSpinner = (Spinner)this.findViewById(R.id.groupSpinner); groupsSpinner.setVisibility(View.VISIBLE); ArrayList<String> spinnerNames = new ArrayList<String>(currentGroups.size()+1); spinnerNames.add(getString(R.string.course)+"-" + Constants.getSelectedCourseShortName()); for(int i=0;i<currentGroups.size();++i){ Group g = currentGroups.get(i); GroupType gType = dbHelper.getGroupTypeFromGroup(g.getId()); spinnerNames.add(getString(R.string.group)+"-" + gType.getGroupTypeName() + " "+ g.getGroupName() ); } ArrayAdapter<String> adapter = new ArrayAdapter<String> (this,android.R.layout.simple_spinner_item,spinnerNames); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); groupsSpinner.setAdapter(adapter); groupsSpinner.setOnItemSelectedListener(new onGroupSelectedListener()); groupsSpinner.setSelection(groupPosition); }else{ this.findViewById(R.id.courseSelectedText).setVisibility(View.VISIBLE); this.findViewById(R.id.groupSpinner).setVisibility(View.GONE); TextView courseNameText = (TextView) this.findViewById(R.id.courseSelectedText); courseNameText.setText(Constants.getSelectedCourseShortName()); } } /** * Listener associated with the spinner. With a new group / course is selected, it is requested the right file tree * */ private class onGroupSelectedListener implements OnItemSelectedListener{ @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { //if the position is 0, it is chosen the whole course. Otherwise a group has been chosen //position - 0 belongs to the whole course long newGroupCode = position==0? 0 : myGroups.get(position-1).getId(); if(chosenGroupCode != newGroupCode || tree == null){ chosenGroupCode = newGroupCode; groupPosition = position; requestDirectoryTree(); } } @Override public void onNothingSelected(AdapterView<?> arg0) { } } /** * Method to request files tree to SWAD thought the web services GETDIRECTORYTREE * */ private void requestDirectoryTree(){ Intent activity; activity = new Intent(getBaseContext(), DirectoryTreeDownload.class); activity.putExtra("treeCode", downloadsAreaCode); activity.putExtra("groupCode", (int)chosenGroupCode); startActivityForResult(activity, Constants.DIRECTORY_TREE_REQUEST_CODE); } /** * It checks if the external storage is available * @return 0 - if external storage can not be read either wrote * 1 - if external storage can only be read * 2 - if external storage can be read and wrote * */ private int checkMediaAvailability(){ String state = Environment.getExternalStorageState(); int returnValue = 0; if (Environment.MEDIA_MOUNTED.equals(state)) { // We can read and write the media returnValue = 2; } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { // We can only read the media returnValue = 1; } else { // Something else is wrong. It may be one of many other states, but all we need // to know is we can neither read nor write returnValue = 0; } return returnValue; } /** * it gets the directory path where the files will be located.This will be /$EXTERNAL_STORAGE/$DOWNLOADS * */ private String getDirectoryPath(){ //String downloadsDirName = Environment.getExternalStorageDirectory()+File.separator+"download"; String downloadsDirName = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath(); return downloadsDirName; } /** * it initializes the download the file from the url @a url and stores it in the directory name @directory * @param directory - directory where the downloaded file will be stored * @param url - url from which the file is downloaded * @param fileSize - file size of the file. It is used to show the download progress in the notification * */ private void downloadFile(String directory, String url,long fileSize){ new FileDownloaderAsyncTask(getApplicationContext(),this.chosenNodeName,true,fileSize).execute(directory,url); } /** * Method to request info file identified with @a fileCode to SWAD thought the web services GETFILE * @fileCode file code * */ private void requestGetFile(long fileCode){ Intent activity; activity = new Intent(getBaseContext(), GetFile.class); activity.putExtra("fileCode", fileCode); //activity.putExtra("path", navigator.getPath() + fileName); startActivityForResult(activity, Constants.GETFILE_REQUEST_CODE); } /** * Method that shows information file and allows its download * It has a button to confirm the download. If It is confirmed getFile will be requested to get the link * */ private AlertDialog createFileInfoDialog(String name,long size, long time,String uploader,long fileCode){ AlertDialog.Builder builder = new AlertDialog.Builder(this); AlertDialog dialog; final long code = fileCode; this.fileSize = size; Date d = new Date(time * 1000); java.text.DateFormat dateShortFormat = android.text.format.DateFormat.getDateFormat(this); java.text.DateFormat timeFormat = android.text.format.DateFormat.getTimeFormat(this); String uploaderName; if(uploader.compareTo("") != 0) uploaderName = uploader; else uploaderName = this.getResources().getString(R.string.unknown); String message = this.getResources().getString(R.string.fileTitle) +" " + name+ '\n' + this.getResources().getString(R.string.sizeFileTitle) +" " + humanReadableByteCount(size, true) + '\n'+ this.getResources().getString(R.string.uploaderTitle) +" " + uploaderName+ '\n' + this.getResources().getString(R.string.creationTimeTitle) +" " + dateShortFormat.format(d)+ " "+(timeFormat.format(d)); builder.setTitle(name); builder.setMessage(message); builder.setPositiveButton(R.string.downloadFileTitle, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { requestGetFile(code); } }); builder.setNegativeButton(R.string.cancelMsg, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); } }); dialog = builder.create(); return dialog; } /** Method to show file size in bytes in a human readable way * http://stackoverflow.com/questions/3758606/how-to-convert-byte-size-into-human-readable-format-in-java * */ private static String humanReadableByteCount(long bytes, boolean si) { int unit = si ? 1000 : 1024; if (bytes < unit) return bytes + " B"; int exp = (int) (Math.log(bytes) / Math.log(unit)); String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp-1) + (si ? "" : "i"); return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre); } /** * Launches an action when refresh button is pushed. * * The listener onClick is set in action_bar.xml * @param v Actual view */ public void onRefreshClick(View v) { updateButton.setVisibility(View.GONE); progressbar.setVisibility(View.VISIBLE); refresh = true; Intent activity = new Intent(getBaseContext(),GroupTypes.class); activity.putExtra("courseCode", Constants.getSelectedCourseCode()); startActivityForResult(activity,Constants.GROUPTYPES_REQUEST_CODE); } // /** // * This method is launched instead of onCreate when device rotates // * It prevents from repeating calls to web services when they are not necessary // * */ // @Override // public void onConfigurationChanged(Configuration newConfig) { // super.onConfigurationChanged(newConfig); // Log.i(TAG,"Device rotation"); // // Checks the orientation of the screen ///* if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) { // Log.i(TAG,"onConfigChanged - Landscape"); // } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){ // Log.i(TAG,"onConfigChanged - Portrait"); // }*/ // } }
false
true
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if(savedInstanceState != null){ this.saveState = savedInstanceState.getBoolean("saveState", false); if(saveState){ this.groupsRequested = true; this.previousConnection = savedInstanceState.getBoolean("previousConnection", false); this.chosenGroupCode = savedInstanceState.getLong("chosenGroupCode",0); this.groupPosition = savedInstanceState.getInt("groupPosition",0); if(previousConnection){ this.tree = savedInstanceState.getString("tree"); String path = savedInstanceState.getString("path"); this.navigator = new DirectoryNavigator(this.tree); if(path.compareTo("/") !=0){ int firstBar = path.indexOf('/',0); int nextBar = path.indexOf('/', firstBar+1); while(nextBar != -1){ String dir = path.substring(firstBar+1, nextBar); this.navigator.goToSubDirectory(dir); firstBar = nextBar; nextBar = path.indexOf('/', firstBar+1); } } } } } setContentView(R.layout.navigation); downloadsAreaCode = getIntent().getIntExtra("downloadsAreaCode", Constants.DOCUMENTS_AREA_CODE); //set the module bar if (downloadsAreaCode == Constants.DOCUMENTS_AREA_CODE) { moduleIcon = (ImageView) this.findViewById(R.id.moduleIcon); moduleIcon.setBackgroundResource(R.drawable.folder); moduleText = (TextView) this.findViewById(R.id.moduleName); moduleText.setText(R.string.documentsDownloadModuleLabel); } else { // SHARE_AREA_CODE moduleIcon = (ImageView) this.findViewById(R.id.moduleIcon); moduleIcon.setBackgroundResource(R.drawable.folder_users); moduleText = (TextView) this.findViewById(R.id.moduleName); moduleText.setText(R.string.sharedsDownloadModuleLabel); } noConnectionText = (TextView) this.findViewById(R.id.noConnectionText); grid = (GridView) this.findViewById(R.id.gridview); grid.setOnItemClickListener((new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id) { //TextView text = (TextView) v.findViewById(R.id.icon_text); //chosenNodeName = text.getText().toString(); //DirectoryItem node = navigator.getDirectoryItem(chosenNodeName); DirectoryItem node = navigator.getDirectoryItem(position); if(node.getFileCode() == -1) //it is a directory therefore navigates into it updateView(navigator.goToSubDirectory(position)); //updateView(navigator.goToSubDirectory(chosenNodeName)); else{ //it is a files therefore gets its information through web service GETFILE chosenNodeName = node.getName(); AlertDialog fileInfoDialog = createFileInfoDialog(node.getName(),node.getSize(),node.getTime(),node.getPublisher(),node.getFileCode()); fileInfoDialog.show(); } } })); ImageButton homeButton = (ImageButton) this .findViewById(R.id.home_button); homeButton.setOnClickListener((new OnClickListener() { @Override public void onClick(View v) { updateView(navigator.goToRoot()); } })); ImageButton parentButton = (ImageButton) this .findViewById(R.id.parent_button); parentButton.setOnClickListener((new OnClickListener() { @Override public void onClick(View v) { updateView(navigator.goToParentDirectory()); } })); progressbar = (ProgressBar) this.findViewById(R.id.progress_refresh); progressbar.setVisibility(View.GONE); updateButton = (ImageButton)this.findViewById(R.id.refresh); updateButton.setVisibility(View.VISIBLE); }
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if(savedInstanceState != null){ this.saveState = savedInstanceState.getBoolean("saveState", false); if(saveState){ this.groupsRequested = true; this.previousConnection = savedInstanceState.getBoolean("previousConnection", false); this.chosenGroupCode = savedInstanceState.getLong("chosenGroupCode",0); this.groupPosition = savedInstanceState.getInt("groupPosition",0); if(previousConnection){ this.tree = savedInstanceState.getString("tree"); String path = savedInstanceState.getString("path"); this.navigator = new DirectoryNavigator(this.tree); if(path.compareTo("/") !=0){ int firstBar = path.indexOf('/',0); int nextBar = path.indexOf('/', firstBar+1); while(nextBar != -1){ String dir = path.substring(firstBar+1, nextBar); this.navigator.goToSubDirectory(dir); firstBar = nextBar; nextBar = path.indexOf('/', firstBar+1); } } } } } setContentView(R.layout.navigation); downloadsAreaCode = getIntent().getIntExtra("downloadsAreaCode", Constants.DOCUMENTS_AREA_CODE); //set the module bar if (downloadsAreaCode == Constants.DOCUMENTS_AREA_CODE) { moduleIcon = (ImageView) this.findViewById(R.id.moduleIcon); moduleIcon.setBackgroundResource(R.drawable.folder); moduleText = (TextView) this.findViewById(R.id.moduleName); moduleText.setText(R.string.documentsDownloadModuleLabel); } else { // SHARE_AREA_CODE moduleIcon = (ImageView) this.findViewById(R.id.moduleIcon); moduleIcon.setBackgroundResource(R.drawable.folder_users); moduleText = (TextView) this.findViewById(R.id.moduleName); moduleText.setText(R.string.sharedsDownloadModuleLabel); } noConnectionText = (TextView) this.findViewById(R.id.noConnectionText); grid = (GridView) this.findViewById(R.id.gridview); grid.setOnItemClickListener((new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id) { //TextView text = (TextView) v.findViewById(R.id.icon_text); //chosenNodeName = text.getText().toString(); //DirectoryItem node = navigator.getDirectoryItem(chosenNodeName); DirectoryItem node = navigator.getDirectoryItem(position); if(node.getFileCode() == -1) //it is a directory therefore navigates into it updateView(navigator.goToSubDirectory(position)); //updateView(navigator.goToSubDirectory(chosenNodeName)); else{ //it is a files therefore gets its information through web service GETFILE chosenNodeName = node.getName(); AlertDialog fileInfoDialog = createFileInfoDialog(node.getName(),node.getSize(),node.getTime(),node.getPublisher(),node.getFileCode()); fileInfoDialog.show(); } } })); ImageButton homeButton = (ImageButton) this .findViewById(R.id.home_button); homeButton.setOnClickListener((new OnClickListener() { @Override public void onClick(View v) { if(navigator != null) { updateView(navigator.goToRoot()); } } })); ImageButton parentButton = (ImageButton) this .findViewById(R.id.parent_button); parentButton.setOnClickListener((new OnClickListener() { @Override public void onClick(View v) { if(navigator != null) { updateView(navigator.goToParentDirectory()); } } })); progressbar = (ProgressBar) this.findViewById(R.id.progress_refresh); progressbar.setVisibility(View.GONE); updateButton = (ImageButton)this.findViewById(R.id.refresh); updateButton.setVisibility(View.VISIBLE); }
diff --git a/src/main/java/org/primefaces/component/menu/BaseMenuRenderer.java b/src/main/java/org/primefaces/component/menu/BaseMenuRenderer.java index 285a95152..92a0e5ae5 100644 --- a/src/main/java/org/primefaces/component/menu/BaseMenuRenderer.java +++ b/src/main/java/org/primefaces/component/menu/BaseMenuRenderer.java @@ -1,120 +1,117 @@ /* * Copyright 2009-2011 Prime Technology. * * 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.primefaces.component.menu; import java.io.IOException; import javax.faces.FacesException; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.context.ResponseWriter; import org.primefaces.component.menuitem.MenuItem; import org.primefaces.renderkit.CoreRenderer; import org.primefaces.util.ComponentUtils; public abstract class BaseMenuRenderer extends CoreRenderer { @Override public void encodeEnd(FacesContext context, UIComponent component) throws IOException { AbstractMenu menu = (AbstractMenu) component; if(menu.shouldBuildFromModel()) { menu.buildMenuFromModel(); } encodeMarkup(context, menu); encodeScript(context, menu); } protected abstract void encodeMarkup(FacesContext context, AbstractMenu abstractMenu) throws IOException; protected abstract void encodeScript(FacesContext context, AbstractMenu abstractMenu) throws IOException; protected void encodeMenuItem(FacesContext context, MenuItem menuItem) throws IOException { String clientId = menuItem.getClientId(context); ResponseWriter writer = context.getResponseWriter(); String icon = menuItem.getIcon(); if(menuItem.shouldRenderChildren()) { renderChildren(context, menuItem); } else { boolean disabled = menuItem.isDisabled(); String onclick = menuItem.getOnclick(); writer.startElement("a", null); String styleClass = menuItem.getStyleClass(); styleClass = styleClass == null ? MenuItem.STYLE_CLASS : MenuItem.STYLE_CLASS + " " + styleClass; styleClass = disabled ? styleClass + " ui-state-disabled" : styleClass; writer.writeAttribute("class", styleClass, null); if(menuItem.getStyle() != null) writer.writeAttribute("style", menuItem.getStyle(), null); if(menuItem.getUrl() != null) { - writer.writeAttribute("href", getResourceURL(context, menuItem.getUrl()), null); + String href = disabled ? "javascript:void(0)" : getResourceURL(context, menuItem.getUrl()); + writer.writeAttribute("href", href, null); - if(menuItem.getTarget() != null) writer.writeAttribute("target", menuItem.getTarget(), null); + if(menuItem.getTarget() != null) + writer.writeAttribute("target", menuItem.getTarget(), null); } else { writer.writeAttribute("href", "javascript:void(0)", null); UIComponent form = ComponentUtils.findParentForm(context, menuItem); if(form == null) { throw new FacesException("Menubar must be inside a form element"); } - if(!disabled) { - String formClientId = form.getClientId(context); - String command = menuItem.isAjax() ? buildAjaxRequest(context, menuItem) : buildNonAjaxRequest(context, menuItem, formClientId, clientId); + String command = menuItem.isAjax() ? buildAjaxRequest(context, menuItem) : buildNonAjaxRequest(context, menuItem, form.getClientId(context), clientId); - onclick = onclick == null ? command : command + ";" + onclick; - } else { - onclick = "return false;"; - } + onclick = onclick == null ? command : onclick + ";" + command; } - if(onclick != null) { + if(onclick != null && !disabled) { writer.writeAttribute("onclick", onclick, null); } if(icon != null) { writer.startElement("span", null); writer.writeAttribute("class", icon + " wijmo-wijmenu-icon-left", null); writer.endElement("span"); } if(menuItem.getValue() != null) { writer.startElement("span", null); writer.writeAttribute("class", "wijmo-wijmenu-text", null); writer.write((String) menuItem.getValue()); writer.endElement("span"); } writer.endElement("a"); } } @Override public void encodeChildren(FacesContext facesContext, UIComponent component) throws IOException { //Do nothing } @Override public boolean getRendersChildren() { return true; } }
false
true
protected void encodeMenuItem(FacesContext context, MenuItem menuItem) throws IOException { String clientId = menuItem.getClientId(context); ResponseWriter writer = context.getResponseWriter(); String icon = menuItem.getIcon(); if(menuItem.shouldRenderChildren()) { renderChildren(context, menuItem); } else { boolean disabled = menuItem.isDisabled(); String onclick = menuItem.getOnclick(); writer.startElement("a", null); String styleClass = menuItem.getStyleClass(); styleClass = styleClass == null ? MenuItem.STYLE_CLASS : MenuItem.STYLE_CLASS + " " + styleClass; styleClass = disabled ? styleClass + " ui-state-disabled" : styleClass; writer.writeAttribute("class", styleClass, null); if(menuItem.getStyle() != null) writer.writeAttribute("style", menuItem.getStyle(), null); if(menuItem.getUrl() != null) { writer.writeAttribute("href", getResourceURL(context, menuItem.getUrl()), null); if(menuItem.getTarget() != null) writer.writeAttribute("target", menuItem.getTarget(), null); } else { writer.writeAttribute("href", "javascript:void(0)", null); UIComponent form = ComponentUtils.findParentForm(context, menuItem); if(form == null) { throw new FacesException("Menubar must be inside a form element"); } if(!disabled) { String formClientId = form.getClientId(context); String command = menuItem.isAjax() ? buildAjaxRequest(context, menuItem) : buildNonAjaxRequest(context, menuItem, formClientId, clientId); onclick = onclick == null ? command : command + ";" + onclick; } else { onclick = "return false;"; } } if(onclick != null) { writer.writeAttribute("onclick", onclick, null); } if(icon != null) { writer.startElement("span", null); writer.writeAttribute("class", icon + " wijmo-wijmenu-icon-left", null); writer.endElement("span"); } if(menuItem.getValue() != null) { writer.startElement("span", null); writer.writeAttribute("class", "wijmo-wijmenu-text", null); writer.write((String) menuItem.getValue()); writer.endElement("span"); } writer.endElement("a"); } }
protected void encodeMenuItem(FacesContext context, MenuItem menuItem) throws IOException { String clientId = menuItem.getClientId(context); ResponseWriter writer = context.getResponseWriter(); String icon = menuItem.getIcon(); if(menuItem.shouldRenderChildren()) { renderChildren(context, menuItem); } else { boolean disabled = menuItem.isDisabled(); String onclick = menuItem.getOnclick(); writer.startElement("a", null); String styleClass = menuItem.getStyleClass(); styleClass = styleClass == null ? MenuItem.STYLE_CLASS : MenuItem.STYLE_CLASS + " " + styleClass; styleClass = disabled ? styleClass + " ui-state-disabled" : styleClass; writer.writeAttribute("class", styleClass, null); if(menuItem.getStyle() != null) writer.writeAttribute("style", menuItem.getStyle(), null); if(menuItem.getUrl() != null) { String href = disabled ? "javascript:void(0)" : getResourceURL(context, menuItem.getUrl()); writer.writeAttribute("href", href, null); if(menuItem.getTarget() != null) writer.writeAttribute("target", menuItem.getTarget(), null); } else { writer.writeAttribute("href", "javascript:void(0)", null); UIComponent form = ComponentUtils.findParentForm(context, menuItem); if(form == null) { throw new FacesException("Menubar must be inside a form element"); } String command = menuItem.isAjax() ? buildAjaxRequest(context, menuItem) : buildNonAjaxRequest(context, menuItem, form.getClientId(context), clientId); onclick = onclick == null ? command : onclick + ";" + command; } if(onclick != null && !disabled) { writer.writeAttribute("onclick", onclick, null); } if(icon != null) { writer.startElement("span", null); writer.writeAttribute("class", icon + " wijmo-wijmenu-icon-left", null); writer.endElement("span"); } if(menuItem.getValue() != null) { writer.startElement("span", null); writer.writeAttribute("class", "wijmo-wijmenu-text", null); writer.write((String) menuItem.getValue()); writer.endElement("span"); } writer.endElement("a"); } }
diff --git a/src/fr/debnet/ircrpg/game/Game.java b/src/fr/debnet/ircrpg/game/Game.java index e6c56d6..0c37859 100644 --- a/src/fr/debnet/ircrpg/game/Game.java +++ b/src/fr/debnet/ircrpg/game/Game.java @@ -1,1842 +1,1842 @@ package fr.debnet.ircrpg.game; import fr.debnet.ircrpg.Config; import fr.debnet.ircrpg.DAO; import fr.debnet.ircrpg.Strings; import fr.debnet.ircrpg.enums.Action; import fr.debnet.ircrpg.enums.Activity; import fr.debnet.ircrpg.enums.Model; import fr.debnet.ircrpg.enums.Potion; import fr.debnet.ircrpg.enums.Return; import fr.debnet.ircrpg.enums.Skill; import fr.debnet.ircrpg.enums.Status; import fr.debnet.ircrpg.game.queues.EventQueue; import fr.debnet.ircrpg.interfaces.IQueue; import fr.debnet.ircrpg.interfaces.INotifiable; import fr.debnet.ircrpg.game.queues.UpdateQueue; import fr.debnet.ircrpg.helpers.CheckItem; import fr.debnet.ircrpg.helpers.CheckPlayer; import fr.debnet.ircrpg.helpers.CheckPotion; import fr.debnet.ircrpg.helpers.CheckSpell; import fr.debnet.ircrpg.helpers.Helpers; import fr.debnet.ircrpg.mock.Random; import fr.debnet.ircrpg.models.Event; import fr.debnet.ircrpg.models.Item; import fr.debnet.ircrpg.models.Modifiers; import fr.debnet.ircrpg.models.Player; import fr.debnet.ircrpg.models.Result; import fr.debnet.ircrpg.models.Spell; import fr.debnet.ircrpg.models.Time; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Game engine * @author Marc */ public class Game { private Admin admin; private Random random; private Map<String, Player> playersByNickname; private Map<String, Player> playersByUsername; private Map<String, Item> itemsByCode; private Map<String, Spell> spellsByCode; private Map<String, Event> eventsByCode; private List<IQueue> queues; /** * Constructor */ public Game() { this.admin = new Admin(this); this.random = new Random(); this.queues = new ArrayList<>(); this.playersByNickname = new HashMap<>(); this.playersByUsername = new HashMap<>(); this.itemsByCode = new HashMap<>(); this.spellsByCode = new HashMap<>(); this.eventsByCode = new HashMap<>(); // Run queues this.queues.add(UpdateQueue.getInstance(this)); this.queues.add(EventQueue.getInstance(this)); // Load all entities if (Config.PERSISTANCE) { this.reloadItems(); // Items this.reloadSpells(); // Spells this.reloadEvents(); // Events this.reloadPlayers(); // Players (must be at the end) } } /** * Get the admin functions * @return Admin instance */ public Admin getAdmin() { return this.admin; } /** * Reload all players */ protected final void reloadPlayers() { List<Player> players = DAO.<Player>getObjectList("from " + Model.PLAYER); this.playersByNickname.clear(); this.playersByUsername.clear(); for (Player player : players) { this.playersByNickname.put(player.getNickname().toLowerCase(), player); this.playersByUsername.put(player.getUsername().toLowerCase(), player); // Update each queue with all players this.updateQueues(player); } } /** * Reload all items */ protected final void reloadItems() { List<Item> items = DAO.<Item>getObjectList("from " + Model.ITEM); this.itemsByCode.clear(); for (Item item : items) { this.itemsByCode.put(item.getCode().toLowerCase(), item); } } /** * Reload all spells */ protected final void reloadSpells() { List<Spell> spells = DAO.<Spell>getObjectList("from " + Model.SPELL); this.spellsByCode.clear(); for (Spell spell : spells) { this.spellsByCode.put(spell.getCode().toLowerCase(), spell); } } /** * Reload all events */ protected final void reloadEvents() { List<Event> events = DAO.<Event>getObjectList("from " + Model.EVENT); this.eventsByCode.clear(); for (Event event : events) { this.eventsByCode.put(event.getCode().toLowerCase(), event); } } /** * Register a notifiable object to all queues * @param notifiable Notifiable object */ public void registerNotifiable(INotifiable notifiable) { for (IQueue queue : this.queues) { queue.register(notifiable); } } /** * Update queues * @param player Player */ public void updateQueues(Player player) { for (IQueue queue : this.queues) { queue.update(player); } } /** * Reload queues */ public void reloadQueues() { for (Map.Entry<String, Player> entry : this.playersByNickname.entrySet()) { this.updateQueues(entry.getValue()); } } /** * Get player by nickname * @param nickname Nickname * @return Player instance or null if not found */ public Player getPlayerByNickname(String nickname) { String key = nickname.toLowerCase(); if (this.playersByNickname.containsKey(key)) { return this.playersByNickname.get(key); } return null; } /** * Get player by username * @param username Username * @return Player instance or null if not found */ public Player getPlayerByUsername(String username) { String key = username.toLowerCase(); if (this.playersByUsername.containsKey(key)) { return this.playersByUsername.get(key); } return null; } /** * Get item by its code * @param item Item code (unique) * @return Item instance or null if not found */ public Item getItemByCode(String item) { if (this.itemsByCode.containsKey(item)) { return this.itemsByCode.get(item); } return null; } /** * Get spell by its code * @param spell Spell code (unique) * @return Spell instance or null if not found */ public Spell getSpellByCode(String spell) { if (this.spellsByCode.containsKey(spell)) { return this.spellsByCode.get(spell); } return null; } /** * Get event by its code * @param event Event code (unique) * @return Event instance of null if not found */ public Event getEventByCode(String event) { if (this.eventsByCode.containsKey(event)) { return this.eventsByCode.get(event); } return null; } /** * Get events matching player's current context * @param player Player * @return List of events */ public List<Event> getEventsForPlayer(Player player) { List<Event> events = new ArrayList<>(); // Get player's maximum health and mana Modifiers modifiers = new Modifiers(player); double maxHealth = player.getMaxHealth() + modifiers.getHealth(); double maxMana = player.getMaxMana() + modifiers.getMana(); double healthPercentage = 100 * player.getCurrentHealth() / maxHealth; double manaPercentage = 100 * player.getCurrentMana() / maxMana; for (Map.Entry<String, Event> entry : this.eventsByCode.entrySet()) { Event event = entry.getValue(); // Parameters boolean isBelow = event.getValueBelow(); boolean isPercentage = event.getValuePercentage(); // Check activity boolean activity = event.getActivityCondition() == Activity.NONE || event.getActivityCondition() == player.getActivity(); if (!activity) continue; // Check status boolean status = event.getStatusCondition() == Status.NONE || event.getStatusCondition() == player.getStatus(); if (!status) continue; // Check level boolean level = event.getLevelCondition() == 0 || (isBelow ? event.getLevelCondition() <= player.getLevel() : event.getLevelCondition() >= player.getLevel() ); if (!level) continue; // Check gold boolean gold = event.getGoldCondition() == 0 || (isBelow ? event.getGoldCondition() <= player.getGold() : event.getGoldCondition() >= player.getGold() ); if (!gold) continue; // Check health boolean health = event.getHealthCondition() == 0 || (isPercentage ? (isBelow ? event.getHealthCondition() <= healthPercentage : event.getHealthCondition() >= healthPercentage) : (isBelow ? event.getHealthCondition() <= player.getCurrentHealth() : event.getHealthCondition() >= player.getCurrentHealth() )); if (!health) continue; // Check mana boolean mana = event.getManaCondition() == 0 || (isPercentage ? (isBelow ? event.getManaCondition() <= manaPercentage : event.getManaCondition() >= manaPercentage) : (isBelow ? event.getManaCondition() <= player.getCurrentMana() : event.getManaCondition() >= player.getCurrentMana() )); if (!mana) continue; // Add executeEvent to list (all checks passed) events.add(event); } return events; } /** * Update player data * @param sender Player's nickname * @return Result */ public Result updatePlayerByNickname(String sender) { Player player = this.getPlayerByNickname(sender); if (player != null) { return this.update(player, false, false); } return null; } /** * Update a player and push returns in given result if success * @param result Given result instance * @param player Player instance * @param save Save the player in database ? * @param target Is the player targetted in the action ? * @return Result Update result onluy */ protected Result updateAndReturn(Result result, Player player, boolean save, boolean target) { Result update = this.update(player, save, target); if (update.isSuccess()) result.addReturnList(update.getReturns()); return update; } /** * Update player data (activity, status and experience) * @param player Player instance * @param save Save the player in database ? * @param target Is the player targetted in the action ? * @return Result */ public Result update(Player player, boolean save, boolean target) { Result result = new Result(Action.UPDATE, player); // Get time difference java.util.Calendar lastUpdate = player.getLastUpdate(); Calendar current = Calendar.getInstance(); long diff = current.getTimeInMillis() - lastUpdate.getTimeInMillis(); // Items modifiers Modifiers modifiers = new Modifiers(player); // Status double hours = diff > player.getStatusDuration() ? player.getStatusDuration() * 1d / Config.HOUR : diff * 1d / Config.HOUR; switch (player.getStatus()) { case POISONED: { // Removing status if timeout if (diff >= player.getStatusDuration()) { result.addReturn(target ? Return.TARGET_POISON_CURED : Return.PLAYER_POISON_CURED); player.setStatus(Status.NORMAL); player.setStatusDuration(0l); } else { player.addStatusDuration(-diff); } // Lower health points double damage = (player.getMaxHealth() * (Config.POISON_EFFECT + modifiers.getPoisonEffect())) * hours; damage = damage < 0 ? 0d : damage; player.addHealth(-damage); // Update statistics player.addDamageTaken(damage); // Update return result.addPlayerHealthChanges(-damage); break; } case PARALYZED: { // Removing status if timeout if (diff >= player.getStatusDuration()) { result.addReturn(target ? Return.TARGET_PARALYSIS_CURED : Return.PLAYER_PARALYSIS_CURED); player.setStatus(Status.NORMAL); player.setStatusDuration(0l); } else { player.addStatusDuration(-diff); } break; } case DEAD: { // Removing status if timeout if (diff >= player.getStatusDuration()) { result.addReturn(target ? Return.TARGET_DEATH_CURED : Return.PLAYER_DEATH_CURED); player.setStatus(Status.NORMAL); player.setStatusDuration(0l); double hp = player.getMaxHealth() + modifiers.getHealth(); player.setCurrentHealth(hp); double mp = player.getMaxMana() + modifiers.getMana(); player.setCurrentMana(mp); // Update return result.addPlayerHealthChanges(hp); result.addPlayerManaChanges(mp); } else { player.addStatusDuration(-diff); } break; } } // Activity hours = diff * 1d / Config.HOUR; switch (player.getActivity()) { case RESTING: { // Limiting hours to max time hours = hours > Config.RESTING_TIME_MAX / 60d ? Config.RESTING_TIME_MAX / 60d : hours; // Restoring health points double healRate = Config.RATE_HEALTH + modifiers.getHealthRate(); double heal = healRate * hours; int maxHp = player.getMaxHealth() + modifiers.getHealth(); double hp = player.getCurrentHealth() + heal; hp = hp > maxHp ? maxHp : hp; player.setCurrentHealth(hp); // Removing activity if timeout player.addActivityDuration(diff); if (player.getActivityDuration() >= Config.RESTING_TIME_MAX * Config.MINUTE) { result.setValue(healRate * Config.RESTING_TIME_MAX / 60d); player.setActivity(Activity.WAITING); player.setActivityDuration(0l); result.addReturn(target ? Return.TARGET_RESTING_ENDED : Return.PLAYER_RESTING_ENDED); } // Update statistics player.addTimeResting((long) (hours * Config.HOUR)); // Update return result.addPlayerHealthChanges(heal); break; } case TRAINING: { // Limiting hours to max time hours = hours > Config.TRAINING_TIME_MAX / 60d ? Config.TRAINING_TIME_MAX / 60d : hours; // Add experience points double xpRate = Config.RATE_EXPERIENCE + modifiers.getExperienceRate(); double xp = xpRate * hours; player.addExperience(xp); // Removing activity if timeout player.addActivityDuration(diff); if (player.getActivityDuration() >= Config.TRAINING_TIME_MAX * Config.MINUTE) { result.setValue(xpRate * Config.TRAINING_TIME_MAX / 60d); player.setActivity(Activity.WAITING); player.setActivityDuration(0l); result.addReturn(target ? Return.TARGET_TRAINING_ENDED : Return.PLAYER_TRAINING_ENDED); } // Update statistics player.addTimeTraining((long) (hours * Config.HOUR)); // Update return result.addPlayerExperienceChanges(xp); break; } case WORKING: { // Limiting hours to max time hours = hours > Config.WORKING_TIME_MAX / 60d ? Config.WORKING_TIME_MAX / 60d : hours; // Earn gold coins double goldRate = Config.RATE_GOLD + modifiers.getGoldRate(); double gold = goldRate * hours; player.addGold(gold); // Removing activity if timeout player.addActivityDuration(diff); if (player.getActivityDuration() >= Config.WORKING_TIME_MAX * Config.MINUTE) { result.setValue(goldRate * Config.WORKING_TIME_MAX / 60d); player.setActivity(Activity.WAITING); player.setActivityDuration(0l); result.addReturn(target ? Return.TARGET_WORKING_ENDED : Return.PLAYER_WORKING_ENDED); } // Update statistics player.addTimeWorking((long) (hours * Config.HOUR)); // Update return result.addPlayerGoldChanges(gold); break; } case WAITING: { player.addActivityDuration(diff); if (player.getActivityDuration() >= Config.ACTIVITY_PENALTY * Config.MINUTE) { player.setActivity(Activity.NONE); player.setActivityDuration(0l); result.addReturn(target ? Return.TARGET_WAITING_ENDED : Return.PLAYER_WAITING_ENDED); } break; } } // Check if player is dead poisonned if (player.getCurrentHealth() <= 0 && player.getStatus() != Status.DEAD) { // Change status player.setStatus(Status.DEAD); player.setStatusDuration(Config.DEATH_PENALTY * Config.MINUTE); player.setCurrentHealth(0d); // Reset activity player.setActivity(Activity.NONE); player.setActivityDuration(0l); // Update return result.addReturn(target ? Return.TARGET_KILLED_BY_POISON : Return.PLAYER_KILLED_BY_POISON); // Update statistics player.addDeaths(1); } // Experience gained for (int level = player.getLevel() + 1; level < 100; level++) { int required = ((level * (level - 1)) / 2) * Config.RATE_LEVEL; player.setExperienceRequired(required); if (player.getExperience() >= required) { player.addLevel(1); player.addSkillPoints(Config.RATE_SKILL); result.addReturn(target ? Return.TARGET_LEVEL_UP : Return.PLAYER_LEVEL_UP); } else break; } // Save object player.addTimeIngame(diff); player.setLastUpdate(current); if (save) { if (Config.PERSISTANCE && !DAO.<Player>setObject(player)) { result.addReturn(Return.PERSISTANCE_ERROR); return result; } // Update queues on save this.updateQueues(player); } // Return result.setSuccess(true); if (Config.PERSISTANCE && !result.getReturns().isEmpty()) { DAO.<Result>addObject(result); } return result; } /** * Execute an event on a player * @param player Player * @param event Event * @return Result */ public Result executeEvent(Player player, Event event) { Result result = new Result(Action.EVENT, player); // Calculate variance double variance = (this.random.nextDouble() + 0.5d) * event.getVariance(); variance = variance == 0d ? 1d : variance; // Health double health = event.getHealthModifier() * variance; player.addHealth(health); result.setPlayerHealthChanges(health); // Mana double mana = event.getManaModifier() * variance; player.addMana(mana); result.setPlayerManaChanges(mana); // Experience double xp = event.getExperienceModifier() * variance; player.addExperience(xp); result.setPlayerExperienceChanges(xp); // Gold double gold = event.getGoldModifier() * variance; player.addGold(gold); result.setPlayerGoldChanges(gold); // Event specific result.setDetails(event.getId().toString()); result.setCustomMessage(event.getDescription()); // Update and save player this.updateAndReturn(result, player, true, false); // Return result.setSuccess(true); if (Config.PERSISTANCE) { DAO.<Result>addObject(result); } return result; } /** * Fight between two players (with spell or not) * @param sender Attacker's nickname * @param target Defender's nickname * @param spell Spell code (or null if physical fight) * @return Result */ public Result fight(String sender, String target, String magic) { Result result = new Result(Action.FIGHT); boolean self = sender.equals(target); // Get attacker Player attacker = this.getPlayer(result, sender); if (attacker == null) return result; // Get defender Player defender; if (!self) { defender = this.getPlayer(result, target, true); if (defender == null) return result; } else { defender = attacker; result.setTarget(defender); } // Update players this.updateAndReturn(result, attacker, false, false); if (!self) this.updateAndReturn(result, defender, false, true); // Check attacker if (!Helpers.checkPlayer(result, attacker, CheckPlayer.from( CheckPlayer.IS_BUSY, CheckPlayer.IS_DEAD, CheckPlayer.IS_PARALYZED, CheckPlayer.HAS_ACTED ) )) return result; // Check defender if (!self && !Helpers.checkPlayer(result, defender, CheckPlayer.from( CheckPlayer.IS_BUSY, CheckPlayer.IS_DEAD, CheckPlayer.IS_PARALYZED, CheckPlayer.IS_TARGET ) )) return result; // Get spell Spell spell = null; if (magic != null) { spell = this.getSpellByCode(magic); if (spell == null) { // Update return result.addReturn(Return.UNKNOWN_SPELL); return result; } else if (!attacker.getSpells().contains(spell)) { // Update return result.addReturn(Return.SPELL_NOT_LEARNED); return result; } } // Items modifiers Modifiers attackerModifiers = new Modifiers(attacker); Modifiers defenderModifiers = new Modifiers(defender); // Attacker phase if (spell == null) { if (self) { // Update return result.addReturn(Return.NOT_SELF_ATTACK); return result; } // With no spell double accuracy = Config.ATTACK_ACCURACY + attackerModifiers.getAttackAccuracy(); double chance = random.nextDouble(); if (chance > accuracy) { // Update return result.addReturn(Return.ATTACK_FAILED); } else { // Update return result.addReturn(Return.ATTACK_SUCCEED); // Health change double damage = (attacker.getAttack() + attackerModifiers.getAttack()) * (1d - chance); defender.addHealth(-damage); // Update return result.addTargetHealthChanges(-damage); // Update statistics attacker.addDamageGiven(damage); defender.addDamageTaken(damage); // Is defender dead? if (defender.getCurrentHealth() <= 0) { defender.setStatus(Status.DEAD); defender.setStatusDuration(Config.DEATH_PENALTY * Config.MINUTE); defender.setCurrentHealth(0d); // Update return result.addReturn(Return.TARGET_KILLED); // Update statistics attacker.addKills(1); defender.addDeaths(1); // Gold looted double gold = (Config.THEFT_GOLD + attackerModifiers.getTheftGold()) * defender.getGold() * random.nextDouble(); // Update players attacker.addGold(gold); defender.addGold(-gold); // Update return result.addPlayerGoldChanges(gold); result.addTargetGoldChanges(-gold); // Update statistics attacker.addMoneyStolen(gold); } } // Experience gained (attacker) double bonus = 1 + (defender.getLevel() - attacker.getLevel()) * Config.EXPERIENCE_BONUS; bonus = bonus < 0 ? 0 : bonus; - double xp = chance > accuracy ? Config.EXPERIENCE_DEFENSE : Config.EXPERIENCE_ATTACK * + double xp = (chance > accuracy ? Config.EXPERIENCE_DEFENSE : Config.EXPERIENCE_ATTACK) * (bonus + attackerModifiers.getExperienceModifier()); attacker.addExperience(xp); // Update return result.addPlayerExperienceChanges(xp); // Defender phase if (defender.getStatus() != Status.DEAD) { if (defender.getStatus() == Status.PARALYZED) { // Update return result.addReturn(Return.NO_STRIKE_BACK); } else { accuracy = Config.DEFENSE_ACCURACY + defenderModifiers.getDefenseAccuracy(); chance = random.nextDouble(); if (chance > accuracy) { result.addReturn(Return.DEFENSE_FAILED); } else { // Update return result.addReturn(Return.DEFENSE_SUCCEED); // Health change double damage = (defender.getDefense() + defenderModifiers.getDefense()) * (1d - chance); attacker.addHealth(-damage); // Update return result.addPlayerHealthChanges(-damage); // Update statistics defender.addDamageGiven(damage); attacker.addDamageTaken(damage); // Is attacker dead? if (attacker.getCurrentHealth() <= 0) { attacker.setStatus(Status.DEAD); attacker.setStatusDuration(Config.DEATH_PENALTY * Config.MINUTE); attacker.setCurrentHealth(0d); // Update return result.addReturn(Return.PLAYER_KILLED); // Update statistics defender.addKills(1); attacker.addDeaths(1); // Gold looted double gold = (Config.THEFT_GOLD + defenderModifiers.getTheftGold()) * defender.getGold() * random.nextDouble(); // Update players defender.addGold(gold); attacker.addGold(-gold); // Update return result.addPlayerGoldChanges(-gold); result.addTargetGoldChanges(gold); // Update statistics defender.addMoneyStolen(gold); } // Experience gained (defenser) bonus = 1 + (attacker.getLevel() - defender.getLevel()) * Config.EXPERIENCE_BONUS; bonus = bonus < 0 ? 0 : bonus; xp = Config.EXPERIENCE_DEFENSE * (bonus + defenderModifiers.getExperienceModifier()); defender.addExperience(xp); // Update statistics result.addTargetExperienceChanges(xp); } } } } else { result.setAction(Action.MAGIC); result.setDetails(spell.getName()); // With spell if (self && !spell.getIsSelf()) { // Update return result.addReturn(Return.NOT_SELF_SPELL); return result; } if (attacker.getCurrentMana() < spell.getManaCost()) { // Update return result.addReturn(Return.NOT_ENOUGH_MANA); return result; } double accuracy = Config.MAGIC_ACCURACY + attackerModifiers.getMagicAccuracy(); if (random.nextDouble() > accuracy) { // Update return result.addReturn(Return.MAGIC_FAILED); } else { // Update return result.addReturn(Return.MAGIC_SUCCEED); // Health change double hp = defender.getCurrentHealth(); double maxHp = defender.getMaxHealth() + defenderModifiers.getHealth(); hp -= spell.getHealthDamage(); hp = hp > maxHp ? maxHp : hp < 0 ? 0 : hp; defender.setCurrentHealth(hp); // Update return result.addTargetHealthChanges(-spell.getHealthDamage()); // Update statistics if (spell.getHealthDamage() > 0) { attacker.addDamageGiven(spell.getHealthDamage()); defender.addDamageTaken(spell.getHealthDamage()); // Update return result.addReturn(Return.MAGIC_DAMAGE_HEALTH); } else if (spell.getHealthDamage() < 0) { // Update return result.addReturn(Return.MAGIC_RESTORE_HEALTH); } // Is defender dead? if (hp <= 0) { defender.setStatus(Status.DEAD); defender.setStatusDuration(Config.DEATH_PENALTY * Config.MINUTE); defender.setCurrentHealth(0d); // Update return result.addReturn(Return.TARGET_KILLED); // Update statistics attacker.addKills(1); defender.addDeaths(1); // Gold looted double gold = (Config.THEFT_GOLD + defenderModifiers.getTheftGold()) * defender.getGold() * random.nextDouble(); // Update players defender.addGold(gold); attacker.addGold(-gold); // Update return result.addPlayerGoldChanges(-gold); result.addTargetGoldChanges(gold); // Update statistics defender.addMoneyStolen(gold); } else { Status status = defender.getStatus(); // Status change if (spell.getStatus() != Status.NONE) { defender.setStatus(spell.getStatus()); defender.setStatusDuration(spell.getStatusDuration()); // Update return switch (spell.getStatus()) { case PARALYZED: { result.addReturn(Return.TARGET_PARALYZED); break; } case POISONED: { result.addReturn(Return.TARGET_POISONED); break; } case NORMAL: { switch (status) { case NORMAL: break; case PARALYZED: result.addReturn(Return.TARGET_PARALYSIS_CURED); break; case POISONED: result.addReturn(Return.TARGET_POISON_CURED); break; } break; } } } } // Experience earned (if offensive spell) if (!spell.getIsSelf()) { double bonus = 1 + (defender.getLevel() - attacker.getLevel()) * Config.EXPERIENCE_BONUS; bonus = bonus < 0 ? 0 : bonus; double xp = Config.EXPERIENCE_ATTACK * (bonus + attackerModifiers.getExperienceModifier()); attacker.addExperience(xp); // Update statistics result.addPlayerExperienceChanges(xp); } } // Mana consumption attacker.addMana(-spell.getManaCost()); // Update return result.addPlayerManaChanges(-spell.getManaCost()); } // Update and save players attacker.setLastAction(Calendar.getInstance()); this.updateAndReturn(result, attacker, true, false); if (!self) this.updateAndReturn(result, defender, true, true); // Return result.setSuccess(true); if (Config.PERSISTANCE) { DAO.<Result>addObject(result); } return result; } /** * Steal a player * @param sender Player's nickname * @param target Target's nickname * @return Result */ public Result steal(String sender, String target) { Result result = new Result(Action.STEAL); if (sender.equals(target)) { result.addReturn(Return.NOT_SELF_THEFT); return result; } // Get attacker Player attacker = this.getPlayer(result, sender); if (attacker == null) return result; // Get defender Player defender = this.getPlayer(result, target, true); if (defender == null) return result; // Update players this.updateAndReturn(result, attacker, false, false); this.updateAndReturn(result, defender, false, true); // Items modifiers Modifiers attackerModifiers = new Modifiers(attacker); Modifiers defenderModifiers = new Modifiers(defender); // Check attacker if (!Helpers.checkPlayer(result, attacker, CheckPlayer.from( CheckPlayer.IS_BUSY, CheckPlayer.IS_DEAD, CheckPlayer.IS_PARALYZED, CheckPlayer.HAS_ACTED ) )) return result; // Check defender if (!Helpers.checkPlayer(result, defender, CheckPlayer.from( CheckPlayer.IS_BUSY, CheckPlayer.IS_DEAD, CheckPlayer.IS_TARGET ) )) return result; // Attacker phase double accuracy = Config.THEFT_CHANCE + attackerModifiers.getTheftChance(); double chance = random.nextDouble(); if (chance > accuracy) { // Update return result.addReturn(Return.THEFT_FAILED); // Health change double damage = (defender.getDefense() + defenderModifiers.getDefense()) * (1d - chance); attacker.addHealth(-damage); // Update return result.addPlayerHealthChanges(-damage); // Update statistics defender.addDamageGiven(damage); attacker.addDamageTaken(damage); // Is attacker dead? if (attacker.getCurrentHealth() <= 0) { attacker.setStatus(Status.DEAD); attacker.setStatusDuration(Config.DEATH_PENALTY * Config.MINUTE); attacker.setCurrentHealth(0d); // Update return result.addReturn(Return.PLAYER_KILLED); // Update statistics defender.addKills(1); attacker.addDeaths(1); // Gold looted double gold = (Config.THEFT_GOLD + defenderModifiers.getTheftGold()) * defender.getGold() * random.nextDouble(); // Update players defender.addGold(gold); attacker.addGold(-gold); // Update return result.addPlayerGoldChanges(-gold); result.addTargetGoldChanges(gold); // Update statistics defender.addMoneyStolen(gold); } // Experience gained (defenser) double bonus = 1 + (attacker.getLevel() - defender.getLevel()) * Config.EXPERIENCE_BONUS; bonus = bonus < 0 ? 0 : bonus; double xp = Config.EXPERIENCE_DEFENSE * (bonus + defenderModifiers.getExperienceModifier()); defender.addExperience(xp); // Update statistics result.addTargetExperienceChanges(xp); } else { // Update return result.addReturn(Return.THEFT_SUCCEED); // Gold stolen double gold = (Config.THEFT_GOLD + attackerModifiers.getTheftGold()) * defender.getGold() * random.nextDouble(); // Update players attacker.addGold(gold); defender.addGold(-gold); // Update return result.addPlayerGoldChanges(gold); result.addTargetGoldChanges(-gold); // Update statistics attacker.addMoneyStolen(gold); } // Update and save players attacker.setLastAction(Calendar.getInstance()); this.updateAndReturn(result, attacker, true, false); this.updateAndReturn(result, defender, true, true); // Return result.setSuccess(true); if (Config.PERSISTANCE) { DAO.<Result>addObject(result); } return result; } /** * Drink a potion * @param sender Player's nickname * @param potionname Potion name * @return Result */ public Result drink(String sender, String potionname) { Result result = new Result(Action.DRINK); // Get the player Player player = this.getPlayer(result, sender); if (player == null) return result; // Get potion Potion potion = Potion.from(potionname); // Check potion if (!Helpers.checkPotion(result, player, potion, CheckPotion.from( CheckPotion.CAN_CURE, CheckPotion.HAS_ENOUGH ) )) return result; // Update player this.updateAndReturn(result, player, false, false); // Check player if (!Helpers.checkPlayer(result, player, CheckPlayer.from( CheckPlayer.IS_BUSY, CheckPlayer.IS_DEAD, CheckPlayer.HAS_ACTED ) )) return result; // Player modifiers Modifiers modifiers = new Modifiers(player); // Potion type switch (potion) { case HEALTH: { double hp = player.getCurrentHealth(); double maxHp = player.getMaxHealth() + modifiers.getHealth(); double heal = maxHp * (Config.POTION_HEALTH_RESTORE + modifiers.getPotionHealth()); hp = hp + heal > maxHp ? maxHp : hp + heal; // Update player player.setCurrentHealth(hp); player.addHealthPotions(-1); // Update return result.addPlayerHealthChanges(heal); result.addReturn(Return.HEALTH_RESTORED); break; } case MANA: { double mp = player.getCurrentMana(); double maxMp = player.getMaxMana()+ modifiers.getMana(); double heal = maxMp * (Config.POTION_MANA_RESTORE + modifiers.getPotionMana()); mp = mp + heal > maxMp ? maxMp : mp + heal; // Update player player.setCurrentMana(mp); player.addManaPotions(-1); // Update return result.addPlayerManaChanges(heal); result.addReturn(Return.MANA_RESTORED); break; } case REMEDY: { Status status = player.getStatus(); // Update player player.setStatus(Status.NORMAL); player.setStatusDuration(0l); player.addRemedyPotions(-1); // Update return switch (status) { case PARALYZED: result.addReturn(Return.PLAYER_PARALYSIS_CURED); break; case POISONED: result.addReturn(Return.PLAYER_POISON_CURED); break; } break; } } // Update and save player player.setLastAction(Calendar.getInstance()); this.updateAndReturn(result, player, true, false); // Return result.setSuccess(true); if (Config.PERSISTANCE) { DAO.<Result>addObject(result); } return result; } /** * Start an activity * @param sender Player's nickname * @param activityname Activity name * @return Result */ public Result startActivity(String sender, String activityname) { Result result = new Result(Action.START_ACTIVITY); // Get the player Player player = this.getPlayer(result, sender); if (player == null) return result; // Get activity Activity activity = Activity.from(activityname); // Update player this.updateAndReturn(result, player, false, false); // Check player if (!Helpers.checkPlayer(result, player, CheckPlayer.from( CheckPlayer.IS_DEAD, CheckPlayer.IS_PARALYZED, CheckPlayer.HAS_ACTED ) )) return result; // Check the activity penalty if (player.getActivity() == Activity.WAITING) { Time time = new Time((Config.ACTIVITY_PENALTY * Config.MINUTE) - player.getActivityDuration()); result.setDetails(time.toString()); result.addReturn(Return.PLAYER_IS_WAITING); return result; } // Check the activity of the player if (player.getActivity() != Activity.NONE) { result.addReturn(Return.PLAYER_BUSY); return result; } // Set player activity player.setActivity(activity); player.setActivityDuration(0l); // Update and save player player.setLastAction(Calendar.getInstance()); this.updateAndReturn(result, player, true, false); // Return switch (activity) { case RESTING: result.addReturn(Return.START_RESTING); break; case TRAINING: result.addReturn(Return.START_TRAINING); break; case WORKING: result.addReturn(Return.START_WORKING); break; } result.setSuccess(true); return result; } /** * End the current player activity * @param sender Player's nickname * @return Result */ public Result endActivity(String sender) { Result result = new Result(Action.END_ACTIVITY); // Get the player Player player = this.getPlayer(result, sender); if (player == null) return result; // Update player this.updateAndReturn(result, player, false, false); // Player modifiers Modifiers modifiers = new Modifiers(player); // Earned double earned = player.getActivityDuration() * 1d / Config.HOUR; // Activity check switch (player.getActivity()) { case NONE: case WAITING: { result.addReturn(Return.PLAYER_NOT_BUSY); return result; } case RESTING: { if (player.getActivityDuration() < Config.RESTING_TIME_MIN) { result.addReturn(Return.NOT_RESTED_ENOUGH); return result; } result.addReturn(Return.PLAYER_RESTING_ENDED); earned *= Config.RATE_HEALTH + modifiers.getHealthRate(); break; } case WORKING: { if (player.getActivityDuration() < Config.WORKING_TIME_MIN) { result.addReturn(Return.NOT_WORKED_ENOUGH); return result; } result.addReturn(Return.PLAYER_WORKING_ENDED); earned *= Config.RATE_GOLD + modifiers.getGoldRate(); break; } case TRAINING: { if (player.getActivityDuration() < Config.TRAINING_TIME_MIN) { result.addReturn(Return.NOT_TRAINED_ENOUGH); return result; } result.addReturn(Return.PLAYER_TRAINING_ENDED); earned *= Config.RATE_EXPERIENCE + modifiers.getExperienceRate(); break; } } // Clear activity player.setActivity(Activity.WAITING); player.setActivityDuration(0l); // Update and save player player.setLastAction(Calendar.getInstance()); this.updateAndReturn(result, player, true, false); // Return result.setValue(earned); result.setSuccess(true); return result; } /** * Upgrade a player * @param sender Player's nickname * @param skillname Skill name to raise * @return Result */ public Result upgrade(String sender, String skillname) { Result result = new Result(Action.UPGRADE); // Get the player Player player = this.getPlayer(result, sender); if (player == null) return result; // Get the statistic Skill skill = Skill.from(skillname); // Check skill if (skill == Skill.NONE) { result.addReturn(Return.UNKNOWN_SKILL); return result; } // Update player this.updateAndReturn(result, player, false, false); // Check player if (!Helpers.checkPlayer(result, player, CheckPlayer.from( CheckPlayer.IS_BUSY, CheckPlayer.IS_DEAD, CheckPlayer.IS_PARALYZED, CheckPlayer.HAS_ACTED ) )) return result; // Check player skill points if (player.getSkillPoints() < 1) { result.addReturn(Return.NOT_ENOUGH_SKILL_POINTS); return result; } // Rising stats switch (skill) { case HEALTH: { player.addMaxHealth(Config.SKILL_HEALTH); player.addHealth(Config.SKILL_HEALTH); result.addReturn(Return.HEALTH_INCREASED); result.setValue(Config.SKILL_HEALTH); break; } case MANA: { player.addMaxMana(Config.SKILL_MANA); player.addMana(Config.SKILL_MANA); result.addReturn(Return.MANA_INCREASED); result.setValue(Config.SKILL_MANA); break; } case ATTACK: { player.addAttack(Config.SKILL_ATTACK); result.addReturn(Return.ATTACK_INCREASED); result.setValue(Config.SKILL_ATTACK); break; } case DEFENSE: { player.addDefense(Config.SKILL_DEFENSE); result.addReturn(Return.DEFENSE_INCREASED); result.setValue(Config.SKILL_DEFENSE); break; } } // Decrease skill points player.addSkillPoints(-1); // Update and save player player.setLastAction(Calendar.getInstance()); this.updateAndReturn(result, player, true, false); // Return result.setSuccess(true); return result; } /** * Buy an item in the shop * @param sender Player's nickname * @param code Item's code * @return Result */ public Result buy(String sender, String code) { Result result = new Result(Action.BUY); // Get the player Player player = this.getPlayer(result, sender); if (player == null) return result; // Check if item is potion Potion potion = Potion.from(code.toLowerCase()); // Check item Item item = null; if (potion == Potion.NONE) { item = this.getItemByCode(code.toLowerCase()); if (!Helpers.checkItem(result, player, item, CheckItem.from( CheckItem.CAN_BE_AFFORDED, CheckItem.CAN_BE_WORN, CheckItem.HAS_ENOUGH_STOCK, CheckItem.IS_ADMIN_ONLY, CheckItem.IS_ALREADY_BOUGHT, CheckItem.TYPE_ALREADY_EQUIPPED ) )) return result; } // Check player if (!Helpers.checkPlayer(result, player, CheckPlayer.from( CheckPlayer.IS_BUSY, CheckPlayer.IS_DEAD, CheckPlayer.IS_PARALYZED, CheckPlayer.HAS_ACTED ) )) return result; // Item if (item != null) { // Decrease stock item.addStock(-1); if (Config.PERSISTANCE) { if (!DAO.<Item>setObject(item)) { result.addReturn(Return.PERSISTANCE_ERROR); return result; } } // Add item in player's inventory player.addItem(item); player.addGold(-item.getGoldCost()); result.addReturn(Return.ITEM_SUCCESSFULLY_BOUGHT); result.setDetails(item.getName()); // Increase current health if (item.getHealthModifier() > 0) { player.addHealth(item.getHealthModifier()); } // Increase current mana if (item.getManaModifier() > 0) { player.addMana(item.getManaModifier()); } // Update return result.addPlayerGoldChanges(-item.getGoldCost()); // Update statistics player.addMoneySpent(item.getGoldCost()); // Potion } else { // Check potion price if (!Helpers.checkPotion(result, player, potion, CheckPotion.from( CheckPotion.CAN_BE_AFFORDED ) )) return result; // Potion type switch (potion) { case HEALTH: { player.addHealthPotions(1); player.addGold(-Config.POTION_HEALTH_COST); // Update return result.addPlayerGoldChanges(-Config.POTION_HEALTH_COST); // Update statistics player.addMoneySpent(Config.POTION_HEALTH_COST); break; } case MANA: { player.addManaPotions(1); player.addGold(-Config.POTION_MANA_COST); // Update return result.addPlayerGoldChanges(-Config.POTION_MANA_COST); // Update statistics player.addMoneySpent(Config.POTION_MANA_COST); break; } case REMEDY: { player.addRemedyPotions(1); player.addGold(-Config.POTION_REMEDY_COST); // Update return result.addPlayerGoldChanges(-Config.POTION_REMEDY_COST); // Update statistics player.addMoneySpent(Config.POTION_REMEDY_COST); break; } } result.addReturn(Return.POTION_SUCCESSFULLY_BOUGHT); result.setDetails(potion.toString()); } // Update and save player player.setLastAction(Calendar.getInstance()); this.updateAndReturn(result, player, true, false); // Return result.setSuccess(true); return result; } /** * Sell an item * @param sender Player's nickname * @param code Item's code * @return result */ public Result sell(String sender, String code) { Result result = new Result(Action.SELL); // Get the player Player player = this.getPlayer(result, sender); if (player == null) return result; // Check item Item item = this.getItemByCode(code.toLowerCase()); if (!Helpers.checkItem(result, player, item, CheckItem.from( CheckItem.IS_ALREADY_BOUGHT ) )) return result; // Increase stock item.addStock(1); if (Config.PERSISTANCE) { if (!DAO.<Item>setObject(item)) { result.addReturn(Return.PERSISTANCE_ERROR); return result; } } // Sell item player.removeItem(item); player.addGold(item.getGoldCost() * Config.SELL_MALUS); result.addReturn(Return.ITEM_SUCCESSFULLY_SOLD); result.setDetails(item.getName()); // Update and save player player.setLastAction(Calendar.getInstance()); this.updateAndReturn(result, player, true, false); // Return result.setSuccess(true); return result; } /** * Learn a spell * @param sender Player's nickname * @param code Spell's code * @return Result */ public Result learn(String sender, String code) { Result result = new Result(Action.LEARN); // Get the player Player player = this.getPlayer(result, sender); if (player == null) return result; // Check spell Spell spell = this.getSpellByCode(code.toLowerCase()); if (!Helpers.checkSpell(result, player, spell, CheckSpell.from( CheckSpell.CAN_BE_AFFORDED, CheckSpell.IS_ADMIN_ONLY, CheckSpell.IS_ALREADY_LEARNED, CheckSpell.CAN_BE_LEARNED ) )) return result; // Check player if (!Helpers.checkPlayer(result, player, CheckPlayer.from( CheckPlayer.IS_BUSY, CheckPlayer.IS_DEAD, CheckPlayer.IS_PARALYZED, CheckPlayer.HAS_ACTED ) )) return result; // Add item in player's inventory player.addSpell(spell); player.addGold(-spell.getGoldCost()); result.setDetails(spell.getName()); // Update return result.addPlayerGoldChanges(-spell.getGoldCost()); result.addReturn(Return.SPELL_SUCCESSFULLY_LEARNED); // Update statistics player.addMoneySpent(spell.getGoldCost()); // Update and save player player.setLastAction(Calendar.getInstance()); this.updateAndReturn(result, player, true, false); // Return result.setSuccess(true); return result; } /** * Show information about item or spell * @param code Item or spell code * @return Formated string */ public String look(String code) { // Potion Potion potion = Potion.from(code.toLowerCase()); switch (potion) { case HEALTH: return String.format(Strings.FORMAT_POTION_HEALTH, Potion.HEALTH, Config.POTION_HEALTH_RESTORE * 100, Config.POTION_HEALTH_COST); case MANA: return String.format(Strings.FORMAT_POTION_MANA, Potion.MANA, Config.POTION_MANA_RESTORE * 100, Config.POTION_MANA_COST); case REMEDY: return String.format(Strings.FORMAT_POTION_REMEDY, Potion.REMEDY, Config.POTION_REMEDY_COST); } // Item Item item = this.getItemByCode(code.toLowerCase()); if (item != null) { return Strings.format(Strings.FORMAT_ITEM_INFOS, item.toMap()); } // Spell Spell spell = this.getSpellByCode(code.toLowerCase()); if (spell != null) { return Strings.format(Strings.FORMAT_SPELL_INFOS, spell.toMap()); } return null; } /** * Show player's all items * @param nickname Player's nickname * @return Formatted string */ public String showItems(String nickname) { Player player = this.getPlayerByNickname(nickname); if (player == null || !player.getOnline()) return null; // Update player this.update(player, false, false); // Build list of items List<String> items = new ArrayList<>(); for (Item item : player.getItems()) { items.add(Strings.format(Strings.FORMAT_ITEM_NAME, item.toMap())); } // Return data if (items.isEmpty()) items.add(Strings.FORMAT_NONE); String string = String.format(Strings.FORMAT_PLAYER_ITEMS, Strings.join(items, ", ")); return Strings.format(string, player.toMap()); } /** * Show player's all spells * @param nickname Player's nickname * @return Formatted string */ public String showSpells(String nickname) { Player player = this.getPlayerByNickname(nickname); if (player == null || !player.getOnline()) return null; // Update player this.update(player, false, false); // Build list of spells List<String> spells = new ArrayList<>(); for (Spell spell : player.getSpells()) { spells.add(Strings.format(Strings.FORMAT_SPELL_NAME, spell.toMap())); } // Return data if (spells.isEmpty()) spells.add(Strings.FORMAT_NONE); String string = String.format(Strings.FORMAT_PLAYER_SPELLS, Strings.join(spells, ", ")); return Strings.format(string, player.toMap()); } /** * Show player's informations * @param nickname Player's nickname * @return Formatted string */ public String showInfos(String nickname) { Player player = this.getPlayerByNickname(nickname); if (player == null || !player.getOnline()) return null; // Update player this.update(player, false, false); // Return data return Strings.format(Strings.FORMAT_PLAYER_INFOS, player.toMap()); } /** * Show player's statistics * @param nickname Player's nickname * @return Formatted string */ public String showStats(String nickname) { Player player = this.getPlayerByNickname(nickname); if (player == null || !player.getOnline()) return null; // Update player this.update(player, false, false); // Return data return Strings.format(Strings.FORMAT_PLAYER_STATS, player.toMap()); } /** * Show items the player can afford * @param nickname Player's nickname * @return Formatted string */ public String showItemsToBuy(String nickname) { Player player = this.getPlayerByNickname(nickname); if (player == null || !player.getOnline()) return null; // Update player this.update(player, false, false); // Get items which can be bought List<String> items = new ArrayList<>(); for (Map.Entry<String, Item> entry : this.itemsByCode.entrySet()) { Item item = entry.getValue(); // Check item conditions boolean admin = !item.getIsAdmin() || (item.getIsAdmin() && player.getAdmin()); boolean level = item.getMinLevel() <= player.getLevel(); boolean money = item.getGoldCost() <= player.getGold(); boolean stock = item.getStock() > 0; boolean owned = !player.getItems().contains(item); // Add item to list if (admin && level && money && stock && owned) { String string = Strings.format(Strings.FORMAT_ITEM_NAME, item.toMap()); items.add(string); } } // Return data if (items.isEmpty()) items.add(Strings.FORMAT_NONE); String string = String.format(Strings.FORMAT_SHOP_ITEMS, Strings.join(items, ", ")); return Strings.format(string, player.toMap()); } /** * Show spells the player can learn * @param nickname Player's nickname * @return Formatted string */ public String showSpellsToLearn(String nickname) { Player player = this.getPlayerByNickname(nickname); if (player == null || !player.getOnline()) return null; // Update player this.update(player, false, false); // Get items which can be bought List<String> spells = new ArrayList<>(); for (Map.Entry<String, Spell> entry : this.spellsByCode.entrySet()) { Spell spell = entry.getValue(); // Check item conditions boolean admin = !spell.getIsAdmin() || (spell.getIsAdmin() && player.getAdmin()); boolean level = spell.getMinLevel() <= player.getLevel(); boolean money = spell.getGoldCost() <= player.getGold(); boolean magic = spell.getManaCost() <= player.getMaxMana(); boolean owned = !player.getSpells().contains(spell); // Add item to list if (admin && level && money && magic && owned) { String string = Strings.format(Strings.FORMAT_ITEM_NAME, spell.toMap()); spells.add(string); } } // Return data if (spells.isEmpty()) spells.add(Strings.FORMAT_NONE); String string = String.format(Strings.FORMAT_SHOP_SPELLS, Strings.join(spells, ", ")); return Strings.format(string, player.toMap()); } /** * Show the list of online players * @return Formatted string */ public String showPlayers() { int count = 0; List<String> players = new ArrayList<>(); for (Map.Entry<String, Player> entry : this.playersByNickname.entrySet()) { if (entry.getValue().getOnline()) { players.add(entry.getValue().getNickname()); count++; } } if (players.isEmpty()) players.add(Strings.FORMAT_NONE); return String.format(Strings.FORMAT_LIST_PLAYERS, count, Strings.join(players, ", ")); } /** * Log in a player * @param username Player's username * @param password Player's password * @param nickname Player's nickname * @param hostname Player's hostname * @return Result */ public Result login(String username, String password, String nickname, String hostname) { Result result = new Result(Action.LOGIN); result.setDetails(username); Player player = this.getPlayerByUsername(username); if (player != null) { if (!player.getOnline()) { if (player.getPassword().equals(password)) { // Clean player references this.playersByNickname.remove(player.getNickname()); this.playersByNickname.remove(nickname.toLowerCase()); this.playersByNickname.put(nickname.toLowerCase(), player); // Update player player.setNickname(nickname); player.setHostname(hostname); player.setOnline(true); player.setLastUpdate(Calendar.getInstance()); this.updateAndReturn(result, player, true, false); // Return result result.setPlayer(player); result.addReturn(Return.LOGIN_SUCCEED); result.setSuccess(true); } else result.addReturn(Return.WRONG_PASSWORD); } else result.addReturn(Return.ALREADY_ONLINE); } else result.addReturn(Return.USERNAME_NOT_FOUND); return result; } /** * Try to identify a player from his nickname and hostname only * If fail, the player must use the login function to proceed * @param nickname Player's nickname * @param hostname Player's hostname * @return Result */ public Result tryRelogin(String nickname, String hostname) { Result result = new Result(Action.LOGIN); result.setDetails(nickname); Player player = this.getPlayerByNickname(nickname); if (player != null && !player.getOnline()) { if (hostname.equals(player.getHostname())) { // Update player player.setOnline(true); player.setLastUpdate(Calendar.getInstance()); this.updateAndReturn(result, player, true, false); // Return result result.setPlayer(player); result.addReturn(Return.LOGIN_SUCCEED); result.setSuccess(true); } } return result; } /** * Log out a player * @param nickname Player's nickname * @return Result */ public Result logout(String nickname) { Result result = new Result(Action.LOGOUT); result.setDetails(nickname); Player player = this.getPlayerByNickname(nickname); if (player != null) { // Update player player.setOnline(false); this.updateAndReturn(result, player, true, false); // Return result result.setPlayer(player); result.addReturn(Return.LOGOUT_SUCCEED); result.setSuccess(true); } else result.addReturn(Return.NOT_ONLINE); return result; } /** * Change the player's nickname * @param oldNickname Old nickname * @param newNickname New nickname * @return True if success, false else */ public boolean changeNickname(String oldNickname, String newNickname) { Player player = this.getPlayerByNickname(oldNickname); if (player != null) { player.setNickname(newNickname); this.playersByNickname.remove(oldNickname.toLowerCase()); this.playersByNickname.put(newNickname.toLowerCase(), player); return true; } return false; } /** * Change the player's password * @param nickname Player's nickname * @param password New password * @return True if success, false else */ public boolean changePassword(String nickname, String password) { Player player = this.getPlayerByNickname(nickname); if (player != null) { player.setPassword(password); return true; } return false; } /** * Disconnect all players */ public void disconnectAll() { for (Map.Entry<String, Player> entry : this.playersByNickname.entrySet()) { Player player = entry.getValue(); player.setOnline(false); this.update(player, true, false); } } /** * Register a new player * @param username Username * @param password Password * @param nickname Nickname * @param hostname Hostname * @return Result */ public Result register(String username, String password, String nickname, String hostname) { Result result = new Result(Action.REGISTER); if (!this.playersByUsername.containsKey(username.toLowerCase())) { if (!this.playersByNickname.containsKey(nickname.toLowerCase())) { Player player = new Player(); player.setUsername(username); player.setPassword(password); player.setNickname(nickname); player.setHostname(hostname); player.setOnline(true); player.setAdmin(this.playersByNickname.isEmpty()); if (Config.PERSISTANCE) { if (DAO.<Player>addObject(player) == 0) { result.addReturn(Return.PERSISTANCE_ERROR); return result; } } this.playersByUsername.put(username.toLowerCase(), player); this.playersByNickname.put(nickname.toLowerCase(), player); result.setPlayer(player); result.addReturn(Return.REGISTER_SUCCEED); result.setSuccess(true); } else result.addReturn(Return.NICKNAME_IN_USE); } else result.addReturn(Return.USERNAME_ALREADY_TAKEN); return result; } /** * Get and check player * @see #getPlayer(fr.debnet.ircrpg.game.Result, java.lang.String) * @param result [out] Result * @param name Player's nickname * @return Player if found and online, null else */ private Player getPlayer(Result result, String name) { return this.getPlayer(result, name, false); } /** * Get and check player * @param result [out] Result * @param name Player's nickname * @param target Is target ? * @return Player if found and online, null else */ private Player getPlayer(Result result, String name, boolean target) { result.setDetails(name); // Check if the player exists Player player = this.getPlayerByNickname(name); if (player == null) { result.addReturn(target ? Return.UNKNOWN_TARGET : Return.UNKNOWN_PLAYER); result.setDetails(name); return null; } // Add player if (target) result.setTarget(player); else result.setPlayer(player); // Check if the player is logged in if (!player.getOnline()) { result.addReturn(target ? Return.TARGET_OFFLINE : Return.PLAYER_OFFLINE); return null; } return player; } /** * Get random generator * @return Random generator (mocked) */ protected Random getRandom() { return this.random; } /** * Explicitly add an item in the list * @param item Item instance * @return True if the item is successfully added, false sinon */ protected boolean addItem(Item item) { if (!this.itemsByCode.containsKey(item.getCode())) { this.itemsByCode.put(item.getCode(), item); if (Config.PERSISTANCE) { return DAO.<Item>addObject(item) != 0; } return true; } return false; } /** * Explicitly add a spell in the list * @param spell Spell instance * @return True if the spell is successfully added, false sinon */ protected boolean addSpell(Spell spell) { if (!this.spellsByCode.containsKey(spell.getCode())) { this.spellsByCode.put(spell.getCode(), spell); if (Config.PERSISTANCE) { return DAO.<Spell>addObject(spell) != 0; } return true; } return false; } }
true
true
public Result fight(String sender, String target, String magic) { Result result = new Result(Action.FIGHT); boolean self = sender.equals(target); // Get attacker Player attacker = this.getPlayer(result, sender); if (attacker == null) return result; // Get defender Player defender; if (!self) { defender = this.getPlayer(result, target, true); if (defender == null) return result; } else { defender = attacker; result.setTarget(defender); } // Update players this.updateAndReturn(result, attacker, false, false); if (!self) this.updateAndReturn(result, defender, false, true); // Check attacker if (!Helpers.checkPlayer(result, attacker, CheckPlayer.from( CheckPlayer.IS_BUSY, CheckPlayer.IS_DEAD, CheckPlayer.IS_PARALYZED, CheckPlayer.HAS_ACTED ) )) return result; // Check defender if (!self && !Helpers.checkPlayer(result, defender, CheckPlayer.from( CheckPlayer.IS_BUSY, CheckPlayer.IS_DEAD, CheckPlayer.IS_PARALYZED, CheckPlayer.IS_TARGET ) )) return result; // Get spell Spell spell = null; if (magic != null) { spell = this.getSpellByCode(magic); if (spell == null) { // Update return result.addReturn(Return.UNKNOWN_SPELL); return result; } else if (!attacker.getSpells().contains(spell)) { // Update return result.addReturn(Return.SPELL_NOT_LEARNED); return result; } } // Items modifiers Modifiers attackerModifiers = new Modifiers(attacker); Modifiers defenderModifiers = new Modifiers(defender); // Attacker phase if (spell == null) { if (self) { // Update return result.addReturn(Return.NOT_SELF_ATTACK); return result; } // With no spell double accuracy = Config.ATTACK_ACCURACY + attackerModifiers.getAttackAccuracy(); double chance = random.nextDouble(); if (chance > accuracy) { // Update return result.addReturn(Return.ATTACK_FAILED); } else { // Update return result.addReturn(Return.ATTACK_SUCCEED); // Health change double damage = (attacker.getAttack() + attackerModifiers.getAttack()) * (1d - chance); defender.addHealth(-damage); // Update return result.addTargetHealthChanges(-damage); // Update statistics attacker.addDamageGiven(damage); defender.addDamageTaken(damage); // Is defender dead? if (defender.getCurrentHealth() <= 0) { defender.setStatus(Status.DEAD); defender.setStatusDuration(Config.DEATH_PENALTY * Config.MINUTE); defender.setCurrentHealth(0d); // Update return result.addReturn(Return.TARGET_KILLED); // Update statistics attacker.addKills(1); defender.addDeaths(1); // Gold looted double gold = (Config.THEFT_GOLD + attackerModifiers.getTheftGold()) * defender.getGold() * random.nextDouble(); // Update players attacker.addGold(gold); defender.addGold(-gold); // Update return result.addPlayerGoldChanges(gold); result.addTargetGoldChanges(-gold); // Update statistics attacker.addMoneyStolen(gold); } } // Experience gained (attacker) double bonus = 1 + (defender.getLevel() - attacker.getLevel()) * Config.EXPERIENCE_BONUS; bonus = bonus < 0 ? 0 : bonus; double xp = chance > accuracy ? Config.EXPERIENCE_DEFENSE : Config.EXPERIENCE_ATTACK * (bonus + attackerModifiers.getExperienceModifier()); attacker.addExperience(xp); // Update return result.addPlayerExperienceChanges(xp); // Defender phase if (defender.getStatus() != Status.DEAD) { if (defender.getStatus() == Status.PARALYZED) { // Update return result.addReturn(Return.NO_STRIKE_BACK); } else { accuracy = Config.DEFENSE_ACCURACY + defenderModifiers.getDefenseAccuracy(); chance = random.nextDouble(); if (chance > accuracy) { result.addReturn(Return.DEFENSE_FAILED); } else { // Update return result.addReturn(Return.DEFENSE_SUCCEED); // Health change double damage = (defender.getDefense() + defenderModifiers.getDefense()) * (1d - chance); attacker.addHealth(-damage); // Update return result.addPlayerHealthChanges(-damage); // Update statistics defender.addDamageGiven(damage); attacker.addDamageTaken(damage); // Is attacker dead? if (attacker.getCurrentHealth() <= 0) { attacker.setStatus(Status.DEAD); attacker.setStatusDuration(Config.DEATH_PENALTY * Config.MINUTE); attacker.setCurrentHealth(0d); // Update return result.addReturn(Return.PLAYER_KILLED); // Update statistics defender.addKills(1); attacker.addDeaths(1); // Gold looted double gold = (Config.THEFT_GOLD + defenderModifiers.getTheftGold()) * defender.getGold() * random.nextDouble(); // Update players defender.addGold(gold); attacker.addGold(-gold); // Update return result.addPlayerGoldChanges(-gold); result.addTargetGoldChanges(gold); // Update statistics defender.addMoneyStolen(gold); } // Experience gained (defenser) bonus = 1 + (attacker.getLevel() - defender.getLevel()) * Config.EXPERIENCE_BONUS; bonus = bonus < 0 ? 0 : bonus; xp = Config.EXPERIENCE_DEFENSE * (bonus + defenderModifiers.getExperienceModifier()); defender.addExperience(xp); // Update statistics result.addTargetExperienceChanges(xp); } } } } else { result.setAction(Action.MAGIC); result.setDetails(spell.getName()); // With spell if (self && !spell.getIsSelf()) { // Update return result.addReturn(Return.NOT_SELF_SPELL); return result; } if (attacker.getCurrentMana() < spell.getManaCost()) { // Update return result.addReturn(Return.NOT_ENOUGH_MANA); return result; } double accuracy = Config.MAGIC_ACCURACY + attackerModifiers.getMagicAccuracy(); if (random.nextDouble() > accuracy) { // Update return result.addReturn(Return.MAGIC_FAILED); } else { // Update return result.addReturn(Return.MAGIC_SUCCEED); // Health change double hp = defender.getCurrentHealth(); double maxHp = defender.getMaxHealth() + defenderModifiers.getHealth(); hp -= spell.getHealthDamage(); hp = hp > maxHp ? maxHp : hp < 0 ? 0 : hp; defender.setCurrentHealth(hp); // Update return result.addTargetHealthChanges(-spell.getHealthDamage()); // Update statistics if (spell.getHealthDamage() > 0) { attacker.addDamageGiven(spell.getHealthDamage()); defender.addDamageTaken(spell.getHealthDamage()); // Update return result.addReturn(Return.MAGIC_DAMAGE_HEALTH); } else if (spell.getHealthDamage() < 0) { // Update return result.addReturn(Return.MAGIC_RESTORE_HEALTH); } // Is defender dead? if (hp <= 0) { defender.setStatus(Status.DEAD); defender.setStatusDuration(Config.DEATH_PENALTY * Config.MINUTE); defender.setCurrentHealth(0d); // Update return result.addReturn(Return.TARGET_KILLED); // Update statistics attacker.addKills(1); defender.addDeaths(1); // Gold looted double gold = (Config.THEFT_GOLD + defenderModifiers.getTheftGold()) * defender.getGold() * random.nextDouble(); // Update players defender.addGold(gold); attacker.addGold(-gold); // Update return result.addPlayerGoldChanges(-gold); result.addTargetGoldChanges(gold); // Update statistics defender.addMoneyStolen(gold); } else { Status status = defender.getStatus(); // Status change if (spell.getStatus() != Status.NONE) { defender.setStatus(spell.getStatus()); defender.setStatusDuration(spell.getStatusDuration()); // Update return switch (spell.getStatus()) { case PARALYZED: { result.addReturn(Return.TARGET_PARALYZED); break; } case POISONED: { result.addReturn(Return.TARGET_POISONED); break; } case NORMAL: { switch (status) { case NORMAL: break; case PARALYZED: result.addReturn(Return.TARGET_PARALYSIS_CURED); break; case POISONED: result.addReturn(Return.TARGET_POISON_CURED); break; } break; } } } } // Experience earned (if offensive spell) if (!spell.getIsSelf()) { double bonus = 1 + (defender.getLevel() - attacker.getLevel()) * Config.EXPERIENCE_BONUS; bonus = bonus < 0 ? 0 : bonus; double xp = Config.EXPERIENCE_ATTACK * (bonus + attackerModifiers.getExperienceModifier()); attacker.addExperience(xp); // Update statistics result.addPlayerExperienceChanges(xp); } } // Mana consumption attacker.addMana(-spell.getManaCost()); // Update return result.addPlayerManaChanges(-spell.getManaCost()); } // Update and save players attacker.setLastAction(Calendar.getInstance()); this.updateAndReturn(result, attacker, true, false); if (!self) this.updateAndReturn(result, defender, true, true); // Return result.setSuccess(true); if (Config.PERSISTANCE) { DAO.<Result>addObject(result); } return result; }
public Result fight(String sender, String target, String magic) { Result result = new Result(Action.FIGHT); boolean self = sender.equals(target); // Get attacker Player attacker = this.getPlayer(result, sender); if (attacker == null) return result; // Get defender Player defender; if (!self) { defender = this.getPlayer(result, target, true); if (defender == null) return result; } else { defender = attacker; result.setTarget(defender); } // Update players this.updateAndReturn(result, attacker, false, false); if (!self) this.updateAndReturn(result, defender, false, true); // Check attacker if (!Helpers.checkPlayer(result, attacker, CheckPlayer.from( CheckPlayer.IS_BUSY, CheckPlayer.IS_DEAD, CheckPlayer.IS_PARALYZED, CheckPlayer.HAS_ACTED ) )) return result; // Check defender if (!self && !Helpers.checkPlayer(result, defender, CheckPlayer.from( CheckPlayer.IS_BUSY, CheckPlayer.IS_DEAD, CheckPlayer.IS_PARALYZED, CheckPlayer.IS_TARGET ) )) return result; // Get spell Spell spell = null; if (magic != null) { spell = this.getSpellByCode(magic); if (spell == null) { // Update return result.addReturn(Return.UNKNOWN_SPELL); return result; } else if (!attacker.getSpells().contains(spell)) { // Update return result.addReturn(Return.SPELL_NOT_LEARNED); return result; } } // Items modifiers Modifiers attackerModifiers = new Modifiers(attacker); Modifiers defenderModifiers = new Modifiers(defender); // Attacker phase if (spell == null) { if (self) { // Update return result.addReturn(Return.NOT_SELF_ATTACK); return result; } // With no spell double accuracy = Config.ATTACK_ACCURACY + attackerModifiers.getAttackAccuracy(); double chance = random.nextDouble(); if (chance > accuracy) { // Update return result.addReturn(Return.ATTACK_FAILED); } else { // Update return result.addReturn(Return.ATTACK_SUCCEED); // Health change double damage = (attacker.getAttack() + attackerModifiers.getAttack()) * (1d - chance); defender.addHealth(-damage); // Update return result.addTargetHealthChanges(-damage); // Update statistics attacker.addDamageGiven(damage); defender.addDamageTaken(damage); // Is defender dead? if (defender.getCurrentHealth() <= 0) { defender.setStatus(Status.DEAD); defender.setStatusDuration(Config.DEATH_PENALTY * Config.MINUTE); defender.setCurrentHealth(0d); // Update return result.addReturn(Return.TARGET_KILLED); // Update statistics attacker.addKills(1); defender.addDeaths(1); // Gold looted double gold = (Config.THEFT_GOLD + attackerModifiers.getTheftGold()) * defender.getGold() * random.nextDouble(); // Update players attacker.addGold(gold); defender.addGold(-gold); // Update return result.addPlayerGoldChanges(gold); result.addTargetGoldChanges(-gold); // Update statistics attacker.addMoneyStolen(gold); } } // Experience gained (attacker) double bonus = 1 + (defender.getLevel() - attacker.getLevel()) * Config.EXPERIENCE_BONUS; bonus = bonus < 0 ? 0 : bonus; double xp = (chance > accuracy ? Config.EXPERIENCE_DEFENSE : Config.EXPERIENCE_ATTACK) * (bonus + attackerModifiers.getExperienceModifier()); attacker.addExperience(xp); // Update return result.addPlayerExperienceChanges(xp); // Defender phase if (defender.getStatus() != Status.DEAD) { if (defender.getStatus() == Status.PARALYZED) { // Update return result.addReturn(Return.NO_STRIKE_BACK); } else { accuracy = Config.DEFENSE_ACCURACY + defenderModifiers.getDefenseAccuracy(); chance = random.nextDouble(); if (chance > accuracy) { result.addReturn(Return.DEFENSE_FAILED); } else { // Update return result.addReturn(Return.DEFENSE_SUCCEED); // Health change double damage = (defender.getDefense() + defenderModifiers.getDefense()) * (1d - chance); attacker.addHealth(-damage); // Update return result.addPlayerHealthChanges(-damage); // Update statistics defender.addDamageGiven(damage); attacker.addDamageTaken(damage); // Is attacker dead? if (attacker.getCurrentHealth() <= 0) { attacker.setStatus(Status.DEAD); attacker.setStatusDuration(Config.DEATH_PENALTY * Config.MINUTE); attacker.setCurrentHealth(0d); // Update return result.addReturn(Return.PLAYER_KILLED); // Update statistics defender.addKills(1); attacker.addDeaths(1); // Gold looted double gold = (Config.THEFT_GOLD + defenderModifiers.getTheftGold()) * defender.getGold() * random.nextDouble(); // Update players defender.addGold(gold); attacker.addGold(-gold); // Update return result.addPlayerGoldChanges(-gold); result.addTargetGoldChanges(gold); // Update statistics defender.addMoneyStolen(gold); } // Experience gained (defenser) bonus = 1 + (attacker.getLevel() - defender.getLevel()) * Config.EXPERIENCE_BONUS; bonus = bonus < 0 ? 0 : bonus; xp = Config.EXPERIENCE_DEFENSE * (bonus + defenderModifiers.getExperienceModifier()); defender.addExperience(xp); // Update statistics result.addTargetExperienceChanges(xp); } } } } else { result.setAction(Action.MAGIC); result.setDetails(spell.getName()); // With spell if (self && !spell.getIsSelf()) { // Update return result.addReturn(Return.NOT_SELF_SPELL); return result; } if (attacker.getCurrentMana() < spell.getManaCost()) { // Update return result.addReturn(Return.NOT_ENOUGH_MANA); return result; } double accuracy = Config.MAGIC_ACCURACY + attackerModifiers.getMagicAccuracy(); if (random.nextDouble() > accuracy) { // Update return result.addReturn(Return.MAGIC_FAILED); } else { // Update return result.addReturn(Return.MAGIC_SUCCEED); // Health change double hp = defender.getCurrentHealth(); double maxHp = defender.getMaxHealth() + defenderModifiers.getHealth(); hp -= spell.getHealthDamage(); hp = hp > maxHp ? maxHp : hp < 0 ? 0 : hp; defender.setCurrentHealth(hp); // Update return result.addTargetHealthChanges(-spell.getHealthDamage()); // Update statistics if (spell.getHealthDamage() > 0) { attacker.addDamageGiven(spell.getHealthDamage()); defender.addDamageTaken(spell.getHealthDamage()); // Update return result.addReturn(Return.MAGIC_DAMAGE_HEALTH); } else if (spell.getHealthDamage() < 0) { // Update return result.addReturn(Return.MAGIC_RESTORE_HEALTH); } // Is defender dead? if (hp <= 0) { defender.setStatus(Status.DEAD); defender.setStatusDuration(Config.DEATH_PENALTY * Config.MINUTE); defender.setCurrentHealth(0d); // Update return result.addReturn(Return.TARGET_KILLED); // Update statistics attacker.addKills(1); defender.addDeaths(1); // Gold looted double gold = (Config.THEFT_GOLD + defenderModifiers.getTheftGold()) * defender.getGold() * random.nextDouble(); // Update players defender.addGold(gold); attacker.addGold(-gold); // Update return result.addPlayerGoldChanges(-gold); result.addTargetGoldChanges(gold); // Update statistics defender.addMoneyStolen(gold); } else { Status status = defender.getStatus(); // Status change if (spell.getStatus() != Status.NONE) { defender.setStatus(spell.getStatus()); defender.setStatusDuration(spell.getStatusDuration()); // Update return switch (spell.getStatus()) { case PARALYZED: { result.addReturn(Return.TARGET_PARALYZED); break; } case POISONED: { result.addReturn(Return.TARGET_POISONED); break; } case NORMAL: { switch (status) { case NORMAL: break; case PARALYZED: result.addReturn(Return.TARGET_PARALYSIS_CURED); break; case POISONED: result.addReturn(Return.TARGET_POISON_CURED); break; } break; } } } } // Experience earned (if offensive spell) if (!spell.getIsSelf()) { double bonus = 1 + (defender.getLevel() - attacker.getLevel()) * Config.EXPERIENCE_BONUS; bonus = bonus < 0 ? 0 : bonus; double xp = Config.EXPERIENCE_ATTACK * (bonus + attackerModifiers.getExperienceModifier()); attacker.addExperience(xp); // Update statistics result.addPlayerExperienceChanges(xp); } } // Mana consumption attacker.addMana(-spell.getManaCost()); // Update return result.addPlayerManaChanges(-spell.getManaCost()); } // Update and save players attacker.setLastAction(Calendar.getInstance()); this.updateAndReturn(result, attacker, true, false); if (!self) this.updateAndReturn(result, defender, true, true); // Return result.setSuccess(true); if (Config.PERSISTANCE) { DAO.<Result>addObject(result); } return result; }
diff --git a/src/org/jruby/RubyArray.java b/src/org/jruby/RubyArray.java index 564ea659f..93758e208 100644 --- a/src/org/jruby/RubyArray.java +++ b/src/org/jruby/RubyArray.java @@ -1,2748 +1,2756 @@ /* **** BEGIN LICENSE BLOCK ***** * Version: CPL 1.0/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Common Public * License Version 1.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.eclipse.org/legal/cpl-v10.html * * Software distributed under the License is distributed on an "AS * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or * implied. See the License for the specific language governing * rights and limitations under the License. * * Copyright (C) 2001 Alan Moore <[email protected]> * Copyright (C) 2001 Chad Fowler <[email protected]> * Copyright (C) 2001-2002 Benoit Cerrina <[email protected]> * Copyright (C) 2001-2004 Jan Arne Petersen <[email protected]> * Copyright (C) 2002-2004 Anders Bengtsson <[email protected]> * Copyright (C) 2002-2005 Thomas E Enebo <[email protected]> * Copyright (C) 2004-2005 Charles O Nutter <[email protected]> * Copyright (C) 2004 Stefan Matthias Aust <[email protected]> * Copyright (C) 2006 Ola Bini <[email protected]> * Copyright (C) 2006 Daniel Steer <[email protected]> * * Alternatively, the contents of this file may be used under the terms of * either of the GNU General Public License Version 2 or later (the "GPL"), * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the CPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the CPL, the GPL or the LGPL. ***** END LICENSE BLOCK *****/ package org.jruby; import java.lang.reflect.Array; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import org.jruby.anno.JRubyMethod; import org.jruby.anno.JRubyClass; import org.jruby.common.IRubyWarnings.ID; import org.jruby.javasupport.JavaUtil; import org.jruby.runtime.Arity; import org.jruby.runtime.Block; import org.jruby.runtime.ClassIndex; import org.jruby.runtime.MethodIndex; import org.jruby.runtime.ObjectAllocator; import org.jruby.runtime.ThreadContext; import org.jruby.runtime.Visibility; import org.jruby.runtime.builtin.IRubyObject; import org.jruby.runtime.marshal.MarshalStream; import org.jruby.runtime.marshal.UnmarshalStream; import org.jruby.util.ByteList; import org.jruby.util.Pack; /** * The implementation of the built-in class Array in Ruby. * * Concurrency: no synchronization is required among readers, but * all users must synchronize externally with writers. * */ @JRubyClass(name="Array") public class RubyArray extends RubyObject implements List { public static RubyClass createArrayClass(Ruby runtime) { RubyClass arrayc = runtime.defineClass("Array", runtime.getObject(), ARRAY_ALLOCATOR); runtime.setArray(arrayc); arrayc.index = ClassIndex.ARRAY; arrayc.kindOf = new RubyModule.KindOf() { @Override public boolean isKindOf(IRubyObject obj, RubyModule type) { return obj instanceof RubyArray; } }; arrayc.includeModule(runtime.getEnumerable()); arrayc.defineAnnotatedMethods(RubyArray.class); return arrayc; } private static ObjectAllocator ARRAY_ALLOCATOR = new ObjectAllocator() { public IRubyObject allocate(Ruby runtime, RubyClass klass) { return new RubyArray(runtime, klass); } }; @Override public int getNativeTypeIndex() { return ClassIndex.ARRAY; } private final void concurrentModification() { // noop for the moment } /** rb_ary_s_create * */ @JRubyMethod(name = "[]", rest = true, frame = true, meta = true) public static IRubyObject create(IRubyObject klass, IRubyObject[] args, Block block) { RubyArray arr = (RubyArray) ((RubyClass) klass).allocate(); arr.callInit(IRubyObject.NULL_ARRAY, block); if (args.length > 0) { arr.alloc(args.length); System.arraycopy(args, 0, arr.values, 0, args.length); arr.realLength = args.length; } return arr; } /** rb_ary_new2 * */ public static final RubyArray newArray(final Ruby runtime, final long len) { return new RubyArray(runtime, len); } public static final RubyArray newArrayLight(final Ruby runtime, final long len) { return new RubyArray(runtime, len, false); } /** rb_ary_new * */ public static final RubyArray newArray(final Ruby runtime) { return new RubyArray(runtime, ARRAY_DEFAULT_SIZE); } /** rb_ary_new * */ public static final RubyArray newArrayLight(final Ruby runtime) { /* Ruby arrays default to holding 16 elements, so we create an * ArrayList of the same size if we're not told otherwise */ RubyArray arr = new RubyArray(runtime, false); arr.alloc(ARRAY_DEFAULT_SIZE); return arr; } public static RubyArray newArray(Ruby runtime, IRubyObject obj) { return new RubyArray(runtime, new IRubyObject[] { obj }); } public static RubyArray newArrayLight(Ruby runtime, IRubyObject obj) { return new RubyArray(runtime, new IRubyObject[] { obj }, false); } /** rb_assoc_new * */ public static RubyArray newArray(Ruby runtime, IRubyObject car, IRubyObject cdr) { return new RubyArray(runtime, new IRubyObject[] { car, cdr }); } public static RubyArray newEmptyArray(Ruby runtime) { return new RubyArray(runtime, NULL_ARRAY); } /** rb_ary_new4, rb_ary_new3 * */ public static RubyArray newArray(Ruby runtime, IRubyObject[] args) { RubyArray arr = new RubyArray(runtime, args.length); System.arraycopy(args, 0, arr.values, 0, args.length); arr.realLength = args.length; return arr; } public static RubyArray newArrayNoCopy(Ruby runtime, IRubyObject[] args) { return new RubyArray(runtime, args); } public static RubyArray newArrayNoCopy(Ruby runtime, IRubyObject[] args, int begin) { return new RubyArray(runtime, args, begin); } public static RubyArray newArrayNoCopyLight(Ruby runtime, IRubyObject[] args) { RubyArray arr = new RubyArray(runtime, false); arr.values = args; arr.realLength = args.length; return arr; } public static RubyArray newArray(Ruby runtime, Collection collection) { RubyArray arr = new RubyArray(runtime, collection.size()); collection.toArray(arr.values); arr.realLength = arr.values.length; return arr; } public static final int ARRAY_DEFAULT_SIZE = 16; // volatile to ensure that initial nil-fill is visible to other threads private volatile IRubyObject[] values; private static final int TMPLOCK_ARR_F = 1 << 9; private static final int TMPLOCK_OR_FROZEN_ARR_F = TMPLOCK_ARR_F | FROZEN_F; private volatile boolean isShared = false; private int begin = 0; private int realLength = 0; /* * plain internal array assignment */ private RubyArray(Ruby runtime, IRubyObject[] vals) { super(runtime, runtime.getArray()); values = vals; realLength = vals.length; } /* * plain internal array assignment */ private RubyArray(Ruby runtime, IRubyObject[] vals, boolean objectSpace) { super(runtime, runtime.getArray(), objectSpace); values = vals; realLength = vals.length; } /* * plain internal array assignment */ private RubyArray(Ruby runtime, IRubyObject[] vals, int begin) { super(runtime, runtime.getArray()); this.values = vals; this.begin = begin; this.realLength = vals.length - begin; this.isShared = true; } /* rb_ary_new2 * just allocates the internal array */ private RubyArray(Ruby runtime, long length) { super(runtime, runtime.getArray()); checkLength(length); alloc((int) length); } private RubyArray(Ruby runtime, long length, boolean objectspace) { super(runtime, runtime.getArray(), objectspace); checkLength(length); alloc((int)length); } /* rb_ary_new3, rb_ary_new4 * allocates the internal array of size length and copies the 'length' elements */ public RubyArray(Ruby runtime, long length, IRubyObject[] vals) { super(runtime, runtime.getArray()); checkLength(length); int ilength = (int) length; alloc(ilength); if (ilength > 0 && vals.length > 0) System.arraycopy(vals, 0, values, 0, ilength); realLength = ilength; } /* NEWOBJ and OBJSETUP equivalent * fastest one, for shared arrays, optional objectspace */ private RubyArray(Ruby runtime, boolean objectSpace) { super(runtime, runtime.getArray(), objectSpace); } private RubyArray(Ruby runtime) { super(runtime, runtime.getArray()); alloc(ARRAY_DEFAULT_SIZE); } public RubyArray(Ruby runtime, RubyClass klass) { super(runtime, klass); alloc(ARRAY_DEFAULT_SIZE); } /* Array constructors taking the MetaClass to fulfil MRI Array subclass behaviour * */ private RubyArray(Ruby runtime, RubyClass klass, int length) { super(runtime, klass); alloc(length); } private RubyArray(Ruby runtime, RubyClass klass, long length) { super(runtime, klass); checkLength(length); alloc((int)length); } private RubyArray(Ruby runtime, RubyClass klass, long length, boolean objectspace) { super(runtime, klass, objectspace); checkLength(length); alloc((int)length); } private RubyArray(Ruby runtime, RubyClass klass, boolean objectSpace) { super(runtime, klass, objectSpace); } private RubyArray(Ruby runtime, RubyClass klass, RubyArray original) { super(runtime, klass); realLength = original.realLength; alloc(realLength); try { System.arraycopy(original.values, original.begin, values, 0, realLength); } catch (ArrayIndexOutOfBoundsException e) { concurrentModification(); } } private final IRubyObject[] reserve(int length) { final IRubyObject[] arr = new IRubyObject[length]; Arrays.fill(arr, getRuntime().getNil()); return arr; } private final void alloc(int length) { final IRubyObject[] newValues = new IRubyObject[length]; Arrays.fill(newValues, getRuntime().getNil()); values = newValues; } private final void realloc(int newLength) { IRubyObject[] reallocated = new IRubyObject[newLength]; Arrays.fill(reallocated, getRuntime().getNil()); try { System.arraycopy(values, 0, reallocated, 0, newLength > realLength ? realLength : newLength); } catch (ArrayIndexOutOfBoundsException e) { concurrentModification(); } values = reallocated; } private final void checkLength(long length) { if (length < 0) { throw getRuntime().newArgumentError("negative array size (or size too big)"); } if (length >= Integer.MAX_VALUE) { throw getRuntime().newArgumentError("array size too big"); } } /** Getter for property list. * @return Value of property list. */ public List getList() { return Arrays.asList(toJavaArray()); } public int getLength() { return realLength; } public IRubyObject[] toJavaArray() { IRubyObject[] copy = reserve(realLength); try { System.arraycopy(values, begin, copy, 0, realLength); } catch (ArrayIndexOutOfBoundsException e) { concurrentModification(); } return copy; } public IRubyObject[] toJavaArrayUnsafe() { return !isShared ? values : toJavaArray(); } public IRubyObject[] toJavaArrayMaybeUnsafe() { return (!isShared && begin == 0 && values.length == realLength) ? values : toJavaArray(); } /** rb_ary_make_shared * */ private final RubyArray makeShared(int beg, int len, RubyClass klass) { return makeShared(beg, len, klass, klass.getRuntime().isObjectSpaceEnabled()); } /** rb_ary_make_shared * */ private final RubyArray makeShared(int beg, int len, RubyClass klass, boolean objectSpace) { RubyArray sharedArray = new RubyArray(getRuntime(), klass, objectSpace); isShared = true; sharedArray.values = values; sharedArray.isShared = true; sharedArray.begin = beg; sharedArray.realLength = len; return sharedArray; } /** rb_ary_modify_check * */ private final void modifyCheck() { if ((flags & TMPLOCK_OR_FROZEN_ARR_F) != 0) { if ((flags & FROZEN_F) != 0) throw getRuntime().newFrozenError("array"); if ((flags & TMPLOCK_ARR_F) != 0) throw getRuntime().newTypeError("can't modify array during iteration"); } if (!isTaint() && getRuntime().getSafeLevel() >= 4) { throw getRuntime().newSecurityError("Insecure: can't modify array"); } } /** rb_ary_modify * */ private final void modify() { modifyCheck(); if (isShared) { IRubyObject[] vals = reserve(realLength); isShared = false; try { System.arraycopy(values, begin, vals, 0, realLength); } catch (ArrayIndexOutOfBoundsException e) { concurrentModification(); } begin = 0; values = vals; } } /* ================ * Instance Methods * ================ */ /** rb_ary_initialize * */ @JRubyMethod(name = "initialize", required = 0, optional = 2, frame = true, visibility = Visibility.PRIVATE) public IRubyObject initialize(ThreadContext context, IRubyObject[] args, Block block) { int argc = args.length; Ruby runtime = getRuntime(); if (argc == 0) { modifyCheck(); realLength = 0; if (block.isGiven()) runtime.getWarnings().warn(ID.BLOCK_UNUSED, "given block not used"); return this; } if (argc == 1 && !(args[0] instanceof RubyFixnum)) { IRubyObject val = args[0].checkArrayType(); if (!val.isNil()) { replace(val); return this; } } long len = RubyNumeric.num2long(args[0]); if (len < 0) throw runtime.newArgumentError("negative array size"); if (len >= Integer.MAX_VALUE) throw runtime.newArgumentError("array size too big"); int ilen = (int) len; modify(); if (ilen > values.length) values = reserve(ilen); if (block.isGiven()) { if (argc == 2) { runtime.getWarnings().warn(ID.BLOCK_BEATS_DEFAULT_VALUE, "block supersedes default value argument"); } for (int i = 0; i < ilen; i++) { store(i, block.yield(context, new RubyFixnum(runtime, i))); realLength = i + 1; } } else { try { Arrays.fill(values, 0, ilen, (argc == 2) ? args[1] : runtime.getNil()); } catch (ArrayIndexOutOfBoundsException e) { concurrentModification(); } realLength = ilen; } return this; } /** rb_ary_initialize_copy * */ @JRubyMethod(name = {"initialize_copy"}, required = 1, visibility=Visibility.PRIVATE) @Override public IRubyObject initialize_copy(IRubyObject orig) { return this.replace(orig); } /** rb_ary_replace * */ @JRubyMethod(name = {"replace"}, required = 1) public IRubyObject replace(IRubyObject orig) { modifyCheck(); RubyArray origArr = orig.convertToArray(); if (this == orig) return this; origArr.isShared = true; isShared = true; values = origArr.values; realLength = origArr.realLength; begin = origArr.begin; return this; } /** rb_ary_to_s * */ @JRubyMethod(name = "to_s") @Override public IRubyObject to_s() { if (realLength == 0) return RubyString.newEmptyString(getRuntime()); return join(getRuntime().getCurrentContext(), getRuntime().getGlobalVariables().get("$,")); } public boolean includes(ThreadContext context, IRubyObject item) { int begin = this.begin; for (int i = begin; i < begin + realLength; i++) { final IRubyObject value; try { value = values[i]; } catch (ArrayIndexOutOfBoundsException e) { concurrentModification(); continue; } if (equalInternal(context, value, item)) return true; } return false; } /** rb_ary_hash * */ @JRubyMethod(name = "hash") public RubyFixnum hash(ThreadContext context) { int h = realLength; Ruby runtime = getRuntime(); int begin = this.begin; for (int i = begin; i < begin + realLength; i++) { h = (h << 1) | (h < 0 ? 1 : 0); final IRubyObject value; try { value = values[i]; } catch (ArrayIndexOutOfBoundsException e) { concurrentModification(); continue; } h ^= RubyNumeric.num2long(value.callMethod(context, MethodIndex.HASH, "hash")); } return runtime.newFixnum(h); } /** rb_ary_store * */ public final IRubyObject store(long index, IRubyObject value) { if (index < 0) { index += realLength; if (index < 0) { throw getRuntime().newIndexError("index " + (index - realLength) + " out of array"); } } modify(); if (index >= realLength) { if (index >= values.length) { long newLength = values.length >> 1; if (newLength < ARRAY_DEFAULT_SIZE) newLength = ARRAY_DEFAULT_SIZE; newLength += index; if (index >= Integer.MAX_VALUE || newLength >= Integer.MAX_VALUE) { throw getRuntime().newArgumentError("index too big"); } realloc((int) newLength); } realLength = (int) index + 1; } try { values[(int) index] = value; } catch (ArrayIndexOutOfBoundsException e) { concurrentModification(); } return value; } /** rb_ary_elt * */ private final IRubyObject elt(long offset) { if (offset < 0 || offset >= realLength) { return getRuntime().getNil(); } try { return values[begin + (int)offset]; } catch (ArrayIndexOutOfBoundsException e) { concurrentModification(); return getRuntime().getNil(); } } /** rb_ary_entry * */ public final IRubyObject entry(long offset) { return (offset < 0 ) ? elt(offset + realLength) : elt(offset); } /** rb_ary_entry * */ public final IRubyObject entry(int offset) { return (offset < 0 ) ? elt(offset + realLength) : elt(offset); } public final IRubyObject eltInternal(int offset) { return values[begin + offset]; } public final IRubyObject eltInternalSet(int offset, IRubyObject item) { return values[begin + offset] = item; } /** * Variable arity version for compatibility. Not bound to a Ruby method. * @deprecated Use the versions with zero, one, or two args. */ public IRubyObject fetch(ThreadContext context, IRubyObject[] args, Block block) { switch (args.length) { case 1: return fetch(context, args[0], block); case 2: return fetch(context, args[0], args[1], block); default: Arity.raiseArgumentError(getRuntime(), args.length, 1, 2); return null; // not reached } } /** rb_ary_fetch * */ @JRubyMethod(name = "fetch", frame = true) public IRubyObject fetch(ThreadContext context, IRubyObject arg0, Block block) { long index = RubyNumeric.num2long(arg0); if (index < 0) index += realLength; if (index < 0 || index >= realLength) { if (block.isGiven()) return block.yield(context, arg0); throw getRuntime().newIndexError("index " + index + " out of array"); } try { return values[begin + (int) index]; } catch (ArrayIndexOutOfBoundsException e) { concurrentModification(); return getRuntime().getNil(); } } /** rb_ary_fetch * */ @JRubyMethod(name = "fetch", frame = true) public IRubyObject fetch(ThreadContext context, IRubyObject arg0, IRubyObject arg1, Block block) { if (block.isGiven()) getRuntime().getWarnings().warn(ID.BLOCK_BEATS_DEFAULT_VALUE, "block supersedes default value argument"); long index = RubyNumeric.num2long(arg0); if (index < 0) index += realLength; if (index < 0 || index >= realLength) { if (block.isGiven()) return block.yield(context, arg0); return arg1; } try { return values[begin + (int) index]; } catch (ArrayIndexOutOfBoundsException e) { concurrentModification(); return getRuntime().getNil(); } } /** rb_ary_to_ary * */ private static RubyArray aryToAry(IRubyObject obj) { if (obj instanceof RubyArray) return (RubyArray) obj; if (obj.respondsTo("to_ary")) return obj.convertToArray(); RubyArray arr = new RubyArray(obj.getRuntime(), false); // possibly should not in object space arr.alloc(1); arr.values[0] = obj; arr.realLength = 1; return arr; } /** rb_ary_splice * */ private final void splice(long beg, long len, IRubyObject rpl) { if (len < 0) throw getRuntime().newIndexError("negative length (" + len + ")"); if (beg < 0) { beg += realLength; if (beg < 0) { beg -= realLength; throw getRuntime().newIndexError("index " + beg + " out of array"); } } final RubyArray rplArr; final int rlen; if (rpl == null || rpl.isNil()) { rplArr = null; rlen = 0; } else { rplArr = aryToAry(rpl); rlen = rplArr.realLength; } modify(); if (beg >= realLength) { len = beg + rlen; if (len >= values.length) { int tryNewLength = values.length + (values.length >> 1); realloc(len > tryNewLength ? (int)len : tryNewLength); } realLength = (int) len; } else { if (beg + len > realLength) len = realLength - beg; long alen = realLength + rlen - len; if (alen >= values.length) { int tryNewLength = values.length + (values.length >> 1); realloc(alen > tryNewLength ? (int)alen : tryNewLength); } if (len != rlen) { try { System.arraycopy(values, (int) (beg + len), values, (int) beg + rlen, realLength - (int) (beg + len)); } catch (ArrayIndexOutOfBoundsException e) { concurrentModification(); } realLength = (int) alen; } } if (rlen > 0) { try { System.arraycopy(rplArr.values, rplArr.begin, values, (int) beg, rlen); } catch (ArrayIndexOutOfBoundsException e) { concurrentModification(); } } } /** rb_ary_splice * */ private final void spliceOne(long beg, long len, IRubyObject rpl) { if (len < 0) throw getRuntime().newIndexError("negative length (" + len + ")"); if (beg < 0) { beg += realLength; if (beg < 0) { beg -= realLength; throw getRuntime().newIndexError("index " + beg + " out of array"); } } modify(); if (beg >= realLength) { len = beg + 1; if (len >= values.length) { int tryNewLength = values.length + (values.length >> 1); realloc(len > tryNewLength ? (int)len : tryNewLength); } realLength = (int) len; } else { if (beg + len > realLength) len = realLength - beg; int alen = realLength + 1 - (int)len; if (alen >= values.length) { int tryNewLength = values.length + (values.length >> 1); realloc(alen > tryNewLength ? alen : tryNewLength); } if (len != 1) { try { System.arraycopy(values, (int) (beg + len), values, (int) beg + 1, realLength - (int) (beg + len)); } catch (ArrayIndexOutOfBoundsException e) { concurrentModification(); } realLength = alen; } } try { values[(int)beg] = rpl; } catch (ArrayIndexOutOfBoundsException e) { concurrentModification(); } } /** rb_ary_insert * */ @JRubyMethod public IRubyObject insert(IRubyObject arg) { return this; } /** rb_ary_insert * */ @JRubyMethod public IRubyObject insert(IRubyObject arg1, IRubyObject arg2) { long pos = RubyNumeric.num2long(arg1); if (pos == -1) pos = realLength; if (pos < 0) pos++; spliceOne(pos, 0, arg2); // rb_ary_new4 return this; } /** rb_ary_insert * */ @JRubyMethod(name = "insert", required = 1, rest = true) public IRubyObject insert(IRubyObject[] args) { if (args.length == 1) return this; long pos = RubyNumeric.num2long(args[0]); if (pos == -1) pos = realLength; if (pos < 0) pos++; RubyArray inserted = new RubyArray(getRuntime(), false); inserted.values = args; inserted.begin = 1; inserted.realLength = args.length - 1; splice(pos, 0, inserted); // rb_ary_new4 return this; } /** rb_ary_dup * */ public final RubyArray aryDup() { RubyArray dup = new RubyArray(getRuntime(), getMetaClass(), this); dup.flags |= flags & TAINTED_F; // from DUP_SETUP // rb_copy_generic_ivar from DUP_SETUP here ...unlikely.. return dup; } /** rb_ary_transpose * */ @JRubyMethod(name = "transpose") public RubyArray transpose() { RubyArray tmp, result = null; int alen = realLength; if (alen == 0) return aryDup(); Ruby runtime = getRuntime(); int elen = -1; int end = begin + alen; for (int i = begin; i < end; i++) { tmp = elt(i).convertToArray(); if (elen < 0) { elen = tmp.realLength; result = new RubyArray(runtime, elen); for (int j = 0; j < elen; j++) { result.store(j, new RubyArray(runtime, alen)); } } else if (elen != tmp.realLength) { throw runtime.newIndexError("element size differs (" + tmp.realLength + " should be " + elen + ")"); } for (int j = 0; j < elen; j++) { ((RubyArray) result.elt(j)).store(i - begin, tmp.elt(j)); } } return result; } /** rb_values_at (internal) * */ private final IRubyObject values_at(long olen, IRubyObject[] args) { RubyArray result = new RubyArray(getRuntime(), args.length); for (int i = 0; i < args.length; i++) { if (args[i] instanceof RubyFixnum) { result.append(entry(((RubyFixnum)args[i]).getLongValue())); continue; } long beglen[]; if (!(args[i] instanceof RubyRange)) { } else if ((beglen = ((RubyRange) args[i]).begLen(olen, 0)) == null) { continue; } else { int beg = (int) beglen[0]; int len = (int) beglen[1]; int end = begin + len; for (int j = begin; j < end; j++) { result.append(entry(j + beg)); } continue; } result.append(entry(RubyNumeric.num2long(args[i]))); } return result; } /** rb_values_at * */ @JRubyMethod(name = "values_at", rest = true) public IRubyObject values_at(IRubyObject[] args) { return values_at(realLength, args); } /** rb_ary_subseq * */ public IRubyObject subseq(long beg, long len) { if (beg > realLength || beg < 0 || len < 0) return getRuntime().getNil(); if (beg + len > realLength) { len = realLength - beg; if (len < 0) len = 0; } if (len == 0) return new RubyArray(getRuntime(), getMetaClass(), 0); return makeShared(begin + (int) beg, (int) len, getMetaClass()); } /** rb_ary_subseq * */ public IRubyObject subseqLight(long beg, long len) { if (beg > realLength || beg < 0 || len < 0) return getRuntime().getNil(); if (beg + len > realLength) { len = realLength - beg; if (len < 0) len = 0; } if (len == 0) return new RubyArray(getRuntime(), getMetaClass(), 0, false); return makeShared(begin + (int) beg, (int) len, getMetaClass(), false); } /** rb_ary_length * */ @JRubyMethod(name = "length", alias = "size") public RubyFixnum length() { return getRuntime().newFixnum(realLength); } /** rb_ary_push - specialized rb_ary_store * */ @JRubyMethod(name = "<<", required = 1) public RubyArray append(IRubyObject item) { modify(); if (realLength == values.length) { if (realLength == Integer.MAX_VALUE) throw getRuntime().newArgumentError("index too big"); long newLength = values.length + (values.length >> 1); if ( newLength > Integer.MAX_VALUE ) { newLength = Integer.MAX_VALUE; }else if ( newLength < ARRAY_DEFAULT_SIZE ) { newLength = ARRAY_DEFAULT_SIZE; } realloc((int) newLength); } try { values[realLength++] = item; } catch (ArrayIndexOutOfBoundsException e) { concurrentModification(); } return this; } /** rb_ary_push_m * FIXME: Whis is this named "push_m"? */ @JRubyMethod(name = "push", rest = true) public RubyArray push_m(IRubyObject[] items) { for (int i = 0; i < items.length; i++) { append(items[i]); } return this; } /** rb_ary_pop * */ @JRubyMethod(name = "pop") public IRubyObject pop() { modifyCheck(); if (realLength == 0) return getRuntime().getNil(); if (isShared) { try { return values[begin + --realLength]; } catch (ArrayIndexOutOfBoundsException e) { concurrentModification(); return getRuntime().getNil(); } } else { int index = begin + --realLength; try { final IRubyObject obj = values[index]; values[index] = getRuntime().getNil(); return obj; } catch (ArrayIndexOutOfBoundsException e) { concurrentModification(); return getRuntime().getNil(); } } } /** rb_ary_shift * */ @JRubyMethod(name = "shift") public IRubyObject shift() { modify(); if (realLength == 0) return getRuntime().getNil(); final IRubyObject obj; try { obj = values[begin]; values[begin] = getRuntime().getNil(); } catch (ArrayIndexOutOfBoundsException e) { concurrentModification(); return getRuntime().getNil(); } isShared = true; begin++; realLength--; return obj; } /** rb_ary_unshift * */ public RubyArray unshift(IRubyObject item) { modify(); if (realLength == values.length) { int newLength = values.length >> 1; if (newLength < ARRAY_DEFAULT_SIZE) newLength = ARRAY_DEFAULT_SIZE; newLength += values.length; realloc(newLength); } try { System.arraycopy(values, 0, values, 1, realLength); } catch (ArrayIndexOutOfBoundsException e) { concurrentModification(); } realLength++; values[0] = item; return this; } /** rb_ary_unshift_m * */ @JRubyMethod(name = "unshift", rest = true) public RubyArray unshift_m(IRubyObject[] items) { long len = realLength; if (items.length == 0) return this; store(len + items.length - 1, getRuntime().getNil()); try { // it's safe to use zeroes here since modified by store() System.arraycopy(values, 0, values, items.length, (int) len); System.arraycopy(items, 0, values, 0, items.length); } catch (ArrayIndexOutOfBoundsException e) { concurrentModification(); } return this; } /** rb_ary_includes * */ @JRubyMethod(name = "include?", required = 1) public RubyBoolean include_p(ThreadContext context, IRubyObject item) { return context.getRuntime().newBoolean(includes(context, item)); } /** rb_ary_frozen_p * */ @JRubyMethod(name = "frozen?") @Override public RubyBoolean frozen_p(ThreadContext context) { return context.getRuntime().newBoolean(isFrozen() || (flags & TMPLOCK_ARR_F) != 0); } /** * Variable arity version for compatibility. Not bound to a Ruby method. * @deprecated Use the versions with zero, one, or two args. */ public IRubyObject aref(IRubyObject[] args) { switch (args.length) { case 1: return aref(args[0]); case 2: return aref(args[0], args[1]); default: Arity.raiseArgumentError(getRuntime(), args.length, 1, 2); return null; // not reached } } /** rb_ary_aref */ @JRubyMethod(name = {"[]", "slice"}) public IRubyObject aref(IRubyObject arg0) { if (arg0 instanceof RubyFixnum) return entry(((RubyFixnum)arg0).getLongValue()); if (arg0 instanceof RubySymbol) throw getRuntime().newTypeError("Symbol as array index"); long[] beglen; if (!(arg0 instanceof RubyRange)) { } else if ((beglen = ((RubyRange) arg0).begLen(realLength, 0)) == null) { return getRuntime().getNil(); } else { return subseq(beglen[0], beglen[1]); } return entry(RubyNumeric.num2long(arg0)); } /** rb_ary_aref */ @JRubyMethod(name = {"[]", "slice"}) public IRubyObject aref(IRubyObject arg0, IRubyObject arg1) { if (arg0 instanceof RubySymbol) throw getRuntime().newTypeError("Symbol as array index"); long beg = RubyNumeric.num2long(arg0); if (beg < 0) beg += realLength; return subseq(beg, RubyNumeric.num2long(arg1)); } /** * Variable arity version for compatibility. Not bound to a Ruby method. * @deprecated Use the versions with zero, one, or two args. */ public IRubyObject aset(IRubyObject[] args) { switch (args.length) { case 2: return aset(args[0], args[1]); case 3: return aset(args[0], args[1], args[2]); default: throw getRuntime().newArgumentError("wrong number of arguments (" + args.length + " for 2)"); } } /** rb_ary_aset * */ @JRubyMethod(name = "[]=") public IRubyObject aset(IRubyObject arg0, IRubyObject arg1) { if (arg0 instanceof RubyFixnum) { store(((RubyFixnum)arg0).getLongValue(), arg1); return arg1; } if (arg0 instanceof RubyRange) { long[] beglen = ((RubyRange) arg0).begLen(realLength, 1); splice(beglen[0], beglen[1], arg1); return arg1; } if (arg0 instanceof RubySymbol) throw getRuntime().newTypeError("Symbol as array index"); store(RubyNumeric.num2long(arg0), arg1); return arg1; } /** rb_ary_aset * */ @JRubyMethod(name = "[]=") public IRubyObject aset(IRubyObject arg0, IRubyObject arg1, IRubyObject arg2) { if (arg0 instanceof RubySymbol) throw getRuntime().newTypeError("Symbol as array index"); if (arg1 instanceof RubySymbol) throw getRuntime().newTypeError("Symbol as subarray length"); splice(RubyNumeric.num2long(arg0), RubyNumeric.num2long(arg1), arg2); return arg2; } /** rb_ary_at * */ @JRubyMethod(name = "at", required = 1) public IRubyObject at(IRubyObject pos) { return entry(RubyNumeric.num2long(pos)); } /** rb_ary_concat * */ @JRubyMethod(name = "concat", required = 1) public RubyArray concat(IRubyObject obj) { RubyArray ary = obj.convertToArray(); if (ary.realLength > 0) splice(realLength, 0, ary); return this; } /** inspect_ary * */ private IRubyObject inspectAry(ThreadContext context) { ByteList buffer = new ByteList(); buffer.append('['); boolean tainted = isTaint(); for (int i = 0; i < realLength; i++) { if (i > 0) buffer.append(',').append(' '); RubyString str = inspect(context, values[begin + i]); if (str.isTaint()) tainted = true; buffer.append(str.getByteList()); } buffer.append(']'); RubyString str = getRuntime().newString(buffer); if (tainted) str.setTaint(true); return str; } /** rb_ary_inspect * */ @JRubyMethod(name = "inspect") @Override public IRubyObject inspect() { if (realLength == 0) return getRuntime().newString("[]"); if (getRuntime().isInspecting(this)) return getRuntime().newString("[...]"); try { getRuntime().registerInspecting(this); return inspectAry(getRuntime().getCurrentContext()); } finally { getRuntime().unregisterInspecting(this); } } /** * Variable arity version for compatibility. Not bound to a Ruby method. * @deprecated Use the versions with zero, one, or two args. */ public IRubyObject first(IRubyObject[] args) { switch (args.length) { case 0: return first(); case 1: return first(args[0]); default: Arity.raiseArgumentError(getRuntime(), args.length, 0, 1); return null; // not reached } } /** rb_ary_first * */ @JRubyMethod(name = "first") public IRubyObject first() { if (realLength == 0) return getRuntime().getNil(); return values[begin]; } /** rb_ary_first * */ @JRubyMethod(name = "first") public IRubyObject first(IRubyObject arg0) { long n = RubyNumeric.num2long(arg0); if (n > realLength) { n = realLength; } else if (n < 0) { throw getRuntime().newArgumentError("negative array size (or size too big)"); } return makeShared(begin, (int) n, getRuntime().getArray()); } /** * Variable arity version for compatibility. Not bound to a Ruby method. * @deprecated Use the versions with zero, one, or two args. */ public IRubyObject last(IRubyObject[] args) { switch (args.length) { case 0: return last(); case 1: return last(args[0]); default: Arity.raiseArgumentError(getRuntime(), args.length, 0, 1); return null; // not reached } } /** rb_ary_last * */ @JRubyMethod(name = "last") public IRubyObject last() { if (realLength == 0) return getRuntime().getNil(); return values[begin + realLength - 1]; } /** rb_ary_last * */ @JRubyMethod(name = "last") public IRubyObject last(IRubyObject arg0) { long n = RubyNumeric.num2long(arg0); if (n > realLength) { n = realLength; } else if (n < 0) { throw getRuntime().newArgumentError("negative array size (or size too big)"); } return makeShared(begin + realLength - (int) n, (int) n, getRuntime().getArray()); } /** rb_ary_each * */ @JRubyMethod(name = "each", frame = true) public IRubyObject each(ThreadContext context, Block block) { for (int i = 0; i < realLength; i++) { block.yield(context, values[begin + i]); } return this; } /** rb_ary_each_index * */ @JRubyMethod(name = "each_index", frame = true) public IRubyObject each_index(ThreadContext context, Block block) { Ruby runtime = getRuntime(); for (int i = 0; i < realLength; i++) { block.yield(context, runtime.newFixnum(i)); } return this; } /** rb_ary_reverse_each * */ @JRubyMethod(name = "reverse_each", frame = true) public IRubyObject reverse_each(ThreadContext context, Block block) { int len = realLength; while(len-- > 0) { block.yield(context, values[begin + len]); if (realLength < len) len = realLength; } return this; } private IRubyObject inspectJoin(ThreadContext context, RubyArray tmp, IRubyObject sep) { Ruby runtime = getRuntime(); // If already inspecting, there is no need to register/unregister again. if (runtime.isInspecting(this)) { return tmp.join(context, sep); } try { runtime.registerInspecting(this); return tmp.join(context, sep); } finally { runtime.unregisterInspecting(this); } } /** rb_ary_join * */ public RubyString join(ThreadContext context, IRubyObject sep) { final Ruby runtime = getRuntime(); if (realLength == 0) return RubyString.newEmptyString(getRuntime()); boolean taint = isTaint() || sep.isTaint(); long len = 1; for (int i = begin; i < begin + realLength; i++) { IRubyObject value; try { value = values[i]; } catch (ArrayIndexOutOfBoundsException e) { concurrentModification(); return runtime.newString(""); } IRubyObject tmp = values[i].checkStringType(); len += tmp.isNil() ? 10 : ((RubyString) tmp).getByteList().length(); } RubyString strSep = null; if (!sep.isNil()) { sep = strSep = sep.convertToString(); len += strSep.getByteList().length() * (realLength - 1); } ByteList buf = new ByteList((int)len); for (int i = begin; i < begin + realLength; i++) { IRubyObject tmp; try { tmp = values[i]; } catch (ArrayIndexOutOfBoundsException e) { concurrentModification(); return runtime.newString(""); } if (tmp instanceof RubyString) { // do nothing } else if (tmp instanceof RubyArray) { if (runtime.isInspecting(tmp)) { tmp = runtime.newString("[...]"); } else { tmp = inspectJoin(context, (RubyArray)tmp, sep); } } else { tmp = RubyString.objAsString(context, tmp); } if (i > begin && !sep.isNil()) buf.append(strSep.getByteList()); buf.append(tmp.asString().getByteList()); if (tmp.isTaint()) taint = true; } RubyString result = runtime.newString(buf); if (taint) result.setTaint(true); return result; } /** rb_ary_join_m * */ @JRubyMethod(name = "join", optional = 1) public RubyString join_m(ThreadContext context, IRubyObject[] args) { int argc = args.length; IRubyObject sep = (argc == 1) ? args[0] : getRuntime().getGlobalVariables().get("$,"); return join(context, sep); } /** rb_ary_to_a * */ @JRubyMethod(name = "to_a") @Override public RubyArray to_a() { if(getMetaClass() != getRuntime().getArray()) { RubyArray dup = new RubyArray(getRuntime(), getRuntime().isObjectSpaceEnabled()); isShared = true; dup.isShared = true; dup.values = values; dup.realLength = realLength; dup.begin = begin; return dup; } return this; } @JRubyMethod(name = "to_ary") public IRubyObject to_ary() { return this; } @Override public RubyArray convertToArray() { return this; } @Override public IRubyObject checkArrayType(){ return this; } /** rb_ary_equal * */ @JRubyMethod(name = "==", required = 1) @Override public IRubyObject op_equal(ThreadContext context, IRubyObject obj) { if (this == obj) return getRuntime().getTrue(); if (!(obj instanceof RubyArray)) { if (!obj.respondsTo("to_ary")) { return getRuntime().getFalse(); } else { if (equalInternal(context, obj.callMethod(context, "to_ary"), this)) return getRuntime().getTrue(); return getRuntime().getFalse(); } } RubyArray ary = (RubyArray) obj; if (realLength != ary.realLength) return getRuntime().getFalse(); Ruby runtime = getRuntime(); for (long i = 0; i < realLength; i++) { if (!equalInternal(context, elt(i), ary.elt(i))) return runtime.getFalse(); } return runtime.getTrue(); } /** rb_ary_eql * */ @JRubyMethod(name = "eql?", required = 1) public RubyBoolean eql_p(ThreadContext context, IRubyObject obj) { if (this == obj) return getRuntime().getTrue(); if (!(obj instanceof RubyArray)) return getRuntime().getFalse(); RubyArray ary = (RubyArray) obj; if (realLength != ary.realLength) return getRuntime().getFalse(); Ruby runtime = getRuntime(); for (int i = 0; i < realLength; i++) { if (!eqlInternal(context, elt(i), ary.elt(i))) return runtime.getFalse(); } return runtime.getTrue(); } /** rb_ary_compact_bang * */ @JRubyMethod(name = "compact!") public IRubyObject compact_bang() { modify(); int p = 0; int t = 0; int end = p + realLength; while (t < end) { if (values[t].isNil()) { t++; } else { values[p++] = values[t++]; } } if (realLength == p) return getRuntime().getNil(); realloc(p); realLength = p; return this; } /** rb_ary_compact * */ @JRubyMethod(name = "compact") public IRubyObject compact() { RubyArray ary = aryDup(); ary.compact_bang(); return ary; } /** rb_ary_empty_p * */ @JRubyMethod(name = "empty?") public IRubyObject empty_p() { return realLength == 0 ? getRuntime().getTrue() : getRuntime().getFalse(); } /** rb_ary_clear * */ @JRubyMethod(name = "clear") public IRubyObject rb_clear() { modifyCheck(); if(isShared) { alloc(ARRAY_DEFAULT_SIZE); isShared = true; } else if (values.length > ARRAY_DEFAULT_SIZE << 1){ alloc(ARRAY_DEFAULT_SIZE << 1); } else { final int begin = this.begin; try { Arrays.fill(values, begin, begin + realLength, getRuntime().getNil()); } catch (ArrayIndexOutOfBoundsException e) { concurrentModification(); } } begin = 0; realLength = 0; return this; } /** rb_ary_fill * */ @JRubyMethod(name = "fill", optional = 3, frame = true) public IRubyObject fill(ThreadContext context, IRubyObject[] args, Block block) { IRubyObject item = null; IRubyObject begObj = null; IRubyObject lenObj = null; int argc = args.length; if (block.isGiven()) { Arity.checkArgumentCount(getRuntime(), args, 0, 2); item = null; begObj = argc > 0 ? args[0] : null; lenObj = argc > 1 ? args[1] : null; argc++; } else { Arity.checkArgumentCount(getRuntime(), args, 1, 3); item = args[0]; begObj = argc > 1 ? args[1] : null; lenObj = argc > 2 ? args[2] : null; } int beg = 0, end = 0, len = 0; switch (argc) { case 1: beg = 0; len = realLength; break; case 2: if (begObj instanceof RubyRange) { long[] beglen = ((RubyRange) begObj).begLen(realLength, 1); beg = (int) beglen[0]; len = (int) beglen[1]; break; } /* fall through */ case 3: beg = begObj.isNil() ? 0 : RubyNumeric.num2int(begObj); if (beg < 0) { beg = realLength + beg; if (beg < 0) beg = 0; } len = (lenObj == null || lenObj.isNil()) ? realLength - beg : RubyNumeric.num2int(lenObj); // TODO: In MRI 1.9, an explicit check for negative length is // added here. IndexError is raised when length is negative. // See [ruby-core:12953] for more details. // // New note: This is actually under re-evaluation, // see [ruby-core:17483]. break; } modify(); // See [ruby-core:17483] if (len < 0) { return this; } if (len > Integer.MAX_VALUE - beg) { throw getRuntime().newArgumentError("argument too big"); } end = beg + len; if (end > realLength) { if (end >= values.length) realloc(end); realLength = end; } if (block.isGiven()) { Ruby runtime = getRuntime(); for (int i = beg; i < end; i++) { IRubyObject v = block.yield(context, runtime.newFixnum(i)); if (i >= realLength) break; try { values[i] = v; } catch (ArrayIndexOutOfBoundsException e) { concurrentModification(); } } + } else { + if (len > 0) { + try { + Arrays.fill(values, beg, beg + len, item); + } catch (ArrayIndexOutOfBoundsException e) { + concurrentModification(); + } + } } return this; } /** rb_ary_index * */ @JRubyMethod(name = "index", required = 1) public IRubyObject index(ThreadContext context, IRubyObject obj) { Ruby runtime = getRuntime(); for (int i = begin; i < begin + realLength; i++) { if (equalInternal(context, values[i], obj)) return runtime.newFixnum(i - begin); } return runtime.getNil(); } /** rb_ary_rindex * */ @JRubyMethod(name = "rindex", required = 1) public IRubyObject rindex(ThreadContext context, IRubyObject obj) { Ruby runtime = getRuntime(); int i = realLength; while (i-- > 0) { if (i > realLength) { i = realLength; continue; } if (equalInternal(context, values[begin + i], obj)) return getRuntime().newFixnum(i); } return runtime.getNil(); } /** rb_ary_indexes * */ @JRubyMethod(name = {"indexes", "indices"}, required = 1, rest = true) public IRubyObject indexes(IRubyObject[] args) { getRuntime().getWarnings().warn(ID.DEPRECATED_METHOD, "Array#indexes is deprecated; use Array#values_at", "Array#indexes", "Array#values_at"); RubyArray ary = new RubyArray(getRuntime(), args.length); IRubyObject[] arefArgs = new IRubyObject[1]; for (int i = 0; i < args.length; i++) { arefArgs[0] = args[i]; ary.append(aref(arefArgs)); } return ary; } /** rb_ary_reverse_bang * */ @JRubyMethod(name = "reverse!") public IRubyObject reverse_bang() { modify(); final int realLength = this.realLength; final IRubyObject[] values = this.values; try { if (realLength > 1) { int p1 = 0; int p2 = p1 + realLength - 1; while (p1 < p2) { final IRubyObject tmp = values[p1]; values[p1++] = values[p2]; values[p2--] = tmp; } } } catch (ArrayIndexOutOfBoundsException e) { concurrentModification(); } return this; } /** rb_ary_reverse_m * */ @JRubyMethod(name = "reverse") public IRubyObject reverse() { return aryDup().reverse_bang(); } /** rb_ary_collect * */ @JRubyMethod(name = {"collect", "map"}, frame = true) public RubyArray collect(ThreadContext context, Block block) { Ruby runtime = getRuntime(); if (!block.isGiven()) return new RubyArray(getRuntime(), runtime.getArray(), this); RubyArray collect = new RubyArray(runtime, realLength); for (int i = begin; i < begin + realLength; i++) { collect.append(block.yield(context, values[i])); } return collect; } /** rb_ary_collect_bang * */ @JRubyMethod(name = {"collect!", "map!"}, frame = true) public RubyArray collect_bang(ThreadContext context, Block block) { modify(); for (int i = 0, len = realLength; i < len; i++) { store(i, block.yield(context, values[begin + i])); } return this; } /** rb_ary_select * */ @JRubyMethod(name = "select", frame = true) public RubyArray select(ThreadContext context, Block block) { Ruby runtime = getRuntime(); RubyArray result = new RubyArray(runtime, realLength); if (isShared) { for (int i = begin; i < begin + realLength; i++) { if (block.yield(context, values[i]).isTrue()) result.append(elt(i - begin)); } } else { for (int i = 0; i < realLength; i++) { if (block.yield(context, values[i]).isTrue()) result.append(elt(i)); } } return result; } /** rb_ary_delete * */ @JRubyMethod(name = "delete", required = 1, frame = true) public IRubyObject delete(ThreadContext context, IRubyObject item, Block block) { int i2 = 0; Ruby runtime = getRuntime(); for (int i1 = 0; i1 < realLength; i1++) { IRubyObject e = values[begin + i1]; if (equalInternal(context, e, item)) continue; if (i1 != i2) store(i2, e); i2++; } if (realLength == i2) { if (block.isGiven()) return block.yield(context, item); return runtime.getNil(); } modify(); final int realLength = this.realLength; final int begin = this.begin; final IRubyObject[] values = this.values; if (realLength > i2) { try { Arrays.fill(values, begin + i2, begin + realLength, getRuntime().getNil()); } catch (ArrayIndexOutOfBoundsException e) { concurrentModification(); } this.realLength = i2; if (i2 << 1 < values.length && values.length > ARRAY_DEFAULT_SIZE) realloc(i2 << 1); } return item; } /** rb_ary_delete_at * */ private final IRubyObject delete_at(int pos) { int len = realLength; if (pos >= len) return getRuntime().getNil(); if (pos < 0) pos += len; if (pos < 0) return getRuntime().getNil(); modify(); IRubyObject obj = values[pos]; try { System.arraycopy(values, pos + 1, values, pos, len - (pos + 1)); values[realLength-1] = getRuntime().getNil(); } catch (ArrayIndexOutOfBoundsException e) { concurrentModification(); } realLength--; return obj; } /** rb_ary_delete_at_m * */ @JRubyMethod(name = "delete_at", required = 1) public IRubyObject delete_at(IRubyObject obj) { return delete_at((int) RubyNumeric.num2long(obj)); } /** rb_ary_reject_bang * */ @JRubyMethod(name = "reject", frame = true) public IRubyObject reject(ThreadContext context, Block block) { RubyArray ary = aryDup(); ary.reject_bang(context, block); return ary; } /** rb_ary_reject_bang * */ @JRubyMethod(name = "reject!", frame = true) public IRubyObject reject_bang(ThreadContext context, Block block) { int i2 = 0; modify(); for (int i1 = 0; i1 < realLength; i1++) { IRubyObject v = values[i1]; if (block.yield(context, v).isTrue()) continue; if (i1 != i2) store(i2, v); i2++; } if (realLength == i2) return getRuntime().getNil(); if (i2 < realLength) { try { Arrays.fill(values, i2, realLength, getRuntime().getNil()); } catch (ArrayIndexOutOfBoundsException e) { concurrentModification(); } realLength = i2; } return this; } /** rb_ary_delete_if * */ @JRubyMethod(name = "delete_if", frame = true) public IRubyObject delete_if(ThreadContext context, Block block) { reject_bang(context, block); return this; } /** rb_ary_zip * */ @JRubyMethod(name = "zip", optional = 1, rest = true, frame = true) public IRubyObject zip(ThreadContext context, IRubyObject[] args, Block block) { for (int i = 0; i < args.length; i++) { args[i] = args[i].convertToArray(); } Ruby runtime = getRuntime(); if (block.isGiven()) { for (int i = 0; i < realLength; i++) { RubyArray tmp = new RubyArray(runtime, args.length + 1); tmp.append(elt(i)); for (int j = 0; j < args.length; j++) { tmp.append(((RubyArray) args[j]).elt(i)); } block.yield(context, tmp); } return runtime.getNil(); } int len = realLength; RubyArray result = new RubyArray(runtime, len); for (int i = 0; i < len; i++) { RubyArray tmp = new RubyArray(runtime, args.length + 1); tmp.append(elt(i)); for (int j = 0; j < args.length; j++) { tmp.append(((RubyArray) args[j]).elt(i)); } result.append(tmp); } return result; } /** rb_ary_cmp * */ @JRubyMethod(name = "<=>", required = 1) public IRubyObject op_cmp(ThreadContext context, IRubyObject obj) { RubyArray ary2 = obj.convertToArray(); int len = realLength; if (len > ary2.realLength) len = ary2.realLength; Ruby runtime = getRuntime(); for (int i = 0; i < len; i++) { IRubyObject v = elt(i).callMethod(context, MethodIndex.OP_SPACESHIP, "<=>", ary2.elt(i)); if (!(v instanceof RubyFixnum) || ((RubyFixnum) v).getLongValue() != 0) return v; } len = realLength - ary2.realLength; if (len == 0) return RubyFixnum.zero(runtime); if (len > 0) return RubyFixnum.one(runtime); return RubyFixnum.minus_one(runtime); } /** * Variable arity version for compatibility. Not bound to a Ruby method. * @deprecated Use the versions with zero, one, or two args. */ public IRubyObject slice_bang(IRubyObject[] args) { switch (args.length) { case 1: return slice_bang(args[0]); case 2: return slice_bang(args[0], args[1]); default: Arity.raiseArgumentError(getRuntime(), args.length, 1, 2); return null; // not reached } } /** rb_ary_slice_bang * */ @JRubyMethod(name = "slice!") public IRubyObject slice_bang(IRubyObject arg0) { if (arg0 instanceof RubyRange) { long[] beglen = ((RubyRange) arg0).begLen(realLength, 1); long pos = beglen[0]; long len = beglen[1]; if (pos < 0) pos = realLength + pos; arg0 = subseq(pos, len); splice(pos, len, null); return arg0; } return delete_at((int) RubyNumeric.num2long(arg0)); } /** rb_ary_slice_bang * */ @JRubyMethod(name = "slice!") public IRubyObject slice_bang(IRubyObject arg0, IRubyObject arg1) { long pos = RubyNumeric.num2long(arg0); long len = RubyNumeric.num2long(arg1); if (pos < 0) pos = realLength + pos; arg1 = subseq(pos, len); splice(pos, len, null); return arg1; } /** rb_ary_assoc * */ @JRubyMethod(name = "assoc", required = 1) public IRubyObject assoc(ThreadContext context, IRubyObject key) { Ruby runtime = getRuntime(); for (int i = begin; i < begin + realLength; i++) { IRubyObject v = values[i]; if (v instanceof RubyArray) { RubyArray arr = (RubyArray)v; if (arr.realLength > 0 && equalInternal(context, arr.values[arr.begin], key)) return arr; } } return runtime.getNil(); } /** rb_ary_rassoc * */ @JRubyMethod(name = "rassoc", required = 1) public IRubyObject rassoc(ThreadContext context, IRubyObject value) { Ruby runtime = getRuntime(); for (int i = begin; i < begin + realLength; i++) { IRubyObject v = values[i]; if (v instanceof RubyArray) { RubyArray arr = (RubyArray)v; if (arr.realLength > 1 && equalInternal(context, arr.values[arr.begin + 1], value)) return arr; } } return runtime.getNil(); } /** flatten * */ private final int flatten(ThreadContext context, int index, RubyArray ary2, RubyArray memo) { int i = index; int n; int lim = index + ary2.realLength; IRubyObject id = ary2.id(); if (memo.includes(context, id)) throw getRuntime().newArgumentError("tried to flatten recursive array"); memo.append(id); splice(index, 1, ary2); while (i < lim) { IRubyObject tmp = elt(i).checkArrayType(); if (!tmp.isNil()) { n = flatten(context, i, (RubyArray) tmp, memo); i += n; lim += n; } i++; } memo.pop(); return lim - index - 1; /* returns number of increased items */ } /** rb_ary_flatten_bang * */ @JRubyMethod(name = "flatten!") public IRubyObject flatten_bang(ThreadContext context) { int i = 0; RubyArray memo = null; while (i < realLength) { IRubyObject ary2 = values[begin + i]; IRubyObject tmp = ary2.checkArrayType(); if (!tmp.isNil()) { if (memo == null) { memo = new RubyArray(getRuntime(), false); memo.values = reserve(ARRAY_DEFAULT_SIZE); } i += flatten(context, i, (RubyArray) tmp, memo); } i++; } if (memo == null) return getRuntime().getNil(); return this; } /** rb_ary_flatten * */ @JRubyMethod(name = "flatten") public IRubyObject flatten(ThreadContext context) { RubyArray ary = aryDup(); ary.flatten_bang(context); return ary; } /** rb_ary_nitems * */ @JRubyMethod(name = "nitems") public IRubyObject nitems() { int n = 0; for (int i = begin; i < begin + realLength; i++) { if (!values[i].isNil()) n++; } return getRuntime().newFixnum(n); } /** rb_ary_plus * */ @JRubyMethod(name = "+", required = 1) public IRubyObject op_plus(IRubyObject obj) { RubyArray y = obj.convertToArray(); int len = realLength + y.realLength; RubyArray z = new RubyArray(getRuntime(), len); try { System.arraycopy(values, begin, z.values, 0, realLength); System.arraycopy(y.values, y.begin, z.values, realLength, y.realLength); } catch (ArrayIndexOutOfBoundsException e) { concurrentModification(); } z.realLength = len; return z; } /** rb_ary_times * */ @JRubyMethod(name = "*", required = 1) public IRubyObject op_times(ThreadContext context, IRubyObject times) { IRubyObject tmp = times.checkStringType(); if (!tmp.isNil()) return join(context, tmp); long len = RubyNumeric.num2long(times); if (len == 0) return new RubyArray(getRuntime(), getMetaClass(), 0); if (len < 0) throw getRuntime().newArgumentError("negative argument"); if (Long.MAX_VALUE / len < realLength) { throw getRuntime().newArgumentError("argument too big"); } len *= realLength; RubyArray ary2 = new RubyArray(getRuntime(), getMetaClass(), len); ary2.realLength = (int) len; try { for (int i = 0; i < len; i += realLength) { System.arraycopy(values, begin, ary2.values, i, realLength); } } catch (ArrayIndexOutOfBoundsException e) { concurrentModification(); } ary2.infectBy(this); return ary2; } /** ary_make_hash * */ private final RubyHash makeHash(RubyArray ary2) { RubyHash hash = new RubyHash(getRuntime(), false); int begin = this.begin; for (int i = begin; i < begin + realLength; i++) { hash.fastASet(values[i], NEVER); } if (ary2 != null) { begin = ary2.begin; for (int i = begin; i < begin + ary2.realLength; i++) { hash.fastASet(ary2.values[i], NEVER); } } return hash; } /** rb_ary_uniq_bang * */ @JRubyMethod(name = "uniq!") public IRubyObject uniq_bang() { RubyHash hash = makeHash(null); if (realLength == hash.size()) return getRuntime().getNil(); int j = 0; for (int i = 0; i < realLength; i++) { IRubyObject v = elt(i); if (hash.fastDelete(v)) store(j++, v); } realLength = j; return this; } /** rb_ary_uniq * */ @JRubyMethod(name = "uniq") public IRubyObject uniq() { RubyArray ary = aryDup(); ary.uniq_bang(); return ary; } /** rb_ary_diff * */ @JRubyMethod(name = "-", required = 1) public IRubyObject op_diff(IRubyObject other) { RubyHash hash = other.convertToArray().makeHash(null); RubyArray ary3 = new RubyArray(getRuntime()); int begin = this.begin; for (int i = begin; i < begin + realLength; i++) { if (hash.fastARef(values[i]) != null) continue; ary3.append(elt(i - begin)); } return ary3; } /** rb_ary_and * */ @JRubyMethod(name = "&", required = 1) public IRubyObject op_and(IRubyObject other) { RubyArray ary2 = other.convertToArray(); RubyHash hash = ary2.makeHash(null); RubyArray ary3 = new RubyArray(getRuntime(), realLength < ary2.realLength ? realLength : ary2.realLength); for (int i = 0; i < realLength; i++) { IRubyObject v = elt(i); if (hash.fastDelete(v)) ary3.append(v); } return ary3; } /** rb_ary_or * */ @JRubyMethod(name = "|", required = 1) public IRubyObject op_or(IRubyObject other) { RubyArray ary2 = other.convertToArray(); RubyHash set = makeHash(ary2); RubyArray ary3 = new RubyArray(getRuntime(), realLength + ary2.realLength); for (int i = 0; i < realLength; i++) { IRubyObject v = elt(i); if (set.fastDelete(v)) ary3.append(v); } for (int i = 0; i < ary2.realLength; i++) { IRubyObject v = ary2.elt(i); if (set.fastDelete(v)) ary3.append(v); } return ary3; } /** rb_ary_sort * */ @JRubyMethod(name = "sort", frame = true) public RubyArray sort(Block block) { RubyArray ary = aryDup(); ary.sort_bang(block); return ary; } /** rb_ary_sort_bang * */ @JRubyMethod(name = "sort!", frame = true) public RubyArray sort_bang(Block block) { modify(); if (realLength > 1) { flags |= TMPLOCK_ARR_F; try { if (block.isGiven()) { Arrays.sort(values, 0, realLength, new BlockComparator(block)); } else { Arrays.sort(values, 0, realLength, new DefaultComparator()); } } finally { flags &= ~TMPLOCK_ARR_F; } } return this; } final class BlockComparator implements Comparator { private Block block; public BlockComparator(Block block) { this.block = block; } public int compare(Object o1, Object o2) { ThreadContext context = getRuntime().getCurrentContext(); IRubyObject obj1 = (IRubyObject) o1; IRubyObject obj2 = (IRubyObject) o2; IRubyObject ret = block.yield(context, getRuntime().newArray(obj1, obj2), null, null, true); int n = RubyComparable.cmpint(context, ret, obj1, obj2); //TODO: ary_sort_check should be done here return n; } } static final class DefaultComparator implements Comparator { public int compare(Object o1, Object o2) { if (o1 instanceof RubyFixnum && o2 instanceof RubyFixnum) { return compareFixnums(o1, o2); } if (o1 instanceof RubyString && o2 instanceof RubyString) { return ((RubyString) o1).op_cmp((RubyString) o2); } //TODO: ary_sort_check should be done here return compareOthers((IRubyObject)o1, (IRubyObject)o2); } private int compareFixnums(Object o1, Object o2) { long a = ((RubyFixnum) o1).getLongValue(); long b = ((RubyFixnum) o2).getLongValue(); if (a > b) { return 1; } if (a < b) { return -1; } return 0; } private int compareOthers(IRubyObject o1, IRubyObject o2) { ThreadContext context = o1.getRuntime().getCurrentContext(); IRubyObject ret = o1.callMethod(context, MethodIndex.OP_SPACESHIP, "<=>", o2); int n = RubyComparable.cmpint(context, ret, o1, o2); //TODO: ary_sort_check should be done here return n; } } public static void marshalTo(RubyArray array, MarshalStream output) throws IOException { output.registerLinkTarget(array); output.writeInt(array.getList().size()); for (Iterator iter = array.getList().iterator(); iter.hasNext();) { output.dumpObject((IRubyObject) iter.next()); } } public static RubyArray unmarshalFrom(UnmarshalStream input) throws IOException { RubyArray result = input.getRuntime().newArray(); input.registerLinkTarget(result); int size = input.unmarshalInt(); for (int i = 0; i < size; i++) { result.append(input.unmarshalObject()); } return result; } /** * @see org.jruby.util.Pack#pack */ @JRubyMethod(name = "pack", required = 1) public RubyString pack(ThreadContext context, IRubyObject obj) { RubyString iFmt = RubyString.objAsString(context, obj); return Pack.pack(getRuntime(), this, iFmt.getByteList()); } @Override public Class getJavaClass() { return List.class; } // Satisfy java.util.List interface (for Java integration) public int size() { return realLength; } public boolean isEmpty() { return realLength == 0; } public boolean contains(Object element) { return indexOf(element) != -1; } public Object[] toArray() { Object[] array = new Object[realLength]; for (int i = begin; i < realLength; i++) { array[i - begin] = JavaUtil.convertRubyToJava(values[i]); } return array; } public Object[] toArray(final Object[] arg) { Object[] array = arg; if (array.length < realLength) { Class type = array.getClass().getComponentType(); array = (Object[]) Array.newInstance(type, realLength); } int length = realLength - begin; for (int i = 0; i < length; i++) { array[i] = JavaUtil.convertRubyToJava(values[i + begin]); } return array; } public boolean add(Object element) { append(JavaUtil.convertJavaToRuby(getRuntime(), element)); return true; } public boolean remove(Object element) { IRubyObject deleted = delete(getRuntime().getCurrentContext(), JavaUtil.convertJavaToRuby(getRuntime(), element), Block.NULL_BLOCK); return deleted.isNil() ? false : true; // TODO: is this correct ? } public boolean containsAll(Collection c) { for (Iterator iter = c.iterator(); iter.hasNext();) { if (indexOf(iter.next()) == -1) { return false; } } return true; } public boolean addAll(Collection c) { for (Iterator iter = c.iterator(); iter.hasNext();) { add(iter.next()); } return !c.isEmpty(); } public boolean addAll(int index, Collection c) { Iterator iter = c.iterator(); for (int i = index; iter.hasNext(); i++) { add(i, iter.next()); } return !c.isEmpty(); } public boolean removeAll(Collection c) { boolean listChanged = false; for (Iterator iter = c.iterator(); iter.hasNext();) { if (remove(iter.next())) { listChanged = true; } } return listChanged; } public boolean retainAll(Collection c) { boolean listChanged = false; for (Iterator iter = iterator(); iter.hasNext();) { Object element = iter.next(); if (!c.contains(element)) { remove(element); listChanged = true; } } return listChanged; } public Object get(int index) { return JavaUtil.convertRubyToJava((IRubyObject) elt(index), Object.class); } public Object set(int index, Object element) { return store(index, JavaUtil.convertJavaToRuby(getRuntime(), element)); } // TODO: make more efficient by not creating IRubyArray[] public void add(int index, Object element) { insert(new IRubyObject[]{RubyFixnum.newFixnum(getRuntime(), index), JavaUtil.convertJavaToRuby(getRuntime(), element)}); } public Object remove(int index) { return JavaUtil.convertRubyToJava(delete_at(index), Object.class); } public int indexOf(Object element) { int begin = this.begin; if (element != null) { IRubyObject convertedElement = JavaUtil.convertJavaToRuby(getRuntime(), element); for (int i = begin; i < begin + realLength; i++) { if (convertedElement.equals(values[i])) { return i; } } } return -1; } public int lastIndexOf(Object element) { int begin = this.begin; if (element != null) { IRubyObject convertedElement = JavaUtil.convertJavaToRuby(getRuntime(), element); for (int i = begin + realLength - 1; i >= begin; i--) { if (convertedElement.equals(values[i])) { return i; } } } return -1; } public class RubyArrayConversionIterator implements Iterator { protected int index = 0; protected int last = -1; public boolean hasNext() { return index < realLength; } public Object next() { IRubyObject element = elt(index); last = index++; return JavaUtil.convertRubyToJava(element, Object.class); } public void remove() { if (last == -1) throw new IllegalStateException(); delete_at(last); if (last < index) index--; last = -1; } } public Iterator iterator() { return new RubyArrayConversionIterator(); } final class RubyArrayConversionListIterator extends RubyArrayConversionIterator implements ListIterator { public RubyArrayConversionListIterator() { } public RubyArrayConversionListIterator(int index) { this.index = index; } public boolean hasPrevious() { return index >= 0; } public Object previous() { return JavaUtil.convertRubyToJava((IRubyObject) elt(last = --index), Object.class); } public int nextIndex() { return index; } public int previousIndex() { return index - 1; } public void set(Object obj) { if (last == -1) throw new IllegalStateException(); store(last, JavaUtil.convertJavaToRuby(getRuntime(), obj)); } public void add(Object obj) { insert(new IRubyObject[] { RubyFixnum.newFixnum(getRuntime(), index++), JavaUtil.convertJavaToRuby(getRuntime(), obj) }); last = -1; } } public ListIterator listIterator() { return new RubyArrayConversionListIterator(); } public ListIterator listIterator(int index) { return new RubyArrayConversionListIterator(index); } // TODO: list.subList(from, to).clear() is supposed to clear the sublist from the list. // How can we support this operation? public List subList(int fromIndex, int toIndex) { if (fromIndex < 0 || toIndex > size() || fromIndex > toIndex) { throw new IndexOutOfBoundsException(); } IRubyObject subList = subseq(fromIndex, toIndex - fromIndex + 1); return subList.isNil() ? null : (List) subList; } public void clear() { rb_clear(); } }
true
true
public IRubyObject fill(ThreadContext context, IRubyObject[] args, Block block) { IRubyObject item = null; IRubyObject begObj = null; IRubyObject lenObj = null; int argc = args.length; if (block.isGiven()) { Arity.checkArgumentCount(getRuntime(), args, 0, 2); item = null; begObj = argc > 0 ? args[0] : null; lenObj = argc > 1 ? args[1] : null; argc++; } else { Arity.checkArgumentCount(getRuntime(), args, 1, 3); item = args[0]; begObj = argc > 1 ? args[1] : null; lenObj = argc > 2 ? args[2] : null; } int beg = 0, end = 0, len = 0; switch (argc) { case 1: beg = 0; len = realLength; break; case 2: if (begObj instanceof RubyRange) { long[] beglen = ((RubyRange) begObj).begLen(realLength, 1); beg = (int) beglen[0]; len = (int) beglen[1]; break; } /* fall through */ case 3: beg = begObj.isNil() ? 0 : RubyNumeric.num2int(begObj); if (beg < 0) { beg = realLength + beg; if (beg < 0) beg = 0; } len = (lenObj == null || lenObj.isNil()) ? realLength - beg : RubyNumeric.num2int(lenObj); // TODO: In MRI 1.9, an explicit check for negative length is // added here. IndexError is raised when length is negative. // See [ruby-core:12953] for more details. // // New note: This is actually under re-evaluation, // see [ruby-core:17483]. break; } modify(); // See [ruby-core:17483] if (len < 0) { return this; } if (len > Integer.MAX_VALUE - beg) { throw getRuntime().newArgumentError("argument too big"); } end = beg + len; if (end > realLength) { if (end >= values.length) realloc(end); realLength = end; } if (block.isGiven()) { Ruby runtime = getRuntime(); for (int i = beg; i < end; i++) { IRubyObject v = block.yield(context, runtime.newFixnum(i)); if (i >= realLength) break; try { values[i] = v; } catch (ArrayIndexOutOfBoundsException e) { concurrentModification(); } } } return this; }
public IRubyObject fill(ThreadContext context, IRubyObject[] args, Block block) { IRubyObject item = null; IRubyObject begObj = null; IRubyObject lenObj = null; int argc = args.length; if (block.isGiven()) { Arity.checkArgumentCount(getRuntime(), args, 0, 2); item = null; begObj = argc > 0 ? args[0] : null; lenObj = argc > 1 ? args[1] : null; argc++; } else { Arity.checkArgumentCount(getRuntime(), args, 1, 3); item = args[0]; begObj = argc > 1 ? args[1] : null; lenObj = argc > 2 ? args[2] : null; } int beg = 0, end = 0, len = 0; switch (argc) { case 1: beg = 0; len = realLength; break; case 2: if (begObj instanceof RubyRange) { long[] beglen = ((RubyRange) begObj).begLen(realLength, 1); beg = (int) beglen[0]; len = (int) beglen[1]; break; } /* fall through */ case 3: beg = begObj.isNil() ? 0 : RubyNumeric.num2int(begObj); if (beg < 0) { beg = realLength + beg; if (beg < 0) beg = 0; } len = (lenObj == null || lenObj.isNil()) ? realLength - beg : RubyNumeric.num2int(lenObj); // TODO: In MRI 1.9, an explicit check for negative length is // added here. IndexError is raised when length is negative. // See [ruby-core:12953] for more details. // // New note: This is actually under re-evaluation, // see [ruby-core:17483]. break; } modify(); // See [ruby-core:17483] if (len < 0) { return this; } if (len > Integer.MAX_VALUE - beg) { throw getRuntime().newArgumentError("argument too big"); } end = beg + len; if (end > realLength) { if (end >= values.length) realloc(end); realLength = end; } if (block.isGiven()) { Ruby runtime = getRuntime(); for (int i = beg; i < end; i++) { IRubyObject v = block.yield(context, runtime.newFixnum(i)); if (i >= realLength) break; try { values[i] = v; } catch (ArrayIndexOutOfBoundsException e) { concurrentModification(); } } } else { if (len > 0) { try { Arrays.fill(values, beg, beg + len, item); } catch (ArrayIndexOutOfBoundsException e) { concurrentModification(); } } } return this; }
diff --git a/java/de/hattrickorganizer/gui/transferscout/PlayerConverter.java b/java/de/hattrickorganizer/gui/transferscout/PlayerConverter.java index 36e77521..02cb80c7 100644 --- a/java/de/hattrickorganizer/gui/transferscout/PlayerConverter.java +++ b/java/de/hattrickorganizer/gui/transferscout/PlayerConverter.java @@ -1,813 +1,824 @@ // %1329240092:de.hattrickorganizer.gui.transferscout% package de.hattrickorganizer.gui.transferscout; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import de.hattrickorganizer.model.HOVerwaltung; /** * Parses a player out of a text copied from HT. Tries also to give error informations but this may * be wrong! * * @author Marco Senn */ public class PlayerConverter { //~ Instance fields ---------------------------------------------------------------------------- /** List of all 21 ratings for the active language */ private List skills; private List skillvalues; private List specialities; private List specialitiesvalues; private int error; final HOVerwaltung homodel = HOVerwaltung.instance(); //~ Constructors ------------------------------------------------------------------------------- /** * We prepare our skill and specialities and sort them */ public PlayerConverter() { // Get all skills for active language // This should be the same language as in Hattrick skills = new ArrayList(); skills.add(homodel.getResource().getProperty("nonexisting").toLowerCase()); skills.add(homodel.getResource().getProperty("katastrophal").toLowerCase()); skills.add(homodel.getResource().getProperty("erbaermlich").toLowerCase()); skills.add(homodel.getResource().getProperty("armselig").toLowerCase()); skills.add(homodel.getResource().getProperty("schwach").toLowerCase()); skills.add(homodel.getResource().getProperty("durchschnittlich").toLowerCase()); skills.add(homodel.getResource().getProperty("passabel").toLowerCase()); skills.add(homodel.getResource().getProperty("gut").toLowerCase()); skills.add(homodel.getResource().getProperty("sehr_gut").toLowerCase()); skills.add(homodel.getResource().getProperty("hervorragend").toLowerCase()); skills.add(homodel.getResource().getProperty("grossartig").toLowerCase()); skills.add(homodel.getResource().getProperty("brilliant").toLowerCase()); skills.add(homodel.getResource().getProperty("fantastisch").toLowerCase()); skills.add(homodel.getResource().getProperty("Weltklasse").toLowerCase()); skills.add(homodel.getResource().getProperty("uebernatuerlich").toLowerCase()); skills.add(homodel.getResource().getProperty("gigantisch").toLowerCase()); skills.add(homodel.getResource().getProperty("ausserirdisch").toLowerCase()); skills.add(homodel.getResource().getProperty("mythisch").toLowerCase()); skills.add(homodel.getResource().getProperty("maerchenhaft").toLowerCase()); skills.add(homodel.getResource().getProperty("galaktisch").toLowerCase()); skills.add(homodel.getResource().getProperty("goettlich").toLowerCase()); skillvalues = new ArrayList(); for (int k = 0; k < skills.size(); k++) { skillvalues.add(new Integer(k)); } // Sort skills by length (shortest first) int p = skills.size() - 1; while (p > 0) { int k = p; while ((k < skills.size()) && (skills.get(k - 1).toString().length() > skills.get(k).toString().length())) { final String t = skills.get(k - 1).toString(); skills.set(k - 1, skills.get(k).toString()); skills.set(k, t); final Integer i = (Integer) skillvalues.get(k - 1); skillvalues.set(k - 1, (Integer) skillvalues.get(k)); skillvalues.set(k, i); k++; } p--; } // Get all specialities for active language // This should be the same language as in Hattrick specialities = new ArrayList(); specialities.add(homodel.getResource().getProperty("sp_Technical").toLowerCase()); specialities.add(homodel.getResource().getProperty("sp_Quick").toLowerCase()); specialities.add(homodel.getResource().getProperty("sp_Powerful").toLowerCase()); specialities.add(homodel.getResource().getProperty("sp_Unpredictable").toLowerCase()); specialities.add(homodel.getResource().getProperty("sp_Head").toLowerCase()); specialities.add(homodel.getResource().getProperty("sp_Regainer").toLowerCase()); specialitiesvalues = new ArrayList(); for (int k = 0; k < 6; k++) { specialitiesvalues.add(new Integer(k)); } // Sort specialities by length (shortest first) p = specialities.size() - 1; while (p > 0) { int k = p; while ((k < specialities.size()) && (specialities.get(k - 1).toString().length() > specialities.get(k).toString() .length())) { final String t = specialities.get(k - 1).toString(); specialities.set(k - 1, specialities.get(k).toString()); specialities.set(k, t); final Integer i = (Integer) specialitiesvalues.get(k - 1); specialitiesvalues.set(k - 1, (Integer) specialitiesvalues.get(k)); specialitiesvalues.set(k, i); k++; } p--; } } //~ Methods ------------------------------------------------------------------------------------ /** * Returns possible error. If error is nonzero, there was a problem. * * @return Returns possible error */ public final int getError() { return error; } /** * Parses the copied text and returns a Player Object * * @param text the copied text from HT site * * @return Player a Player object * * @throws Exception Throws exception on some parse errors */ public final Player build(String text) throws Exception { error = 0; final Player player = new Player(); // Init some helper variables String mytext = text; final List lines = new ArrayList(); int p = -1; String tmp = ""; // Detect linefeed // \n will do for linux and windows // \r is for mac String feed = ""; if (text.indexOf("\n") >= 0) { feed = "\n"; } else { if (text.indexOf("\r") >= 0) { feed = "\r"; } } // If we detected some possible player if (!feed.equals("")) { // // We start reformating given input here and extracting // only needed lines for player detection // // Delete empty lines from input String txt = text; boolean startFound = false; while ((p = txt.indexOf(feed)) >= 0) { tmp = txt.substring(0, p).trim(); if (tmp.indexOf("�") > 0) { startFound = true; } if (!tmp.equals("") && startFound) { lines.add(tmp); } txt = txt.substring(p + 1); } //-- get name and store club name tmp = lines.get(0).toString(); player.setPlayerName(tmp.substring(tmp.indexOf("�")+1).trim()); String teamname = tmp.substring(0, tmp.indexOf("�")).trim(); //-- get playerid int found_at_line = -1; + int n = 0; for (int m = 0; m<10; m++) { tmp = lines.get(m).toString(); try { - if (tmp.indexOf("(") > -1 && tmp.indexOf(")") > -1 && Integer.parseInt(tmp.substring(tmp.indexOf("(")+1, tmp.indexOf(")")).trim()) > 100000) { + if ((p = tmp.indexOf("(")) > -1 && (n = tmp.indexOf(")")) > -1 && Integer.parseInt(tmp.substring(tmp.indexOf("(")+1, tmp.indexOf(")")).trim()) > 100000) { player.setPlayerID(Integer.parseInt(tmp.substring(tmp.indexOf("(")+1, tmp.indexOf(")")).trim())); found_at_line = m; break; } + } catch (Exception e) { + if (p < 0) continue; + } + try { + // handle categories: Player Name (TW) (123456789) + if (tmp.indexOf("(", p+1) > -1 && tmp.indexOf(")", n+1) > -1 && Integer.parseInt(tmp.substring(tmp.indexOf("(", p+1)+1, tmp.indexOf(")", n+1)).trim()) > 100000) { + player.setPlayerID(Integer.parseInt(tmp.substring(tmp.indexOf("(", p+1)+1, tmp.indexOf(")", n+1)).trim())); + found_at_line = m; + break; + } } catch (Exception e) { continue; } } //-- get age tmp = lines.get(found_at_line + 1).toString(); String age = ""; p = 0; - int n = 0; + n = 0; while (p < tmp.length()) { if ((tmp.charAt(p) < '0') || (tmp.charAt(p) > '9')) { n++; } else { tmp = tmp.substring(n); break; } p++; } p = 0; while (p < tmp.length()) { if ((tmp.charAt(p) >= '0') && (tmp.charAt(p) <= '9')) { age = age + tmp.charAt(p); } else { break; } p++; } if (!age.equals("")) { player.setAge(Integer.valueOf(age).intValue()); } else { error = 2; } //-- get ageDays int ageIndex = tmp.indexOf(age) + age.length(); tmp = tmp.substring(ageIndex); String ageDays = ""; p = 0; n = 0; while (p < tmp.length()) { if ((tmp.charAt(p) < '0') || (tmp.charAt(p) > '9')) { n++; } else { tmp = tmp.substring(n); break; } p++; } p = 0; while (p < tmp.length()) { if ((tmp.charAt(p) >= '0') && (tmp.charAt(p) <= '9')) { ageDays = ageDays + tmp.charAt(p); } else { break; } p++; } if (!ageDays.equals("")) { player.setAgeDays(Integer.valueOf(ageDays).intValue()); } else { error = 2; } // clean lines till here if (found_at_line > 0) { for (int m=0; m<=(found_at_line+1); m++) { lines.remove(0); } } // remove club line and all lines until the time info (e.g. "since 06.04.2008") boolean teamfound = false; boolean datefound = false; for (int m = 0; m<12; m++) { tmp = lines.get(m).toString(); if (tmp.indexOf(teamname)>-1) { teamfound = true; } if (teamfound && !datefound) { lines.remove(m); m--; } if (teamfound && tmp.indexOf("(")>-1 && tmp.indexOf(")")>-1) { datefound = true; break; } } // Extract TSI-line p = 2; while (p < lines.size()) { //Search for TSI-line (ending in numbers) tmp = lines.get(p).toString(); if ((tmp.charAt(tmp.length() - 1) >= '0') && (tmp.charAt(tmp.length() - 1) <= '9') ) { if (tmp.length()>9 && tmp.substring(tmp.length()-9, tmp.length()).indexOf(".")>-1) { p++; continue; } found_at_line = p; break; } p++; } //-- get tsi String tsi = ""; p = 0; while (p < tmp.length()) { if ((tmp.charAt(p) >= '0') && (tmp.charAt(p) <= '9')) { tsi = tsi + tmp.charAt(p); } p++; } if (!tsi.equals("")) { player.setTSI(Integer.valueOf(tsi).intValue()); } else { error = 2; } //-- check bookings tmp = lines.get(found_at_line+2).toString(); try { if (tmp.indexOf(":") > -1 && tmp.indexOf("0") == -1) { player.setBooked(tmp); } } catch (Exception e) { /* ignore */ } //-- Get injury tmp = lines.get(found_at_line+3).toString(); try { String injury = ""; for (int j = 0; j < tmp.length(); j++) { if ((tmp.charAt(j) >= '0') && (tmp.charAt(j) <= '9') && (tmp.charAt(j-1) != '[')) { injury = String.valueOf(tmp.charAt(j)); break; } } if (!injury.equals("")) { player.setInjury(Integer.valueOf(injury).intValue()); } } catch (Exception e) { /* ignore */ } // Search for actual year (expires) and also next year // (end of year problem) final Date d = new Date(); SimpleDateFormat f = new SimpleDateFormat("yyyy"); final String year = f.format(d); final String year2 = String.valueOf((Integer.parseInt(year)+1)); p = 0; for (int m = 6; m < 8; m++) { // Delete all rows not containing our year tmp = lines.get(m).toString(); if (p > 10) { // already 10 lines deleted - there must be something wrong, break break; } if ((tmp.indexOf(year) > -1) || (tmp.indexOf(year2) > -1)) { found_at_line = m; break; } else { lines.remove(m); m--; p++; } } String exp = getDeadlineString(tmp); // Extract minimal bid tmp = lines.get(found_at_line+1).toString(); n = 0; int k = 0; String bid = ""; while (k < tmp.length()) { if ((tmp.charAt(k) < '0') || (tmp.charAt(k) > '9')) { n++; } else { tmp = tmp.substring(n); break; } k++; } k = 0; while (k < tmp.length()) { if ((tmp.charAt(k) >= '0') && (tmp.charAt(k) <= '9')) { bid += tmp.charAt(k); } k++; } // Extract current bid if any tmp = lines.get(found_at_line + 2).toString(); n = 0; k = 0; String curbid = ""; while (k < tmp.length()) { if ((tmp.charAt(k) < '0') || (tmp.charAt(k) > '9')) { n++; } else { tmp = tmp.substring(n); break; } k++; } k = 0; while (k < tmp.length()) { if ((tmp.charAt(k) >= '0') && (tmp.charAt(k) <= '9')) { curbid += tmp.charAt(k); } else if ((tmp.charAt(k) != ' ') && curbid.length()>0) { // avoid to add numbers from bidding team names break; } k++; } player.setPrice(getPrice(bid, curbid)); //-------------------------------------------- // exp is of format: ddmmyyyyhhmm try { player.setExpiryDate(exp.substring(0, 2) + "." + exp.substring(2, 4) + "." + exp.substring(6, 8)); player.setExpiryTime(exp.substring(8, 10) + ":" + exp.substring(10, 12)); } catch (RuntimeException e) { // error getting deadline - just set current date f = new SimpleDateFormat("dd.MM.yyyy"); player.setExpiryDate(f.format(new Date())); f = new SimpleDateFormat("HH:mm"); player.setExpiryTime(f.format(new Date())); if (error == 0) { error = 1; } } // truncate text from player name to date (year) final String name = player.getPlayerName(); if ((p = mytext.indexOf(name)) >= 0) { mytext = mytext.substring(p + name.length()); } if ((p = mytext.indexOf(name)) >= 0) { mytext = mytext.substring(p); } char[] cs = new char[teamname.length()]; for (int cl = 0; cl < cs.length; cl++) { cs[cl] = '*'; } mytext = mytext.replaceAll(teamname, new String(cs)).toLowerCase(); cs = new char[name.length()]; for (int cl = 0; cl < cs.length; cl++) { cs[cl] = '*'; } mytext = mytext.replaceAll(name.toLowerCase(), new String(cs)).toLowerCase(); // We can search all the skills in text now p = skills.size() - 1; final List foundskills = new ArrayList(); while (p >= 0) { final String singleskill = skills.get(p).toString(); k = mytext.indexOf(singleskill); if (k >= 0) { final List pair = new ArrayList(); pair.add(new Integer(k)); pair.add(singleskill); pair.add(new Integer(p)); foundskills.add(pair); final char[] ct = new char[singleskill.length()]; for (int cl = 0; cl < ct.length; cl++) { ct[cl] = '*'; } mytext = mytext.replaceFirst(singleskill, new String(ct)); } else { p--; } } - if ((foundskills.size() != 11) && (error == 0)) { + if ((foundskills.size() < 11) && (error == 0)) { error = 1; } // Sort skills by location p = foundskills.size() - 1; while (p > 0) { k = p; while (k < foundskills.size()) { final List ts1 = (ArrayList) foundskills.get(k - 1); final List ts2 = (ArrayList) foundskills.get(k); if (((Integer) ts1.get(0)).intValue() > ((Integer) ts2.get(0)).intValue()) { foundskills.set(k - 1, ts2); foundskills.set(k, ts1); k++; } else { break; } } p--; } // check format try { p = mytext.indexOf("/20"); if (p > -1 && mytext.indexOf("/20", p+5) > -1 && foundskills.size() >= 11) { // player skills (long default format with bars) player.setForm(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(0)).get(2)).intValue())).intValue()); player.setStamina(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(1)).get(2)).intValue())).intValue()); player.setExperience(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(2)).get(2)).intValue())).intValue()); player.setLeadership(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(3)).get(2)).intValue())).intValue()); player.setGoalKeeping(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(4)).get(2)).intValue())).intValue()); player.setDefense(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(5)).get(2)).intValue())).intValue()); player.setPlayMaking(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(6)).get(2)).intValue())).intValue()); player.setWing(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(7)).get(2)).intValue())).intValue()); player.setPassing(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(8)).get(2)).intValue())).intValue()); player.setAttack(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(9)).get(2)).intValue())).intValue()); player.setSetPieces(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(10)).get(2)).intValue())).intValue()); } else if (foundskills.size() >= 12) { // player skills (2er format without bars) player.setForm(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(0)).get(2)).intValue())).intValue()); player.setStamina(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(1)).get(2)).intValue())).intValue()); player.setExperience(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(2)).get(2)).intValue())).intValue()); player.setLeadership(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(3)).get(2)).intValue())).intValue()); player.setGoalKeeping(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(5)).get(2)).intValue())).intValue()); player.setDefense(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(9)).get(2)).intValue())).intValue()); player.setPlayMaking(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(6)).get(2)).intValue())).intValue()); player.setWing(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(8)).get(2)).intValue())).intValue()); player.setPassing(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(7)).get(2)).intValue())).intValue()); player.setAttack(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(10)).get(2)).intValue())).intValue()); player.setSetPieces(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(11)).get(2)).intValue())).intValue()); } } catch (RuntimeException e) { error = 2; } // We can search the speciality in text now p = specialities.size() - 1; final List foundspecialities = new ArrayList(); while (p >= 0) { final String singlespeciality = specialities.get(p).toString(); k = mytext.indexOf(singlespeciality); if (k >= 0) { final List pair = new ArrayList(); pair.add(new Integer(k)); pair.add(singlespeciality); pair.add(new Integer(p)); foundspecialities.add(pair); final char[] ct = new char[singlespeciality.length()]; for (int cl = 0; cl < ct.length; cl++) { ct[cl] = '*'; } mytext = mytext.replaceFirst(singlespeciality, new String(ct)); } else { p--; } } if ((foundspecialities.size() > 1) && (error == 0)) { error = 1; } // Sort specialities by location p = foundspecialities.size() - 1; while (p > 0) { k = p; while (k < foundspecialities.size()) { final List ts1 = (ArrayList) foundspecialities.get(k - 1); final List ts2 = (ArrayList) foundspecialities.get(k); if (((Integer) ts1.get(0)).intValue() > ((Integer) ts2.get(0)).intValue()) { foundspecialities.set(k - 1, ts2); foundspecialities.set(k, ts1); k++; } else { break; } } p--; } if (foundspecialities.size() > 0) { player.setSpeciality(((Integer) specialitiesvalues.get(((Integer) ((ArrayList) foundspecialities.get(0)).get(2)).intValue())).intValue() + 1); } else { player.setSpeciality(0); } } return player; } public static int getPrice(String bid, String curbid) { int price = 0; try { price = Integer.parseInt(bid); if (curbid.length()>0 && Integer.parseInt(curbid) >= Integer.parseInt(bid)) { price = Integer.parseInt(curbid); } } catch (Exception e) { /* nothing */ } return price; } public static String getDeadlineString(String tmp) { // get deadline String exp = ""; int p = 0; int k = 0; while (p < tmp.length()) { if ((tmp.charAt(p) < '0') || (tmp.charAt(p) > '9')) { k++; } else { tmp = tmp.substring(k); break; } p++; } p = 0; k = 0; String part1 = ""; while (p < tmp.length()) { if ((tmp.charAt(p) >= '0') && (tmp.charAt(p) <= '9')) { k++; } else { part1 = tmp.substring(0, k); if (part1.length() < 2) { part1 = "0" + part1; } tmp = tmp.substring(k + 1); break; } p++; } p = 0; k = 0; String part2 = ""; while (p < tmp.length()) { if ((tmp.charAt(p) >= '0') && (tmp.charAt(p) <= '9')) { k++; } else { part2 = tmp.substring(0, k); if (part2.length() < 2) { part2 = "0" + part2; } tmp = tmp.substring(k + 1); break; } p++; } p = 0; k = 0; String part3 = ""; while (p < tmp.length()) { if ((tmp.charAt(p) >= '0') && (tmp.charAt(p) <= '9')) { k++; } else { part3 = tmp.substring(0, k); if (part3.length() < 2) { part3 = "0" + part3; } tmp = tmp.substring(k + 1); break; } p++; } p = 0; String part4 = ""; while (p < tmp.length()) { if ((tmp.charAt(p) >= '0') && (tmp.charAt(p) <= '9')) { part4 = part4 + tmp.charAt(p); } p++; } final Calendar c = Calendar.getInstance(); SimpleDateFormat f = new SimpleDateFormat("ddMMyyyy"); final Date d1 = c.getTime(); final String date1 = f.format(d1); c.add(Calendar.DATE, 1); final Date d2 = c.getTime(); final String date2 = f.format(d2); c.add(Calendar.DATE, 1); final Date d3 = c.getTime(); final String date3 = f.format(d3); String date = part1 + part2 + part3; if ((date1.equals(date)) || (date2.equals(date)) || (date3.equals(date))) { exp = date + part4; } else { date = part1 + part3 + part2; if ((date1.equals(date)) || (date2.equals(date)) || (date3.equals(date))) { exp = date + part4; } else { date = part2 + part1 + part3; if ((date1.equals(date)) || (date2.equals(date)) || (date3.equals(date))) { exp = date + part4; } else { date = part2 + part3 + part1; if ((date1.equals(date)) || (date2.equals(date)) || (date3.equals(date))) { exp = date + part4; } else { date = part3 + part1 + part2; if ((date1.equals(date)) || (date2.equals(date)) || (date3.equals(date))) { exp = date + part4; } else { date = part3 + part2 + part1; if ((date1.equals(date)) || (date2.equals(date)) || (date3.equals(date))) { exp = date + part4; } else { exp = part1 + part2 + part3 + part4; } } } } } } return exp; } }
false
true
public final Player build(String text) throws Exception { error = 0; final Player player = new Player(); // Init some helper variables String mytext = text; final List lines = new ArrayList(); int p = -1; String tmp = ""; // Detect linefeed // \n will do for linux and windows // \r is for mac String feed = ""; if (text.indexOf("\n") >= 0) { feed = "\n"; } else { if (text.indexOf("\r") >= 0) { feed = "\r"; } } // If we detected some possible player if (!feed.equals("")) { // // We start reformating given input here and extracting // only needed lines for player detection // // Delete empty lines from input String txt = text; boolean startFound = false; while ((p = txt.indexOf(feed)) >= 0) { tmp = txt.substring(0, p).trim(); if (tmp.indexOf("�") > 0) { startFound = true; } if (!tmp.equals("") && startFound) { lines.add(tmp); } txt = txt.substring(p + 1); } //-- get name and store club name tmp = lines.get(0).toString(); player.setPlayerName(tmp.substring(tmp.indexOf("�")+1).trim()); String teamname = tmp.substring(0, tmp.indexOf("�")).trim(); //-- get playerid int found_at_line = -1; for (int m = 0; m<10; m++) { tmp = lines.get(m).toString(); try { if (tmp.indexOf("(") > -1 && tmp.indexOf(")") > -1 && Integer.parseInt(tmp.substring(tmp.indexOf("(")+1, tmp.indexOf(")")).trim()) > 100000) { player.setPlayerID(Integer.parseInt(tmp.substring(tmp.indexOf("(")+1, tmp.indexOf(")")).trim())); found_at_line = m; break; } } catch (Exception e) { continue; } } //-- get age tmp = lines.get(found_at_line + 1).toString(); String age = ""; p = 0; int n = 0; while (p < tmp.length()) { if ((tmp.charAt(p) < '0') || (tmp.charAt(p) > '9')) { n++; } else { tmp = tmp.substring(n); break; } p++; } p = 0; while (p < tmp.length()) { if ((tmp.charAt(p) >= '0') && (tmp.charAt(p) <= '9')) { age = age + tmp.charAt(p); } else { break; } p++; } if (!age.equals("")) { player.setAge(Integer.valueOf(age).intValue()); } else { error = 2; } //-- get ageDays int ageIndex = tmp.indexOf(age) + age.length(); tmp = tmp.substring(ageIndex); String ageDays = ""; p = 0; n = 0; while (p < tmp.length()) { if ((tmp.charAt(p) < '0') || (tmp.charAt(p) > '9')) { n++; } else { tmp = tmp.substring(n); break; } p++; } p = 0; while (p < tmp.length()) { if ((tmp.charAt(p) >= '0') && (tmp.charAt(p) <= '9')) { ageDays = ageDays + tmp.charAt(p); } else { break; } p++; } if (!ageDays.equals("")) { player.setAgeDays(Integer.valueOf(ageDays).intValue()); } else { error = 2; } // clean lines till here if (found_at_line > 0) { for (int m=0; m<=(found_at_line+1); m++) { lines.remove(0); } } // remove club line and all lines until the time info (e.g. "since 06.04.2008") boolean teamfound = false; boolean datefound = false; for (int m = 0; m<12; m++) { tmp = lines.get(m).toString(); if (tmp.indexOf(teamname)>-1) { teamfound = true; } if (teamfound && !datefound) { lines.remove(m); m--; } if (teamfound && tmp.indexOf("(")>-1 && tmp.indexOf(")")>-1) { datefound = true; break; } } // Extract TSI-line p = 2; while (p < lines.size()) { //Search for TSI-line (ending in numbers) tmp = lines.get(p).toString(); if ((tmp.charAt(tmp.length() - 1) >= '0') && (tmp.charAt(tmp.length() - 1) <= '9') ) { if (tmp.length()>9 && tmp.substring(tmp.length()-9, tmp.length()).indexOf(".")>-1) { p++; continue; } found_at_line = p; break; } p++; } //-- get tsi String tsi = ""; p = 0; while (p < tmp.length()) { if ((tmp.charAt(p) >= '0') && (tmp.charAt(p) <= '9')) { tsi = tsi + tmp.charAt(p); } p++; } if (!tsi.equals("")) { player.setTSI(Integer.valueOf(tsi).intValue()); } else { error = 2; } //-- check bookings tmp = lines.get(found_at_line+2).toString(); try { if (tmp.indexOf(":") > -1 && tmp.indexOf("0") == -1) { player.setBooked(tmp); } } catch (Exception e) { /* ignore */ } //-- Get injury tmp = lines.get(found_at_line+3).toString(); try { String injury = ""; for (int j = 0; j < tmp.length(); j++) { if ((tmp.charAt(j) >= '0') && (tmp.charAt(j) <= '9') && (tmp.charAt(j-1) != '[')) { injury = String.valueOf(tmp.charAt(j)); break; } } if (!injury.equals("")) { player.setInjury(Integer.valueOf(injury).intValue()); } } catch (Exception e) { /* ignore */ } // Search for actual year (expires) and also next year // (end of year problem) final Date d = new Date(); SimpleDateFormat f = new SimpleDateFormat("yyyy"); final String year = f.format(d); final String year2 = String.valueOf((Integer.parseInt(year)+1)); p = 0; for (int m = 6; m < 8; m++) { // Delete all rows not containing our year tmp = lines.get(m).toString(); if (p > 10) { // already 10 lines deleted - there must be something wrong, break break; } if ((tmp.indexOf(year) > -1) || (tmp.indexOf(year2) > -1)) { found_at_line = m; break; } else { lines.remove(m); m--; p++; } } String exp = getDeadlineString(tmp); // Extract minimal bid tmp = lines.get(found_at_line+1).toString(); n = 0; int k = 0; String bid = ""; while (k < tmp.length()) { if ((tmp.charAt(k) < '0') || (tmp.charAt(k) > '9')) { n++; } else { tmp = tmp.substring(n); break; } k++; } k = 0; while (k < tmp.length()) { if ((tmp.charAt(k) >= '0') && (tmp.charAt(k) <= '9')) { bid += tmp.charAt(k); } k++; } // Extract current bid if any tmp = lines.get(found_at_line + 2).toString(); n = 0; k = 0; String curbid = ""; while (k < tmp.length()) { if ((tmp.charAt(k) < '0') || (tmp.charAt(k) > '9')) { n++; } else { tmp = tmp.substring(n); break; } k++; } k = 0; while (k < tmp.length()) { if ((tmp.charAt(k) >= '0') && (tmp.charAt(k) <= '9')) { curbid += tmp.charAt(k); } else if ((tmp.charAt(k) != ' ') && curbid.length()>0) { // avoid to add numbers from bidding team names break; } k++; } player.setPrice(getPrice(bid, curbid)); //-------------------------------------------- // exp is of format: ddmmyyyyhhmm try { player.setExpiryDate(exp.substring(0, 2) + "." + exp.substring(2, 4) + "." + exp.substring(6, 8)); player.setExpiryTime(exp.substring(8, 10) + ":" + exp.substring(10, 12)); } catch (RuntimeException e) { // error getting deadline - just set current date f = new SimpleDateFormat("dd.MM.yyyy"); player.setExpiryDate(f.format(new Date())); f = new SimpleDateFormat("HH:mm"); player.setExpiryTime(f.format(new Date())); if (error == 0) { error = 1; } } // truncate text from player name to date (year) final String name = player.getPlayerName(); if ((p = mytext.indexOf(name)) >= 0) { mytext = mytext.substring(p + name.length()); } if ((p = mytext.indexOf(name)) >= 0) { mytext = mytext.substring(p); } char[] cs = new char[teamname.length()]; for (int cl = 0; cl < cs.length; cl++) { cs[cl] = '*'; } mytext = mytext.replaceAll(teamname, new String(cs)).toLowerCase(); cs = new char[name.length()]; for (int cl = 0; cl < cs.length; cl++) { cs[cl] = '*'; } mytext = mytext.replaceAll(name.toLowerCase(), new String(cs)).toLowerCase(); // We can search all the skills in text now p = skills.size() - 1; final List foundskills = new ArrayList(); while (p >= 0) { final String singleskill = skills.get(p).toString(); k = mytext.indexOf(singleskill); if (k >= 0) { final List pair = new ArrayList(); pair.add(new Integer(k)); pair.add(singleskill); pair.add(new Integer(p)); foundskills.add(pair); final char[] ct = new char[singleskill.length()]; for (int cl = 0; cl < ct.length; cl++) { ct[cl] = '*'; } mytext = mytext.replaceFirst(singleskill, new String(ct)); } else { p--; } } if ((foundskills.size() != 11) && (error == 0)) { error = 1; } // Sort skills by location p = foundskills.size() - 1; while (p > 0) { k = p; while (k < foundskills.size()) { final List ts1 = (ArrayList) foundskills.get(k - 1); final List ts2 = (ArrayList) foundskills.get(k); if (((Integer) ts1.get(0)).intValue() > ((Integer) ts2.get(0)).intValue()) { foundskills.set(k - 1, ts2); foundskills.set(k, ts1); k++; } else { break; } } p--; } // check format try { p = mytext.indexOf("/20"); if (p > -1 && mytext.indexOf("/20", p+5) > -1 && foundskills.size() >= 11) { // player skills (long default format with bars) player.setForm(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(0)).get(2)).intValue())).intValue()); player.setStamina(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(1)).get(2)).intValue())).intValue()); player.setExperience(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(2)).get(2)).intValue())).intValue()); player.setLeadership(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(3)).get(2)).intValue())).intValue()); player.setGoalKeeping(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(4)).get(2)).intValue())).intValue()); player.setDefense(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(5)).get(2)).intValue())).intValue()); player.setPlayMaking(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(6)).get(2)).intValue())).intValue()); player.setWing(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(7)).get(2)).intValue())).intValue()); player.setPassing(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(8)).get(2)).intValue())).intValue()); player.setAttack(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(9)).get(2)).intValue())).intValue()); player.setSetPieces(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(10)).get(2)).intValue())).intValue()); } else if (foundskills.size() >= 12) { // player skills (2er format without bars) player.setForm(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(0)).get(2)).intValue())).intValue()); player.setStamina(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(1)).get(2)).intValue())).intValue()); player.setExperience(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(2)).get(2)).intValue())).intValue()); player.setLeadership(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(3)).get(2)).intValue())).intValue()); player.setGoalKeeping(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(5)).get(2)).intValue())).intValue()); player.setDefense(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(9)).get(2)).intValue())).intValue()); player.setPlayMaking(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(6)).get(2)).intValue())).intValue()); player.setWing(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(8)).get(2)).intValue())).intValue()); player.setPassing(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(7)).get(2)).intValue())).intValue()); player.setAttack(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(10)).get(2)).intValue())).intValue()); player.setSetPieces(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(11)).get(2)).intValue())).intValue()); } } catch (RuntimeException e) { error = 2; } // We can search the speciality in text now p = specialities.size() - 1; final List foundspecialities = new ArrayList(); while (p >= 0) { final String singlespeciality = specialities.get(p).toString(); k = mytext.indexOf(singlespeciality); if (k >= 0) { final List pair = new ArrayList(); pair.add(new Integer(k)); pair.add(singlespeciality); pair.add(new Integer(p)); foundspecialities.add(pair); final char[] ct = new char[singlespeciality.length()]; for (int cl = 0; cl < ct.length; cl++) { ct[cl] = '*'; } mytext = mytext.replaceFirst(singlespeciality, new String(ct)); } else { p--; } } if ((foundspecialities.size() > 1) && (error == 0)) { error = 1; } // Sort specialities by location p = foundspecialities.size() - 1; while (p > 0) { k = p; while (k < foundspecialities.size()) { final List ts1 = (ArrayList) foundspecialities.get(k - 1); final List ts2 = (ArrayList) foundspecialities.get(k); if (((Integer) ts1.get(0)).intValue() > ((Integer) ts2.get(0)).intValue()) { foundspecialities.set(k - 1, ts2); foundspecialities.set(k, ts1); k++; } else { break; } } p--; } if (foundspecialities.size() > 0) { player.setSpeciality(((Integer) specialitiesvalues.get(((Integer) ((ArrayList) foundspecialities.get(0)).get(2)).intValue())).intValue() + 1); } else { player.setSpeciality(0); } } return player; }
public final Player build(String text) throws Exception { error = 0; final Player player = new Player(); // Init some helper variables String mytext = text; final List lines = new ArrayList(); int p = -1; String tmp = ""; // Detect linefeed // \n will do for linux and windows // \r is for mac String feed = ""; if (text.indexOf("\n") >= 0) { feed = "\n"; } else { if (text.indexOf("\r") >= 0) { feed = "\r"; } } // If we detected some possible player if (!feed.equals("")) { // // We start reformating given input here and extracting // only needed lines for player detection // // Delete empty lines from input String txt = text; boolean startFound = false; while ((p = txt.indexOf(feed)) >= 0) { tmp = txt.substring(0, p).trim(); if (tmp.indexOf("�") > 0) { startFound = true; } if (!tmp.equals("") && startFound) { lines.add(tmp); } txt = txt.substring(p + 1); } //-- get name and store club name tmp = lines.get(0).toString(); player.setPlayerName(tmp.substring(tmp.indexOf("�")+1).trim()); String teamname = tmp.substring(0, tmp.indexOf("�")).trim(); //-- get playerid int found_at_line = -1; int n = 0; for (int m = 0; m<10; m++) { tmp = lines.get(m).toString(); try { if ((p = tmp.indexOf("(")) > -1 && (n = tmp.indexOf(")")) > -1 && Integer.parseInt(tmp.substring(tmp.indexOf("(")+1, tmp.indexOf(")")).trim()) > 100000) { player.setPlayerID(Integer.parseInt(tmp.substring(tmp.indexOf("(")+1, tmp.indexOf(")")).trim())); found_at_line = m; break; } } catch (Exception e) { if (p < 0) continue; } try { // handle categories: Player Name (TW) (123456789) if (tmp.indexOf("(", p+1) > -1 && tmp.indexOf(")", n+1) > -1 && Integer.parseInt(tmp.substring(tmp.indexOf("(", p+1)+1, tmp.indexOf(")", n+1)).trim()) > 100000) { player.setPlayerID(Integer.parseInt(tmp.substring(tmp.indexOf("(", p+1)+1, tmp.indexOf(")", n+1)).trim())); found_at_line = m; break; } } catch (Exception e) { continue; } } //-- get age tmp = lines.get(found_at_line + 1).toString(); String age = ""; p = 0; n = 0; while (p < tmp.length()) { if ((tmp.charAt(p) < '0') || (tmp.charAt(p) > '9')) { n++; } else { tmp = tmp.substring(n); break; } p++; } p = 0; while (p < tmp.length()) { if ((tmp.charAt(p) >= '0') && (tmp.charAt(p) <= '9')) { age = age + tmp.charAt(p); } else { break; } p++; } if (!age.equals("")) { player.setAge(Integer.valueOf(age).intValue()); } else { error = 2; } //-- get ageDays int ageIndex = tmp.indexOf(age) + age.length(); tmp = tmp.substring(ageIndex); String ageDays = ""; p = 0; n = 0; while (p < tmp.length()) { if ((tmp.charAt(p) < '0') || (tmp.charAt(p) > '9')) { n++; } else { tmp = tmp.substring(n); break; } p++; } p = 0; while (p < tmp.length()) { if ((tmp.charAt(p) >= '0') && (tmp.charAt(p) <= '9')) { ageDays = ageDays + tmp.charAt(p); } else { break; } p++; } if (!ageDays.equals("")) { player.setAgeDays(Integer.valueOf(ageDays).intValue()); } else { error = 2; } // clean lines till here if (found_at_line > 0) { for (int m=0; m<=(found_at_line+1); m++) { lines.remove(0); } } // remove club line and all lines until the time info (e.g. "since 06.04.2008") boolean teamfound = false; boolean datefound = false; for (int m = 0; m<12; m++) { tmp = lines.get(m).toString(); if (tmp.indexOf(teamname)>-1) { teamfound = true; } if (teamfound && !datefound) { lines.remove(m); m--; } if (teamfound && tmp.indexOf("(")>-1 && tmp.indexOf(")")>-1) { datefound = true; break; } } // Extract TSI-line p = 2; while (p < lines.size()) { //Search for TSI-line (ending in numbers) tmp = lines.get(p).toString(); if ((tmp.charAt(tmp.length() - 1) >= '0') && (tmp.charAt(tmp.length() - 1) <= '9') ) { if (tmp.length()>9 && tmp.substring(tmp.length()-9, tmp.length()).indexOf(".")>-1) { p++; continue; } found_at_line = p; break; } p++; } //-- get tsi String tsi = ""; p = 0; while (p < tmp.length()) { if ((tmp.charAt(p) >= '0') && (tmp.charAt(p) <= '9')) { tsi = tsi + tmp.charAt(p); } p++; } if (!tsi.equals("")) { player.setTSI(Integer.valueOf(tsi).intValue()); } else { error = 2; } //-- check bookings tmp = lines.get(found_at_line+2).toString(); try { if (tmp.indexOf(":") > -1 && tmp.indexOf("0") == -1) { player.setBooked(tmp); } } catch (Exception e) { /* ignore */ } //-- Get injury tmp = lines.get(found_at_line+3).toString(); try { String injury = ""; for (int j = 0; j < tmp.length(); j++) { if ((tmp.charAt(j) >= '0') && (tmp.charAt(j) <= '9') && (tmp.charAt(j-1) != '[')) { injury = String.valueOf(tmp.charAt(j)); break; } } if (!injury.equals("")) { player.setInjury(Integer.valueOf(injury).intValue()); } } catch (Exception e) { /* ignore */ } // Search for actual year (expires) and also next year // (end of year problem) final Date d = new Date(); SimpleDateFormat f = new SimpleDateFormat("yyyy"); final String year = f.format(d); final String year2 = String.valueOf((Integer.parseInt(year)+1)); p = 0; for (int m = 6; m < 8; m++) { // Delete all rows not containing our year tmp = lines.get(m).toString(); if (p > 10) { // already 10 lines deleted - there must be something wrong, break break; } if ((tmp.indexOf(year) > -1) || (tmp.indexOf(year2) > -1)) { found_at_line = m; break; } else { lines.remove(m); m--; p++; } } String exp = getDeadlineString(tmp); // Extract minimal bid tmp = lines.get(found_at_line+1).toString(); n = 0; int k = 0; String bid = ""; while (k < tmp.length()) { if ((tmp.charAt(k) < '0') || (tmp.charAt(k) > '9')) { n++; } else { tmp = tmp.substring(n); break; } k++; } k = 0; while (k < tmp.length()) { if ((tmp.charAt(k) >= '0') && (tmp.charAt(k) <= '9')) { bid += tmp.charAt(k); } k++; } // Extract current bid if any tmp = lines.get(found_at_line + 2).toString(); n = 0; k = 0; String curbid = ""; while (k < tmp.length()) { if ((tmp.charAt(k) < '0') || (tmp.charAt(k) > '9')) { n++; } else { tmp = tmp.substring(n); break; } k++; } k = 0; while (k < tmp.length()) { if ((tmp.charAt(k) >= '0') && (tmp.charAt(k) <= '9')) { curbid += tmp.charAt(k); } else if ((tmp.charAt(k) != ' ') && curbid.length()>0) { // avoid to add numbers from bidding team names break; } k++; } player.setPrice(getPrice(bid, curbid)); //-------------------------------------------- // exp is of format: ddmmyyyyhhmm try { player.setExpiryDate(exp.substring(0, 2) + "." + exp.substring(2, 4) + "." + exp.substring(6, 8)); player.setExpiryTime(exp.substring(8, 10) + ":" + exp.substring(10, 12)); } catch (RuntimeException e) { // error getting deadline - just set current date f = new SimpleDateFormat("dd.MM.yyyy"); player.setExpiryDate(f.format(new Date())); f = new SimpleDateFormat("HH:mm"); player.setExpiryTime(f.format(new Date())); if (error == 0) { error = 1; } } // truncate text from player name to date (year) final String name = player.getPlayerName(); if ((p = mytext.indexOf(name)) >= 0) { mytext = mytext.substring(p + name.length()); } if ((p = mytext.indexOf(name)) >= 0) { mytext = mytext.substring(p); } char[] cs = new char[teamname.length()]; for (int cl = 0; cl < cs.length; cl++) { cs[cl] = '*'; } mytext = mytext.replaceAll(teamname, new String(cs)).toLowerCase(); cs = new char[name.length()]; for (int cl = 0; cl < cs.length; cl++) { cs[cl] = '*'; } mytext = mytext.replaceAll(name.toLowerCase(), new String(cs)).toLowerCase(); // We can search all the skills in text now p = skills.size() - 1; final List foundskills = new ArrayList(); while (p >= 0) { final String singleskill = skills.get(p).toString(); k = mytext.indexOf(singleskill); if (k >= 0) { final List pair = new ArrayList(); pair.add(new Integer(k)); pair.add(singleskill); pair.add(new Integer(p)); foundskills.add(pair); final char[] ct = new char[singleskill.length()]; for (int cl = 0; cl < ct.length; cl++) { ct[cl] = '*'; } mytext = mytext.replaceFirst(singleskill, new String(ct)); } else { p--; } } if ((foundskills.size() < 11) && (error == 0)) { error = 1; } // Sort skills by location p = foundskills.size() - 1; while (p > 0) { k = p; while (k < foundskills.size()) { final List ts1 = (ArrayList) foundskills.get(k - 1); final List ts2 = (ArrayList) foundskills.get(k); if (((Integer) ts1.get(0)).intValue() > ((Integer) ts2.get(0)).intValue()) { foundskills.set(k - 1, ts2); foundskills.set(k, ts1); k++; } else { break; } } p--; } // check format try { p = mytext.indexOf("/20"); if (p > -1 && mytext.indexOf("/20", p+5) > -1 && foundskills.size() >= 11) { // player skills (long default format with bars) player.setForm(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(0)).get(2)).intValue())).intValue()); player.setStamina(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(1)).get(2)).intValue())).intValue()); player.setExperience(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(2)).get(2)).intValue())).intValue()); player.setLeadership(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(3)).get(2)).intValue())).intValue()); player.setGoalKeeping(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(4)).get(2)).intValue())).intValue()); player.setDefense(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(5)).get(2)).intValue())).intValue()); player.setPlayMaking(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(6)).get(2)).intValue())).intValue()); player.setWing(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(7)).get(2)).intValue())).intValue()); player.setPassing(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(8)).get(2)).intValue())).intValue()); player.setAttack(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(9)).get(2)).intValue())).intValue()); player.setSetPieces(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(10)).get(2)).intValue())).intValue()); } else if (foundskills.size() >= 12) { // player skills (2er format without bars) player.setForm(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(0)).get(2)).intValue())).intValue()); player.setStamina(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(1)).get(2)).intValue())).intValue()); player.setExperience(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(2)).get(2)).intValue())).intValue()); player.setLeadership(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(3)).get(2)).intValue())).intValue()); player.setGoalKeeping(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(5)).get(2)).intValue())).intValue()); player.setDefense(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(9)).get(2)).intValue())).intValue()); player.setPlayMaking(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(6)).get(2)).intValue())).intValue()); player.setWing(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(8)).get(2)).intValue())).intValue()); player.setPassing(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(7)).get(2)).intValue())).intValue()); player.setAttack(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(10)).get(2)).intValue())).intValue()); player.setSetPieces(((Integer) skillvalues.get(((Integer) ((ArrayList) foundskills.get(11)).get(2)).intValue())).intValue()); } } catch (RuntimeException e) { error = 2; } // We can search the speciality in text now p = specialities.size() - 1; final List foundspecialities = new ArrayList(); while (p >= 0) { final String singlespeciality = specialities.get(p).toString(); k = mytext.indexOf(singlespeciality); if (k >= 0) { final List pair = new ArrayList(); pair.add(new Integer(k)); pair.add(singlespeciality); pair.add(new Integer(p)); foundspecialities.add(pair); final char[] ct = new char[singlespeciality.length()]; for (int cl = 0; cl < ct.length; cl++) { ct[cl] = '*'; } mytext = mytext.replaceFirst(singlespeciality, new String(ct)); } else { p--; } } if ((foundspecialities.size() > 1) && (error == 0)) { error = 1; } // Sort specialities by location p = foundspecialities.size() - 1; while (p > 0) { k = p; while (k < foundspecialities.size()) { final List ts1 = (ArrayList) foundspecialities.get(k - 1); final List ts2 = (ArrayList) foundspecialities.get(k); if (((Integer) ts1.get(0)).intValue() > ((Integer) ts2.get(0)).intValue()) { foundspecialities.set(k - 1, ts2); foundspecialities.set(k, ts1); k++; } else { break; } } p--; } if (foundspecialities.size() > 0) { player.setSpeciality(((Integer) specialitiesvalues.get(((Integer) ((ArrayList) foundspecialities.get(0)).get(2)).intValue())).intValue() + 1); } else { player.setSpeciality(0); } } return player; }
diff --git a/src/test/java/algorithm/BinaryBehaviour.java b/src/test/java/algorithm/BinaryBehaviour.java index 8d4c76e..2224ac6 100644 --- a/src/test/java/algorithm/BinaryBehaviour.java +++ b/src/test/java/algorithm/BinaryBehaviour.java @@ -1,175 +1,175 @@ package algorithm; import org.apache.commons.math3.distribution.NormalDistribution; import crowdtrust.BinaryR; public class BinaryBehaviour { /* * Represents how biased the member is towards 0/1 1(low threshold) * 0 (low threshold) No bias if = 0 */ protected double threshold; /* * Represents how well the member can distinguish between the two classes of answer */ protected double sensitivityIndex; /* * Assumed in the paper */ protected int variance = 1; protected int standardDev = 1; /* * Records the members answering statistics used to calculate t, d and * therefore ukj */ protected int truePos; protected int trueNeg; protected int totalPos; protected int totalNeg; protected double truePosRate; protected double trueNegRate; /* * Seed the crowd memeber with these inital values from this the true positive * and negative rates can be calculated which are used to calculate the inital * t and d, if you seeded the member with a t and d and truepos/neg rates the * rates wouldn't actually reflect that t and d. */ public BinaryBehaviour(int truePos, int trueNeg, int totalPos, int totalNeg){ this.truePos = truePos ; this.trueNeg = trueNeg ; this.totalPos = totalPos; this.totalNeg = totalNeg; this.updateRates(); //Set up the inital true pos/neg rates // this.updateSensThresh(); //Set up the inital threshold and sensetivity index } public int generateAnswer(BinaryR response){ - int answer; + int realanswer; if (response.isTrue()){ - answer = 1; + realanswer = 1; }else{ - answer = 0; + realanswer = 0; } //update the sensory index and threshold for the calculation of ujk // this.updateRates(); this.updateSensThresh(); //generate ujk double ujk = calculateujk(response.isTrue() ? 1 : 0); //generate the appropriate normal distribution NormalDistribution dist = new NormalDistribution(ujk, this.standardDev); /* * generate a random number sampled from this distribution representing * the annotators signal */ double signal = dist.sample(); - System.out.println("Rate" + this.truePosRate + " Answer " + answer + " Signal " + signal ); + System.out.println("Rate" + this.truePosRate + " Answer " + realanswer + " Signal " + signal ); int answer = (Double.compare(signal, this.threshold) > 0) ? 1 : 0; //this.updateNumbers(answer, actualAnswer); //Update truePos/neg and totalpos/neg this.updateRates(); //Update truePos/negRates return answer; } /* * Update the total positive/negative answers and the true * positive/negative answers if they got it correct. */ private void updateNumbers(int answer, int actualAnswer){ if(actualAnswer == 1){ this.totalPos++; if(answer == 1){ this.truePos++; } }else{ this.totalNeg++; if(answer == 0){ this.trueNeg++; } } } //Calculates the new true pos/neg rates private void updateRates(){ //System.out.println("~~~~~~~~~~~~Calculating rates~~~~~~~~~~~~~"); //System.out.println("Total Pos: " + this.totalPos + " Total neg " + this.totalNeg); //System.out.println("True Pos: " + this.truePos + " true neg " + this.trueNeg); //System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); this.truePosRate = ((this.truePos * 1.0) / (this.totalPos * 1.0)); this.trueNegRate = ((this.trueNeg * 1.0) / (this.totalNeg * 1.0)); } /* * |1 1/2| |t| | inv(aj0) | * |1 -1/2| = |d| | inv(1 - aj1) | * * From this... * * t + d/2 = inv(aj0) * t - d/2 = inv(1 - aj1) */ private void updateSensThresh(){ //System.out.println("~~~~~~~~~~Calculating sens/thresh~~~~~~~~~~~"); //Create a standard normal distribution //System.out.println("True neg rate = " + this.trueNegRate); //System.out.println("True pos rate = " + this.truePosRate); NormalDistribution standardNormal = new NormalDistribution(); double invTrueNeg = standardNormal.inverseCumulativeProbability(this.trueNegRate); double invTruePos = standardNormal.inverseCumulativeProbability(1 - this.truePosRate); this.sensitivityIndex = invTrueNeg - invTruePos; this.threshold = invTrueNeg - (this.sensitivityIndex / (2 * 1.0)); //System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); } private double calculateujk(int actualAnswer){ if(actualAnswer == 1){ return (this.sensitivityIndex / 2); }else{ return -(this.sensitivityIndex / 2); } } /* * Get methods mainly used for testing */ public int getTotalPos(){ return this.totalPos; } public int getTotalNeg(){ return this.totalNeg; } public int getTruePos(){ return this.truePos; } public int getTrueNeg(){ return this.trueNeg; } public int getFalseNeg(){ return (this.totalNeg - this.trueNeg); } public int getFalsePos(){ return(this.totalPos - this.truePos); } public double getThreshold(){ return this.threshold; } public double getSensIndex(){ return this.sensitivityIndex; } public double getTruePosRate(){ return this.truePosRate; } public double getTrueNegRate(){ return this.trueNegRate; } }
false
true
public int generateAnswer(BinaryR response){ int answer; if (response.isTrue()){ answer = 1; }else{ answer = 0; } //update the sensory index and threshold for the calculation of ujk // this.updateRates(); this.updateSensThresh(); //generate ujk double ujk = calculateujk(response.isTrue() ? 1 : 0); //generate the appropriate normal distribution NormalDistribution dist = new NormalDistribution(ujk, this.standardDev); /* * generate a random number sampled from this distribution representing * the annotators signal */ double signal = dist.sample(); System.out.println("Rate" + this.truePosRate + " Answer " + answer + " Signal " + signal ); int answer = (Double.compare(signal, this.threshold) > 0) ? 1 : 0; //this.updateNumbers(answer, actualAnswer); //Update truePos/neg and totalpos/neg this.updateRates(); //Update truePos/negRates return answer; }
public int generateAnswer(BinaryR response){ int realanswer; if (response.isTrue()){ realanswer = 1; }else{ realanswer = 0; } //update the sensory index and threshold for the calculation of ujk // this.updateRates(); this.updateSensThresh(); //generate ujk double ujk = calculateujk(response.isTrue() ? 1 : 0); //generate the appropriate normal distribution NormalDistribution dist = new NormalDistribution(ujk, this.standardDev); /* * generate a random number sampled from this distribution representing * the annotators signal */ double signal = dist.sample(); System.out.println("Rate" + this.truePosRate + " Answer " + realanswer + " Signal " + signal ); int answer = (Double.compare(signal, this.threshold) > 0) ? 1 : 0; //this.updateNumbers(answer, actualAnswer); //Update truePos/neg and totalpos/neg this.updateRates(); //Update truePos/negRates return answer; }
diff --git a/src/main/java/be/Balor/Manager/Commands/Server/Extinguish.java b/src/main/java/be/Balor/Manager/Commands/Server/Extinguish.java index 171042af..47cfb42f 100644 --- a/src/main/java/be/Balor/Manager/Commands/Server/Extinguish.java +++ b/src/main/java/be/Balor/Manager/Commands/Server/Extinguish.java @@ -1,90 +1,90 @@ /************************************************************************ * This file is part of AdminCmd. * * AdminCmd 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. * * AdminCmd 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 AdminCmd. If not, see <http://www.gnu.org/licenses/>. ************************************************************************/ package be.Balor.Manager.Commands.Server; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import be.Balor.Manager.ACCommands; import be.Balor.Tools.Utils; /** * @author Balor (aka Antoine Aflalo) * */ public class Extinguish extends ACCommands { /** * */ public Extinguish() { permNode = "admincmd.server.extinguish"; cmdName = "bal_extinguish"; } /* * (non-Javadoc) * * @see * be.Balor.Manager.ACCommands#execute(org.bukkit.command.CommandSender, * java.lang.String[]) */ @Override public void execute(CommandSender sender, String... args) { if (Utils.isPlayer(sender)) { int range = 20; if (args.length >= 1) { try { range = Integer.parseInt(args[0]); } catch (NumberFormatException e) { } } Block block = ((Player) sender).getLocation().getBlock(); int count = 0; int limitX = block.getX() + range; int limitY = block.getY() + range; int limitZ = block.getZ() + range; Block current; for (int x = block.getX() - range; x <= limitX; x++) for (int y = block.getY() - range; y <= limitY; y++) for (int z = block.getZ() - range; z <= limitZ; z++) { current = block.getWorld().getBlockAt(x, y, z); if (current.getType().equals(Material.FIRE)) { current.setType(Material.AIR); count++; } } - Utils.sI18n(sender, "extinguish", "%nb", String.valueOf(count)); + Utils.sI18n(sender, "extinguish", "nb", String.valueOf(count)); } } /* * (non-Javadoc) * * @see be.Balor.Manager.ACCommands#argsCheck(java.lang.String[]) */ @Override public boolean argsCheck(String... args) { return args != null; } }
true
true
public void execute(CommandSender sender, String... args) { if (Utils.isPlayer(sender)) { int range = 20; if (args.length >= 1) { try { range = Integer.parseInt(args[0]); } catch (NumberFormatException e) { } } Block block = ((Player) sender).getLocation().getBlock(); int count = 0; int limitX = block.getX() + range; int limitY = block.getY() + range; int limitZ = block.getZ() + range; Block current; for (int x = block.getX() - range; x <= limitX; x++) for (int y = block.getY() - range; y <= limitY; y++) for (int z = block.getZ() - range; z <= limitZ; z++) { current = block.getWorld().getBlockAt(x, y, z); if (current.getType().equals(Material.FIRE)) { current.setType(Material.AIR); count++; } } Utils.sI18n(sender, "extinguish", "%nb", String.valueOf(count)); } }
public void execute(CommandSender sender, String... args) { if (Utils.isPlayer(sender)) { int range = 20; if (args.length >= 1) { try { range = Integer.parseInt(args[0]); } catch (NumberFormatException e) { } } Block block = ((Player) sender).getLocation().getBlock(); int count = 0; int limitX = block.getX() + range; int limitY = block.getY() + range; int limitZ = block.getZ() + range; Block current; for (int x = block.getX() - range; x <= limitX; x++) for (int y = block.getY() - range; y <= limitY; y++) for (int z = block.getZ() - range; z <= limitZ; z++) { current = block.getWorld().getBlockAt(x, y, z); if (current.getType().equals(Material.FIRE)) { current.setType(Material.AIR); count++; } } Utils.sI18n(sender, "extinguish", "nb", String.valueOf(count)); } }
diff --git a/ev/endrov/flowMorphology/EvOpMorphFillHolesBinary2D.java b/ev/endrov/flowMorphology/EvOpMorphFillHolesBinary2D.java index 26065135..83ef19a9 100644 --- a/ev/endrov/flowMorphology/EvOpMorphFillHolesBinary2D.java +++ b/ev/endrov/flowMorphology/EvOpMorphFillHolesBinary2D.java @@ -1,92 +1,93 @@ /*** * Copyright (C) 2010 Johan Henriksson * This code is under the Endrov / BSD license. See www.endrov.net * for the full text and how to cite. */ package endrov.flowMorphology; import java.util.LinkedList; import endrov.flow.EvOpSlice1; import endrov.imageset.EvPixels; import endrov.imageset.EvPixelsType; import endrov.util.ProgressHandle; import endrov.util.Vector3i; /** * Fill holes in binary image. The algorithm is optimized for images with small holes. O(w h) * <br/> * P.Soille - Morphological Image Analysis, Principles and applications. 2nd edition * @author Johan Henriksson */ public class EvOpMorphFillHolesBinary2D extends EvOpSlice1 { @Override public EvPixels exec1(ProgressHandle ph, EvPixels... p) { return apply(p[0]); } public static EvPixels apply(EvPixels pixels) { int w=pixels.getWidth(); int h=pixels.getHeight(); + pixels=pixels.convertToInt(true); EvPixels markstack=new EvPixels(EvPixelsType.INT, w, h); int[] inarr=pixels.getArrayInt(); int[] markarr=markstack.getArrayInt(); //Move along border and mark all open pixels as starting point LinkedList<Vector3i> q=new LinkedList<Vector3i>(); for(int ax=0;ax<w;ax++) { q.add(new Vector3i(ax,0,0)); q.add(new Vector3i(ax,h-1,0)); } for(int ay=0;ay<h;ay++) { q.add(new Vector3i(0,ay,0)); q.add(new Vector3i(w-1,ay,0)); } while(!q.isEmpty()) { Vector3i v=q.poll(); int x=v.x; int y=v.y; int index=y*w+x; //Check that this pixel has not been evaluated before if(markarr[index]==0) { int thisval=inarr[index]; //Test if this pixel should be included if(thisval==0) { markarr[index]=1; //Evaluate neighbours if(x>0) q.add(new Vector3i(x-1,y,0)); if(x<w-1) q.add(new Vector3i(x+1,y,0)); if(y>0) q.add(new Vector3i(x,y-1,0)); if(y<h-1) q.add(new Vector3i(x,y+1,0)); } } } //Invert the matrix to get the filled region for(int i=0;i<markarr.length;i++) markarr[i]=1-markarr[i]; return markstack; } }
true
true
public static EvPixels apply(EvPixels pixels) { int w=pixels.getWidth(); int h=pixels.getHeight(); EvPixels markstack=new EvPixels(EvPixelsType.INT, w, h); int[] inarr=pixels.getArrayInt(); int[] markarr=markstack.getArrayInt(); //Move along border and mark all open pixels as starting point LinkedList<Vector3i> q=new LinkedList<Vector3i>(); for(int ax=0;ax<w;ax++) { q.add(new Vector3i(ax,0,0)); q.add(new Vector3i(ax,h-1,0)); } for(int ay=0;ay<h;ay++) { q.add(new Vector3i(0,ay,0)); q.add(new Vector3i(w-1,ay,0)); } while(!q.isEmpty()) { Vector3i v=q.poll(); int x=v.x; int y=v.y; int index=y*w+x; //Check that this pixel has not been evaluated before if(markarr[index]==0) { int thisval=inarr[index]; //Test if this pixel should be included if(thisval==0) { markarr[index]=1; //Evaluate neighbours if(x>0) q.add(new Vector3i(x-1,y,0)); if(x<w-1) q.add(new Vector3i(x+1,y,0)); if(y>0) q.add(new Vector3i(x,y-1,0)); if(y<h-1) q.add(new Vector3i(x,y+1,0)); } } } //Invert the matrix to get the filled region for(int i=0;i<markarr.length;i++) markarr[i]=1-markarr[i]; return markstack; }
public static EvPixels apply(EvPixels pixels) { int w=pixels.getWidth(); int h=pixels.getHeight(); pixels=pixels.convertToInt(true); EvPixels markstack=new EvPixels(EvPixelsType.INT, w, h); int[] inarr=pixels.getArrayInt(); int[] markarr=markstack.getArrayInt(); //Move along border and mark all open pixels as starting point LinkedList<Vector3i> q=new LinkedList<Vector3i>(); for(int ax=0;ax<w;ax++) { q.add(new Vector3i(ax,0,0)); q.add(new Vector3i(ax,h-1,0)); } for(int ay=0;ay<h;ay++) { q.add(new Vector3i(0,ay,0)); q.add(new Vector3i(w-1,ay,0)); } while(!q.isEmpty()) { Vector3i v=q.poll(); int x=v.x; int y=v.y; int index=y*w+x; //Check that this pixel has not been evaluated before if(markarr[index]==0) { int thisval=inarr[index]; //Test if this pixel should be included if(thisval==0) { markarr[index]=1; //Evaluate neighbours if(x>0) q.add(new Vector3i(x-1,y,0)); if(x<w-1) q.add(new Vector3i(x+1,y,0)); if(y>0) q.add(new Vector3i(x,y-1,0)); if(y<h-1) q.add(new Vector3i(x,y+1,0)); } } } //Invert the matrix to get the filled region for(int i=0;i<markarr.length;i++) markarr[i]=1-markarr[i]; return markstack; }
diff --git a/potbs4j/src/main/java/com/ashlux/potbs/potbs4j/services/AbstractPotbsService.java b/potbs4j/src/main/java/com/ashlux/potbs/potbs4j/services/AbstractPotbsService.java index 59f4c8b..157ef29 100644 --- a/potbs4j/src/main/java/com/ashlux/potbs/potbs4j/services/AbstractPotbsService.java +++ b/potbs4j/src/main/java/com/ashlux/potbs/potbs4j/services/AbstractPotbsService.java @@ -1,82 +1,82 @@ package com.ashlux.potbs.potbs4j.services; import com.ashlux.potbs.potbs4j.exception.PotbsServiceException; import org.apache.commons.io.IOUtils; import org.apache.xmlbeans.XmlException; import org.apache.xmlbeans.XmlObject; import org.slf4j.LoggerFactory; import org.slf4j.Logger; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; abstract public class AbstractPotbsService implements PotbsService { final Logger log = LoggerFactory.getLogger( AbstractPotbsService.class ); private String apiKey; private String userId; public AbstractPotbsService( String apiKey, String userId ) { this.apiKey = apiKey; this.userId = userId; } protected XmlObject executeService( final String url ) throws PotbsServiceException { log.debug( "Making call to PotBS server using url=[" + url + "]." ); return doPost( url ); } private XmlObject doPost( final String urlString ) throws PotbsServiceException { String xml = null; try { URL url = new URL( urlString ); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setDoOutput( true ); httpURLConnection.setRequestMethod( "POST" ); OutputStream outputStream = httpURLConnection.getOutputStream(); log.trace( "Setting apikey=[" + apiKey + "]." ); IOUtils.write( "apikey=" + apiKey, outputStream ); IOUtils.write( "&", outputStream ); - log.trace( "Setting apikey=[" + userId + "]." ); + log.trace( "Setting userId=[" + userId + "]." ); IOUtils.write( "userid=" + userId, outputStream ); IOUtils.closeQuietly( outputStream ); if ( httpURLConnection.getResponseCode() != HttpURLConnection.HTTP_OK ) { throw new PotbsServiceException( "PotBS service returned [" + httpURLConnection.getResponseCode() + "], a non-OK response." ); } InputStream inputStream = httpURLConnection.getInputStream(); xml = IOUtils.toString( inputStream ); IOUtils.closeQuietly( inputStream ); if (log.isTraceEnabled()) { log.trace("PotBS service returned [" + xml + "]"); } return XmlObject.Factory.parse( xml ); } catch ( IOException e ) { throw new PotbsServiceException( "Error sending post for PotBS service.", e ); } catch ( XmlException e ) { throw new PotbsServiceException( "Could not parse PotBS response xml=[" + xml + "].", e ); } } }
true
true
private XmlObject doPost( final String urlString ) throws PotbsServiceException { String xml = null; try { URL url = new URL( urlString ); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setDoOutput( true ); httpURLConnection.setRequestMethod( "POST" ); OutputStream outputStream = httpURLConnection.getOutputStream(); log.trace( "Setting apikey=[" + apiKey + "]." ); IOUtils.write( "apikey=" + apiKey, outputStream ); IOUtils.write( "&", outputStream ); log.trace( "Setting apikey=[" + userId + "]." ); IOUtils.write( "userid=" + userId, outputStream ); IOUtils.closeQuietly( outputStream ); if ( httpURLConnection.getResponseCode() != HttpURLConnection.HTTP_OK ) { throw new PotbsServiceException( "PotBS service returned [" + httpURLConnection.getResponseCode() + "], a non-OK response." ); } InputStream inputStream = httpURLConnection.getInputStream(); xml = IOUtils.toString( inputStream ); IOUtils.closeQuietly( inputStream ); if (log.isTraceEnabled()) { log.trace("PotBS service returned [" + xml + "]"); } return XmlObject.Factory.parse( xml ); } catch ( IOException e ) { throw new PotbsServiceException( "Error sending post for PotBS service.", e ); } catch ( XmlException e ) { throw new PotbsServiceException( "Could not parse PotBS response xml=[" + xml + "].", e ); } }
private XmlObject doPost( final String urlString ) throws PotbsServiceException { String xml = null; try { URL url = new URL( urlString ); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setDoOutput( true ); httpURLConnection.setRequestMethod( "POST" ); OutputStream outputStream = httpURLConnection.getOutputStream(); log.trace( "Setting apikey=[" + apiKey + "]." ); IOUtils.write( "apikey=" + apiKey, outputStream ); IOUtils.write( "&", outputStream ); log.trace( "Setting userId=[" + userId + "]." ); IOUtils.write( "userid=" + userId, outputStream ); IOUtils.closeQuietly( outputStream ); if ( httpURLConnection.getResponseCode() != HttpURLConnection.HTTP_OK ) { throw new PotbsServiceException( "PotBS service returned [" + httpURLConnection.getResponseCode() + "], a non-OK response." ); } InputStream inputStream = httpURLConnection.getInputStream(); xml = IOUtils.toString( inputStream ); IOUtils.closeQuietly( inputStream ); if (log.isTraceEnabled()) { log.trace("PotBS service returned [" + xml + "]"); } return XmlObject.Factory.parse( xml ); } catch ( IOException e ) { throw new PotbsServiceException( "Error sending post for PotBS service.", e ); } catch ( XmlException e ) { throw new PotbsServiceException( "Could not parse PotBS response xml=[" + xml + "].", e ); } }
diff --git a/doxia-doc-renderer/src/main/java/org/apache/maven/doxia/docrenderer/pdf/itext/ITextPdfRenderer.java b/doxia-doc-renderer/src/main/java/org/apache/maven/doxia/docrenderer/pdf/itext/ITextPdfRenderer.java index bb3cc16..f6cbc50 100644 --- a/doxia-doc-renderer/src/main/java/org/apache/maven/doxia/docrenderer/pdf/itext/ITextPdfRenderer.java +++ b/doxia-doc-renderer/src/main/java/org/apache/maven/doxia/docrenderer/pdf/itext/ITextPdfRenderer.java @@ -1,621 +1,621 @@ package org.apache.maven.doxia.docrenderer.pdf.itext; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.Writer; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import org.apache.maven.doxia.docrenderer.DocumentRendererException; import org.apache.maven.doxia.docrenderer.pdf.AbstractPdfRenderer; import org.apache.maven.doxia.document.DocumentCover; import org.apache.maven.doxia.document.DocumentMeta; import org.apache.maven.doxia.document.DocumentModel; import org.apache.maven.doxia.document.DocumentTOCItem; import org.apache.maven.doxia.module.itext.ITextSink; import org.apache.maven.doxia.module.itext.ITextSinkFactory; import org.apache.maven.doxia.module.itext.ITextUtil; import org.apache.maven.doxia.module.site.SiteModule; import org.apache.xml.utils.DefaultErrorHandler; import org.codehaus.plexus.util.IOUtil; import org.codehaus.plexus.util.StringUtils; import org.codehaus.plexus.util.WriterFactory; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.xml.sax.SAXException; import com.lowagie.text.ElementTags; /** * Abstract <code>document</code> render with the <code>iText</code> framework * * @author <a href="mailto:[email protected]">Vincent Siveton</a> * @author ltheussl * @version $Id$ * @since 1.1 * @plexus.component role="org.apache.maven.doxia.docrenderer.pdf.PdfRenderer" role-hint="itext" */ public class ITextPdfRenderer extends AbstractPdfRenderer { /** The xslt style sheet used to transform a Document to an iText file. */ private static final String XSLT_RESOURCE = "TOC.xslt"; /** The TransformerFactory. */ private static final TransformerFactory TRANSFORMER_FACTORY = TransformerFactory.newInstance(); /** The DocumentBuilderFactory. */ private static final DocumentBuilderFactory DOCUMENT_BUILDER_FACTORY = DocumentBuilderFactory.newInstance(); /** The DocumentBuilder. */ private static final DocumentBuilder DOCUMENT_BUILDER; static { TRANSFORMER_FACTORY.setErrorListener( new DefaultErrorHandler() ); try { DOCUMENT_BUILDER = DOCUMENT_BUILDER_FACTORY.newDocumentBuilder(); } catch ( ParserConfigurationException e ) { throw new RuntimeException( "Error building document :" + e.getMessage() ); } } /** {@inheritDoc} */ public void generatePdf( File inputFile, File pdfFile ) throws DocumentRendererException { if ( getLogger().isDebugEnabled() ) { getLogger().debug( "Generating : " + pdfFile ); } try { ITextUtil.writePdf( new FileInputStream( inputFile ), new FileOutputStream( pdfFile ) ); } catch ( IOException e ) { throw new DocumentRendererException( "Cannot create PDF from " + inputFile + ": " + e.getMessage(), e ); } catch ( RuntimeException e ) { throw new DocumentRendererException( "Error creating PDF from " + inputFile + ": " + e.getMessage(), e ); } } /** {@inheritDoc} */ public void render( Map filesToProcess, File outputDirectory, DocumentModel documentModel ) throws DocumentRendererException, IOException { // copy resources, images, etc. copyResources( outputDirectory ); if ( documentModel == null ) { getLogger().debug( "No document model, generating all documents individually." ); renderIndividual( filesToProcess, outputDirectory ); return; } String outputName = getOutputName( documentModel ); File outputITextFile = new File( outputDirectory, outputName + ".xml" ); if ( !outputITextFile.getParentFile().exists() ) { outputITextFile.getParentFile().mkdirs(); } File pdfOutputFile = new File( outputDirectory, outputName + ".pdf" ); if ( !pdfOutputFile.getParentFile().exists() ) { pdfOutputFile.getParentFile().mkdirs(); } List iTextFiles; if ( ( documentModel.getToc() == null ) || ( documentModel.getToc().getItems() == null ) ) { getLogger().info( "No TOC is defined in the document descriptor. Merging all documents." ); iTextFiles = parseAllFiles( filesToProcess, outputDirectory ); } else { getLogger().debug( "Using TOC defined in the document descriptor." ); iTextFiles = parseTOCFiles( filesToProcess, outputDirectory, documentModel ); } File iTextFile = new File( outputDirectory, outputName + ".xml" ); File iTextOutput = new File( outputDirectory, outputName + "." + getOutputExtension() ); Document document = generateDocument( iTextFiles ); transform( documentModel, document, iTextFile ); generatePdf( iTextFile, iTextOutput ); } /** {@inheritDoc} */ public void renderIndividual( Map filesToProcess, File outputDirectory ) throws DocumentRendererException, IOException { for ( Iterator it = filesToProcess.keySet().iterator(); it.hasNext(); ) { String key = (String) it.next(); SiteModule module = (SiteModule) filesToProcess.get( key ); File fullDoc = new File( getBaseDir(), module.getSourceDirectory() + File.separator + key ); String output = key; String lowerCaseExtension = module.getExtension().toLowerCase( Locale.ENGLISH ); if ( output.toLowerCase( Locale.ENGLISH ).indexOf( "." + lowerCaseExtension ) != -1 ) { output = output.substring( 0, output.toLowerCase( Locale.ENGLISH ).indexOf( "." + lowerCaseExtension ) ); } File outputITextFile = new File( outputDirectory, output + ".xml" ); if ( !outputITextFile.getParentFile().exists() ) { outputITextFile.getParentFile().mkdirs(); } File pdfOutputFile = new File( outputDirectory, output + ".pdf" ); if ( !pdfOutputFile.getParentFile().exists() ) { pdfOutputFile.getParentFile().mkdirs(); } parse( fullDoc, module, outputITextFile ); generatePdf( outputITextFile, pdfOutputFile ); } } //-------------------------------------------- // //-------------------------------------------- /** * Parse a source document and emit results into a sink. * * @param fullDocPath file to the source document. * @param module the site module associated with the source document (determines the parser to use). * @param iTextFile the resulting iText xml file. * @throws DocumentRendererException in case of a parsing problem. * @throws IOException if the source and/or target document cannot be opened. */ private void parse( File fullDoc, SiteModule module, File iTextFile ) throws DocumentRendererException, IOException { if ( getLogger().isDebugEnabled() ) { getLogger().debug( "Parsing file " + fullDoc.getAbsolutePath() ); } System.setProperty( "itext.basedir", iTextFile.getParentFile().getAbsolutePath() ); Writer writer = null; ITextSink sink = null; try { writer = WriterFactory.newXmlWriter( iTextFile ); sink = (ITextSink) new ITextSinkFactory().createSink( writer ); sink.setClassLoader( new URLClassLoader( new URL[] { iTextFile.getParentFile().toURI().toURL() } ) ); parse( fullDoc.getAbsolutePath(), module.getParserId(), sink ); } finally { if ( sink != null ) { sink.flush(); sink.close(); } IOUtil.close( writer ); System.getProperties().remove( "itext.basedir" ); } } /** * Merge all iTextFiles to a single one. * * @param iTextFiles list of iText xml files. * @return Document. * @throws DocumentRendererException if any. * @throws IOException if any. */ private Document generateDocument( List iTextFiles ) throws DocumentRendererException, IOException { Document document = DOCUMENT_BUILDER.newDocument(); document.appendChild( document.createElement( ElementTags.ITEXT ) ); // Used only to set a root for ( int i = 0; i < iTextFiles.size(); i++ ) { File iTextFile = (File) iTextFiles.get( i ); Document iTextDocument; try { iTextDocument = DOCUMENT_BUILDER.parse( iTextFile ); } catch ( SAXException e ) { throw new DocumentRendererException( "SAX Error : " + e.getMessage() ); } // Only one chapter per doc Node chapter = iTextDocument.getElementsByTagName( ElementTags.CHAPTER ).item( 0 ); try { document.getDocumentElement().appendChild( document.importNode( chapter, true ) ); } catch ( DOMException e ) { throw new DocumentRendererException( "Error appending chapter for " + iTextFile + " : " + e.getMessage() ); } } return document; } /** * Initialize the transformer object. * * @return an instance of a transformer object. * @throws DocumentRendererException if any. */ private Transformer initTransformer() throws DocumentRendererException { try { Transformer transformer = TRANSFORMER_FACTORY.newTransformer( new StreamSource( ITextPdfRenderer.class .getResourceAsStream( XSLT_RESOURCE ) ) ); transformer.setErrorListener( TRANSFORMER_FACTORY.getErrorListener() ); transformer.setOutputProperty( OutputKeys.OMIT_XML_DECLARATION, "false" ); transformer.setOutputProperty( OutputKeys.INDENT, "yes" ); transformer.setOutputProperty( OutputKeys.METHOD, "xml" ); transformer.setOutputProperty( OutputKeys.ENCODING, "UTF-8" ); // No doctype since itext doctype is not up to date! return transformer; } catch ( TransformerConfigurationException e ) { throw new DocumentRendererException( "Error configuring Transformer for " + XSLT_RESOURCE + ": " + e.getMessage() ); } catch ( IllegalArgumentException e ) { throw new DocumentRendererException( "Error configuring Transformer for " + XSLT_RESOURCE + ": " + e.getMessage() ); } } /** * Add transformer parameters from a DocumentModel. * * @param transformer the Transformer to set the parameters. * @param documentModel the DocumentModel to take the parameters from, could be null. * @param iTextFile the iTextFile not null for the relative paths. */ private void addTransformerParameters( Transformer transformer, DocumentModel documentModel, File iTextFile ) { if ( documentModel == null ) { return; } // Meta parameters boolean hasNullMeta = false; if ( documentModel.getMeta() == null ) { hasNullMeta = true; documentModel.setMeta( new DocumentMeta() ); } addTransformerParameter( transformer, "meta.author", documentModel.getMeta().getAllAuthorNames(), System.getProperty( "user.name", "null" ) ); addTransformerParameter( transformer, "meta.creator", documentModel.getMeta().getCreator(), System.getProperty( "user.name", "null" ) ); // see com.lowagie.text.Document#addCreationDate() SimpleDateFormat sdf = new SimpleDateFormat( "EEE MMM dd HH:mm:ss zzz yyyy" ); - addTransformerParameter( transformer, "meta.creationdate", documentModel.getMeta().getCreationDate_(), + addTransformerParameter( transformer, "meta.creationdate", documentModel.getMeta().getCreationdate(), sdf.format( new Date() ) ); addTransformerParameter( transformer, "meta.keywords", documentModel.getMeta().getAllKeyWords() ); addTransformerParameter( transformer, "meta.pagesize", documentModel.getMeta().getSubject(), ITextUtil.getPageSize( ITextUtil.getDefaultPageSize() ) ); addTransformerParameter( transformer, "meta.producer", documentModel.getMeta().getGenerator(), "Apache Doxia iText" ); addTransformerParameter( transformer, "meta.subject", documentModel.getMeta().getSubject(), ( documentModel.getMeta().getTitle() != null ? documentModel.getMeta().getTitle() : "" ) ); addTransformerParameter( transformer, "meta.title", documentModel.getMeta().getTitle() ); if ( hasNullMeta ) { documentModel.setMeta( null ); } // cover parameter boolean hasNullCover = false; if ( documentModel.getCover() == null ) { hasNullCover = true; documentModel.setCover( new DocumentCover() ); } addTransformerParameter( transformer, "cover.author", documentModel.getCover().getAllAuthorNames(), System.getProperty( "user.name", "null" ) ); String companyLogo = getLogoURL( documentModel.getCover().getCompanyLogo(), iTextFile.getParentFile() ); addTransformerParameter( transformer, "cover.companyLogo", companyLogo ); addTransformerParameter( transformer, "cover.companyName", documentModel.getCover().getCompanyName() ); - if ( documentModel.getCover().getCoverDate_() == null ) + if ( documentModel.getCover().getCoverdate() == null ) { documentModel.getCover().setCoverDate( new Date() ); - addTransformerParameter( transformer, "cover.date", documentModel.getCover().getCoverDate_() ); + addTransformerParameter( transformer, "cover.date", documentModel.getCover().getCoverdate() ); documentModel.getCover().setCoverDate( null ); } else { - addTransformerParameter( transformer, "cover.date", documentModel.getCover().getCoverDate_() ); + addTransformerParameter( transformer, "cover.date", documentModel.getCover().getCoverdate() ); } addTransformerParameter( transformer, "cover.subtitle", documentModel.getCover().getCoverSubTitle() ); addTransformerParameter( transformer, "cover.title", documentModel.getCover().getCoverTitle() ); addTransformerParameter( transformer, "cover.type", documentModel.getCover().getCoverType() ); addTransformerParameter( transformer, "cover.version", documentModel.getCover().getCoverVersion() ); String projectLogo = getLogoURL( documentModel.getCover().getProjectLogo(), iTextFile.getParentFile() ); addTransformerParameter( transformer, "cover.projectLogo", projectLogo ); addTransformerParameter( transformer, "cover.projectName", documentModel.getCover().getProjectName() ); if ( hasNullCover ) { documentModel.setCover( null ); } } /** * @param transformer not null * @param name not null * @param value could be empty * @param defaultValue could be empty * @since 1.1.1 */ private void addTransformerParameter( Transformer transformer, String name, String value, String defaultValue ) { if ( StringUtils.isEmpty( value ) ) { addTransformerParameter( transformer, name, defaultValue ); } else { addTransformerParameter( transformer, name, value ); } } /** * @param transformer not null * @param name not null * @param value could be empty * @since 1.1.1 */ private void addTransformerParameter( Transformer transformer, String name, String value ) { if ( StringUtils.isEmpty( value ) ) { return; } transformer.setParameter( name, value ); } /** * Transform a document to an iTextFile. * * @param documentModel the DocumentModel to take the parameters from, could be null. * @param document the Document to transform. * @param iTextFile the resulting iText xml file. * @throws DocumentRendererException in case of a transformation error. */ private void transform( DocumentModel documentModel, Document document, File iTextFile ) throws DocumentRendererException { Transformer transformer = initTransformer(); addTransformerParameters( transformer, documentModel, iTextFile ); try { transformer.transform( new DOMSource( document ), new StreamResult( iTextFile ) ); } catch ( TransformerException e ) { throw new DocumentRendererException( "Error transforming Document " + document + ": " + e.getMessage() ); } } /** * @param filesToProcess not null * @param outputDirectory not null * @return a list of all parsed files. * @throws DocumentRendererException if any * @throws IOException if any * @since 1.1.1 */ private List parseAllFiles( Map filesToProcess, File outputDirectory ) throws DocumentRendererException, IOException { List iTextFiles = new LinkedList(); for ( Iterator it = filesToProcess.keySet().iterator(); it.hasNext(); ) { String key = (String) it.next(); SiteModule module = (SiteModule) filesToProcess.get( key ); File fullDoc = new File( getBaseDir(), module.getSourceDirectory() + File.separator + key ); String outputITextName = key.substring( 0, key.lastIndexOf( "." ) + 1 ) + "xml"; File outputITextFileTmp = new File( outputDirectory, outputITextName ); outputITextFileTmp.deleteOnExit(); if ( !outputITextFileTmp.getParentFile().exists() ) { outputITextFileTmp.getParentFile().mkdirs(); } iTextFiles.add( outputITextFileTmp ); parse( fullDoc, module, outputITextFileTmp ); } return iTextFiles; } /** * @param filesToProcess not null * @param outputDirectory not null * @return a list of all parsed files. * @throws DocumentRendererException if any * @throws IOException if any * @since 1.1.1 */ private List parseTOCFiles( Map filesToProcess, File outputDirectory, DocumentModel documentModel ) throws DocumentRendererException, IOException { List iTextFiles = new LinkedList(); for ( Iterator it = documentModel.getToc().getItems().iterator(); it.hasNext(); ) { DocumentTOCItem tocItem = (DocumentTOCItem) it.next(); if ( tocItem.getRef() == null ) { getLogger().debug( "No ref defined for the tocItem '" + tocItem.getName() + "' in the document descriptor. IGNORING" ); continue; } String href = StringUtils.replace( tocItem.getRef(), "\\", "/" ); if ( href.lastIndexOf( "." ) != -1 ) { href = href.substring( 0, href.lastIndexOf( "." ) ); } for ( Iterator i = siteModuleManager.getSiteModules().iterator(); i.hasNext(); ) { SiteModule module = (SiteModule) i.next(); File moduleBasedir = new File( getBaseDir(), module.getSourceDirectory() ); if ( moduleBasedir.exists() ) { String doc = href + "." + module.getExtension(); File source = new File( moduleBasedir, doc ); if ( source.exists() ) { String outputITextName = doc.substring( 0, doc.lastIndexOf( "." ) + 1 ) + "xml"; File outputITextFileTmp = new File( outputDirectory, outputITextName ); outputITextFileTmp.deleteOnExit(); if ( !outputITextFileTmp.getParentFile().exists() ) { outputITextFileTmp.getParentFile().mkdirs(); } iTextFiles.add( outputITextFileTmp ); parse( source, module, outputITextFileTmp ); } } } } return iTextFiles; } /** * @param logo * @param parentFile * @return the logo url or null if unable to create it. * @since 1.1.1 */ private String getLogoURL( String logo, File parentFile ) { if ( logo == null ) { return null; } try { return new URL( logo ).toString(); } catch ( MalformedURLException e ) { try { File f = new File( parentFile, logo ); if ( !f.exists() ) { getLogger().warn( "The logo " + f.getAbsolutePath() + " doesnt exist. IGNORING" ); } else { return f.toURL().toString(); } } catch ( MalformedURLException e1 ) { // nope } } return null; } }
false
true
private void addTransformerParameters( Transformer transformer, DocumentModel documentModel, File iTextFile ) { if ( documentModel == null ) { return; } // Meta parameters boolean hasNullMeta = false; if ( documentModel.getMeta() == null ) { hasNullMeta = true; documentModel.setMeta( new DocumentMeta() ); } addTransformerParameter( transformer, "meta.author", documentModel.getMeta().getAllAuthorNames(), System.getProperty( "user.name", "null" ) ); addTransformerParameter( transformer, "meta.creator", documentModel.getMeta().getCreator(), System.getProperty( "user.name", "null" ) ); // see com.lowagie.text.Document#addCreationDate() SimpleDateFormat sdf = new SimpleDateFormat( "EEE MMM dd HH:mm:ss zzz yyyy" ); addTransformerParameter( transformer, "meta.creationdate", documentModel.getMeta().getCreationDate_(), sdf.format( new Date() ) ); addTransformerParameter( transformer, "meta.keywords", documentModel.getMeta().getAllKeyWords() ); addTransformerParameter( transformer, "meta.pagesize", documentModel.getMeta().getSubject(), ITextUtil.getPageSize( ITextUtil.getDefaultPageSize() ) ); addTransformerParameter( transformer, "meta.producer", documentModel.getMeta().getGenerator(), "Apache Doxia iText" ); addTransformerParameter( transformer, "meta.subject", documentModel.getMeta().getSubject(), ( documentModel.getMeta().getTitle() != null ? documentModel.getMeta().getTitle() : "" ) ); addTransformerParameter( transformer, "meta.title", documentModel.getMeta().getTitle() ); if ( hasNullMeta ) { documentModel.setMeta( null ); } // cover parameter boolean hasNullCover = false; if ( documentModel.getCover() == null ) { hasNullCover = true; documentModel.setCover( new DocumentCover() ); } addTransformerParameter( transformer, "cover.author", documentModel.getCover().getAllAuthorNames(), System.getProperty( "user.name", "null" ) ); String companyLogo = getLogoURL( documentModel.getCover().getCompanyLogo(), iTextFile.getParentFile() ); addTransformerParameter( transformer, "cover.companyLogo", companyLogo ); addTransformerParameter( transformer, "cover.companyName", documentModel.getCover().getCompanyName() ); if ( documentModel.getCover().getCoverDate_() == null ) { documentModel.getCover().setCoverDate( new Date() ); addTransformerParameter( transformer, "cover.date", documentModel.getCover().getCoverDate_() ); documentModel.getCover().setCoverDate( null ); } else { addTransformerParameter( transformer, "cover.date", documentModel.getCover().getCoverDate_() ); } addTransformerParameter( transformer, "cover.subtitle", documentModel.getCover().getCoverSubTitle() ); addTransformerParameter( transformer, "cover.title", documentModel.getCover().getCoverTitle() ); addTransformerParameter( transformer, "cover.type", documentModel.getCover().getCoverType() ); addTransformerParameter( transformer, "cover.version", documentModel.getCover().getCoverVersion() ); String projectLogo = getLogoURL( documentModel.getCover().getProjectLogo(), iTextFile.getParentFile() ); addTransformerParameter( transformer, "cover.projectLogo", projectLogo ); addTransformerParameter( transformer, "cover.projectName", documentModel.getCover().getProjectName() ); if ( hasNullCover ) { documentModel.setCover( null ); } }
private void addTransformerParameters( Transformer transformer, DocumentModel documentModel, File iTextFile ) { if ( documentModel == null ) { return; } // Meta parameters boolean hasNullMeta = false; if ( documentModel.getMeta() == null ) { hasNullMeta = true; documentModel.setMeta( new DocumentMeta() ); } addTransformerParameter( transformer, "meta.author", documentModel.getMeta().getAllAuthorNames(), System.getProperty( "user.name", "null" ) ); addTransformerParameter( transformer, "meta.creator", documentModel.getMeta().getCreator(), System.getProperty( "user.name", "null" ) ); // see com.lowagie.text.Document#addCreationDate() SimpleDateFormat sdf = new SimpleDateFormat( "EEE MMM dd HH:mm:ss zzz yyyy" ); addTransformerParameter( transformer, "meta.creationdate", documentModel.getMeta().getCreationdate(), sdf.format( new Date() ) ); addTransformerParameter( transformer, "meta.keywords", documentModel.getMeta().getAllKeyWords() ); addTransformerParameter( transformer, "meta.pagesize", documentModel.getMeta().getSubject(), ITextUtil.getPageSize( ITextUtil.getDefaultPageSize() ) ); addTransformerParameter( transformer, "meta.producer", documentModel.getMeta().getGenerator(), "Apache Doxia iText" ); addTransformerParameter( transformer, "meta.subject", documentModel.getMeta().getSubject(), ( documentModel.getMeta().getTitle() != null ? documentModel.getMeta().getTitle() : "" ) ); addTransformerParameter( transformer, "meta.title", documentModel.getMeta().getTitle() ); if ( hasNullMeta ) { documentModel.setMeta( null ); } // cover parameter boolean hasNullCover = false; if ( documentModel.getCover() == null ) { hasNullCover = true; documentModel.setCover( new DocumentCover() ); } addTransformerParameter( transformer, "cover.author", documentModel.getCover().getAllAuthorNames(), System.getProperty( "user.name", "null" ) ); String companyLogo = getLogoURL( documentModel.getCover().getCompanyLogo(), iTextFile.getParentFile() ); addTransformerParameter( transformer, "cover.companyLogo", companyLogo ); addTransformerParameter( transformer, "cover.companyName", documentModel.getCover().getCompanyName() ); if ( documentModel.getCover().getCoverdate() == null ) { documentModel.getCover().setCoverDate( new Date() ); addTransformerParameter( transformer, "cover.date", documentModel.getCover().getCoverdate() ); documentModel.getCover().setCoverDate( null ); } else { addTransformerParameter( transformer, "cover.date", documentModel.getCover().getCoverdate() ); } addTransformerParameter( transformer, "cover.subtitle", documentModel.getCover().getCoverSubTitle() ); addTransformerParameter( transformer, "cover.title", documentModel.getCover().getCoverTitle() ); addTransformerParameter( transformer, "cover.type", documentModel.getCover().getCoverType() ); addTransformerParameter( transformer, "cover.version", documentModel.getCover().getCoverVersion() ); String projectLogo = getLogoURL( documentModel.getCover().getProjectLogo(), iTextFile.getParentFile() ); addTransformerParameter( transformer, "cover.projectLogo", projectLogo ); addTransformerParameter( transformer, "cover.projectName", documentModel.getCover().getProjectName() ); if ( hasNullCover ) { documentModel.setCover( null ); } }
diff --git a/src/net/mcft/copy/betterstorage/container/ContainerCrate.java b/src/net/mcft/copy/betterstorage/container/ContainerCrate.java index dd4a7e0..8b421f2 100644 --- a/src/net/mcft/copy/betterstorage/container/ContainerCrate.java +++ b/src/net/mcft/copy/betterstorage/container/ContainerCrate.java @@ -1,78 +1,79 @@ package net.mcft.copy.betterstorage.container; import net.mcft.copy.betterstorage.block.crate.CratePileData; import net.mcft.copy.betterstorage.inventory.InventoryCratePlayerView; import net.mcft.copy.betterstorage.utils.PacketUtils; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.ICrafting; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; import net.minecraft.network.packet.Packet103SetSlot; public class ContainerCrate extends ContainerBetterStorage { private EntityPlayer player; private InventoryCratePlayerView playerView; private int lastFullness = 0; private int fullness = 0; public ContainerCrate(EntityPlayer player, InventoryCratePlayerView inventory) { super(player, inventory, 9, inventory.getSizeInventory() / 9); this.player = player; this.playerView = inventory; CratePileData data = inventory.data; fullness = data.getOccupiedSlots() * 255 / data.getCapacity(); } @Override public void detectAndSendChanges() { super.detectAndSendChanges(); CratePileData data = playerView.data; // detectAndSendChanges gets called after a crate gets broken. // So to prevent a division by zero, just return. if (data.getNumCrates() <= 0) return; fullness = data.getOccupiedSlots() * 255 / data.getCapacity(); if (lastFullness != fullness) for (Object c : crafters) ((ICrafting)c).sendProgressBarUpdate(this, 0, fullness); lastFullness = fullness; } @Override public ItemStack transferStackInSlot(EntityPlayer player, int slotId) { Slot slot = (Slot)inventorySlots.get(slotId); ItemStack stackBefore = slot.getStack(); if (stackBefore != null) stackBefore.copy(); // If slot isn't empty and item can be stacked. if ((slot != null) && slot.getHasStack()) { ItemStack slotStack = slot.getStack(); // If slot is in the container inventory, try to transfer the item to the player. if (slotId < playerView.getSizeInventory()) { int count = slotStack.stackSize; mergeItemStack(slotStack, playerView.getSizeInventory(), inventorySlots.size(), true); int amount = count - slotStack.stackSize; slotStack.stackSize = count; playerView.decrStackSize(slotId, amount); + return null; // If slot is in the player inventory, try to transfer the item to the container. } else { ItemStack overflow = playerView.data.addItems(slotStack); slot.putStack(overflow); // Send slot contents to player. PacketUtils.sendPacket(player, new Packet103SetSlot(player.openContainer.windowId, slotId, overflow)); // If there's overflow, return null because otherwise, retrySlotClick // will be called and there's going to be an infinite loop. // This kills the game. if (overflow != null) return null; } } return stackBefore; } }
true
true
public ItemStack transferStackInSlot(EntityPlayer player, int slotId) { Slot slot = (Slot)inventorySlots.get(slotId); ItemStack stackBefore = slot.getStack(); if (stackBefore != null) stackBefore.copy(); // If slot isn't empty and item can be stacked. if ((slot != null) && slot.getHasStack()) { ItemStack slotStack = slot.getStack(); // If slot is in the container inventory, try to transfer the item to the player. if (slotId < playerView.getSizeInventory()) { int count = slotStack.stackSize; mergeItemStack(slotStack, playerView.getSizeInventory(), inventorySlots.size(), true); int amount = count - slotStack.stackSize; slotStack.stackSize = count; playerView.decrStackSize(slotId, amount); // If slot is in the player inventory, try to transfer the item to the container. } else { ItemStack overflow = playerView.data.addItems(slotStack); slot.putStack(overflow); // Send slot contents to player. PacketUtils.sendPacket(player, new Packet103SetSlot(player.openContainer.windowId, slotId, overflow)); // If there's overflow, return null because otherwise, retrySlotClick // will be called and there's going to be an infinite loop. // This kills the game. if (overflow != null) return null; } } return stackBefore; }
public ItemStack transferStackInSlot(EntityPlayer player, int slotId) { Slot slot = (Slot)inventorySlots.get(slotId); ItemStack stackBefore = slot.getStack(); if (stackBefore != null) stackBefore.copy(); // If slot isn't empty and item can be stacked. if ((slot != null) && slot.getHasStack()) { ItemStack slotStack = slot.getStack(); // If slot is in the container inventory, try to transfer the item to the player. if (slotId < playerView.getSizeInventory()) { int count = slotStack.stackSize; mergeItemStack(slotStack, playerView.getSizeInventory(), inventorySlots.size(), true); int amount = count - slotStack.stackSize; slotStack.stackSize = count; playerView.decrStackSize(slotId, amount); return null; // If slot is in the player inventory, try to transfer the item to the container. } else { ItemStack overflow = playerView.data.addItems(slotStack); slot.putStack(overflow); // Send slot contents to player. PacketUtils.sendPacket(player, new Packet103SetSlot(player.openContainer.windowId, slotId, overflow)); // If there's overflow, return null because otherwise, retrySlotClick // will be called and there's going to be an infinite loop. // This kills the game. if (overflow != null) return null; } } return stackBefore; }
diff --git a/plugins/org.eclipse.m2m.atl.emftvm/src/org/eclipse/m2m/atl/emftvm/impl/CodeBlockImpl.java b/plugins/org.eclipse.m2m.atl.emftvm/src/org/eclipse/m2m/atl/emftvm/impl/CodeBlockImpl.java index effd603f..8862a8c8 100644 --- a/plugins/org.eclipse.m2m.atl.emftvm/src/org/eclipse/m2m/atl/emftvm/impl/CodeBlockImpl.java +++ b/plugins/org.eclipse.m2m.atl.emftvm/src/org/eclipse/m2m/atl/emftvm/impl/CodeBlockImpl.java @@ -1,2558 +1,2558 @@ /******************************************************************************* * Copyright (c) 2011-2012 Vrije Universiteit Brussel. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Dennis Wagelaar, Vrije Universiteit Brussel - initial API and * implementation and/or initial documentation *******************************************************************************/ package org.eclipse.m2m.atl.emftvm.impl; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.BasicEList; import org.eclipse.emf.common.util.ECollections; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EClassifier; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EStructuralFeature; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.impl.EObjectImpl; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.ecore.util.EObjectContainmentWithInverseEList; import org.eclipse.emf.ecore.util.EcoreUtil; import org.eclipse.emf.ecore.util.InternalEList; import org.eclipse.emf.ecore.xmi.XMIResource; import org.eclipse.m2m.atl.emftvm.Add; import org.eclipse.m2m.atl.emftvm.And; import org.eclipse.m2m.atl.emftvm.BranchInstruction; import org.eclipse.m2m.atl.emftvm.CodeBlock; import org.eclipse.m2m.atl.emftvm.EmftvmPackage; import org.eclipse.m2m.atl.emftvm.Enditerate; import org.eclipse.m2m.atl.emftvm.ExecEnv; import org.eclipse.m2m.atl.emftvm.Feature; import org.eclipse.m2m.atl.emftvm.Field; import org.eclipse.m2m.atl.emftvm.Findtype; import org.eclipse.m2m.atl.emftvm.Get; import org.eclipse.m2m.atl.emftvm.GetStatic; import org.eclipse.m2m.atl.emftvm.GetSuper; import org.eclipse.m2m.atl.emftvm.GetTrans; import org.eclipse.m2m.atl.emftvm.Getcb; import org.eclipse.m2m.atl.emftvm.Goto; import org.eclipse.m2m.atl.emftvm.If; import org.eclipse.m2m.atl.emftvm.Ifn; import org.eclipse.m2m.atl.emftvm.Ifte; import org.eclipse.m2m.atl.emftvm.Implies; import org.eclipse.m2m.atl.emftvm.InputRuleElement; import org.eclipse.m2m.atl.emftvm.Insert; import org.eclipse.m2m.atl.emftvm.Instruction; import org.eclipse.m2m.atl.emftvm.Invoke; import org.eclipse.m2m.atl.emftvm.InvokeAllCbs; import org.eclipse.m2m.atl.emftvm.InvokeCb; import org.eclipse.m2m.atl.emftvm.InvokeCbS; import org.eclipse.m2m.atl.emftvm.InvokeStatic; import org.eclipse.m2m.atl.emftvm.InvokeSuper; import org.eclipse.m2m.atl.emftvm.Iterate; import org.eclipse.m2m.atl.emftvm.LineNumber; import org.eclipse.m2m.atl.emftvm.Load; import org.eclipse.m2m.atl.emftvm.LocalVariable; import org.eclipse.m2m.atl.emftvm.Match; import org.eclipse.m2m.atl.emftvm.MatchS; import org.eclipse.m2m.atl.emftvm.Model; import org.eclipse.m2m.atl.emftvm.Module; import org.eclipse.m2m.atl.emftvm.New; import org.eclipse.m2m.atl.emftvm.Operation; import org.eclipse.m2m.atl.emftvm.Or; import org.eclipse.m2m.atl.emftvm.Push; import org.eclipse.m2m.atl.emftvm.Remove; import org.eclipse.m2m.atl.emftvm.Rule; import org.eclipse.m2m.atl.emftvm.RuleMode; import org.eclipse.m2m.atl.emftvm.Set; import org.eclipse.m2m.atl.emftvm.SetStatic; import org.eclipse.m2m.atl.emftvm.Store; import org.eclipse.m2m.atl.emftvm.jit.CodeBlockJIT; import org.eclipse.m2m.atl.emftvm.jit.JITCodeBlock; import org.eclipse.m2m.atl.emftvm.util.DuplicateEntryException; import org.eclipse.m2m.atl.emftvm.util.EMFTVMUtil; import org.eclipse.m2m.atl.emftvm.util.LazyBagOnCollection; import org.eclipse.m2m.atl.emftvm.util.LazyList; import org.eclipse.m2m.atl.emftvm.util.LazyListOnList; import org.eclipse.m2m.atl.emftvm.util.LazySetOnSet; import org.eclipse.m2m.atl.emftvm.util.NativeTypes; import org.eclipse.m2m.atl.emftvm.util.StackFrame; import org.eclipse.m2m.atl.emftvm.util.VMException; import org.eclipse.m2m.atl.emftvm.util.VMMonitor; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Code Block</b></em>'. * @author <a href="mailto:[email protected]">Dennis Wagelaar</a> * <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link org.eclipse.m2m.atl.emftvm.impl.CodeBlockImpl#getMaxLocals <em>Max Locals</em>}</li> * <li>{@link org.eclipse.m2m.atl.emftvm.impl.CodeBlockImpl#getMaxStack <em>Max Stack</em>}</li> * <li>{@link org.eclipse.m2m.atl.emftvm.impl.CodeBlockImpl#getCode <em>Code</em>}</li> * <li>{@link org.eclipse.m2m.atl.emftvm.impl.CodeBlockImpl#getLineNumbers <em>Line Numbers</em>}</li> * <li>{@link org.eclipse.m2m.atl.emftvm.impl.CodeBlockImpl#getLocalVariables <em>Local Variables</em>}</li> * <li>{@link org.eclipse.m2m.atl.emftvm.impl.CodeBlockImpl#getMatcherFor <em>Matcher For</em>}</li> * <li>{@link org.eclipse.m2m.atl.emftvm.impl.CodeBlockImpl#getApplierFor <em>Applier For</em>}</li> * <li>{@link org.eclipse.m2m.atl.emftvm.impl.CodeBlockImpl#getPostApplyFor <em>Post Apply For</em>}</li> * <li>{@link org.eclipse.m2m.atl.emftvm.impl.CodeBlockImpl#getBodyFor <em>Body For</em>}</li> * <li>{@link org.eclipse.m2m.atl.emftvm.impl.CodeBlockImpl#getInitialiserFor <em>Initialiser For</em>}</li> * <li>{@link org.eclipse.m2m.atl.emftvm.impl.CodeBlockImpl#getNested <em>Nested</em>}</li> * <li>{@link org.eclipse.m2m.atl.emftvm.impl.CodeBlockImpl#getNestedFor <em>Nested For</em>}</li> * <li>{@link org.eclipse.m2m.atl.emftvm.impl.CodeBlockImpl#getParentFrame <em>Parent Frame</em>}</li> * <li>{@link org.eclipse.m2m.atl.emftvm.impl.CodeBlockImpl#getBindingFor <em>Binding For</em>}</li> * </ul> * </p> * * @generated */ public class CodeBlockImpl extends EObjectImpl implements CodeBlock { /** * The default value of the '{@link #getMaxLocals() <em>Max Locals</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getMaxLocals() * @generated * @ordered */ protected static final int MAX_LOCALS_EDEFAULT = -1; /** * The default value of the '{@link #getMaxStack() <em>Max Stack</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getMaxStack() * @generated * @ordered */ protected static final int MAX_STACK_EDEFAULT = -1; /** * The cached value of the '{@link #getMaxLocals() <em>Max Locals</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getMaxLocals() * @generated NOT * @ordered */ protected int maxLocals = MAX_LOCALS_EDEFAULT; /** * The cached value of the '{@link #getMaxStack() <em>Max Stack</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getMaxStack() * @generated NOT * @ordered */ protected int maxStack = MAX_STACK_EDEFAULT; /** * The cached value of the '{@link #getCode() <em>Code</em>}' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getCode() * @generated * @ordered */ protected EList<Instruction> code; /** * The cached value of the '{@link #getLineNumbers() <em>Line Numbers</em>}' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getLineNumbers() * @generated * @ordered */ protected EList<LineNumber> lineNumbers; /** * The cached value of the '{@link #getLocalVariables() <em>Local Variables</em>}' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getLocalVariables() * @generated * @ordered */ protected EList<LocalVariable> localVariables; /** * The cached value of the '{@link #getNested() <em>Nested</em>}' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getNested() * @generated * @ordered */ protected EList<CodeBlock> nested; /** * The default value of the '{@link #getParentFrame() <em>Parent Frame</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getParentFrame() * @generated * @ordered */ protected static final StackFrame PARENT_FRAME_EDEFAULT = null; /** * The cached value of the '{@link #getParentFrame() <em>Parent Frame</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getParentFrame() * @generated * @ordered */ protected StackFrame parentFrame = PARENT_FRAME_EDEFAULT; /** * Singleton instance of the {@link ExecEnv} {@link EClass}. */ protected static final EClass EXEC_ENV = EmftvmPackage.eINSTANCE.getExecEnv(); private static final Object[] EMPTY = new Object[0]; private static final EObject[] EEMPTY = new EObject[0]; private static final int JIT_THRESHOLD = 100; // require > JIT_THRESHOLD runs before JIT-ing private boolean ruleSet; private Rule rule; private Map<Instruction, EList<Instruction>> predecessors = new HashMap<Instruction, EList<Instruction>>(); private Map<Instruction, EList<Instruction>> allPredecessors = new HashMap<Instruction, EList<Instruction>>(); private Map<Instruction, EList<Instruction>> nlPredecessors = new HashMap<Instruction, EList<Instruction>>(); private JITCodeBlock jitCodeBlock; private int runcount; /** * <!-- begin-user-doc --> * Creates a new {@link CodeBlockImpl}. * <!-- end-user-doc --> * @generated */ protected CodeBlockImpl() { super(); } /** * <!-- begin-user-doc --> * Returns the {@link EClass} that correspond to this metaclass. * @return the {@link EClass} that correspond to this metaclass. * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return EmftvmPackage.Literals.CODE_BLOCK; } /** * <!-- begin-user-doc. --> * {@inheritDoc} * <!-- end-user-doc --> * @generated NOT */ public int getMaxLocals() { if (maxLocals == MAX_LOCALS_EDEFAULT) { for (LocalVariable lv : getLocalVariables()) { maxLocals = Math.max(maxLocals, lv.getSlot()); } maxLocals++; // highest index + 1 } return maxLocals; } /** * <!-- begin-user-doc. --> * {@inheritDoc} * <!-- end-user-doc --> * @generated NOT */ public void setMaxLocals(int newMaxLocals) { int oldMaxLocals = maxLocals; maxLocals = newMaxLocals; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, EmftvmPackage.CODE_BLOCK__MAX_LOCALS, oldMaxLocals, maxLocals)); } /** * <!-- begin-user-doc. --> * {@inheritDoc} * <!-- end-user-doc --> * @generated NOT */ public int getMaxStack() { if (maxStack == MAX_STACK_EDEFAULT) { maxStack = 0; for (Instruction instr : getCode()) { maxStack = Math.max(maxStack, instr.getStackLevel()); } } return maxStack; } /** * <!-- begin-user-doc. --> * {@inheritDoc} * <!-- end-user-doc --> * @generated NOT */ public void setMaxStack(int newMaxStack) { int oldMaxStack = maxStack; maxStack = newMaxStack; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, EmftvmPackage.CODE_BLOCK__MAX_STACK, oldMaxStack, maxStack)); } /** * <!-- begin-user-doc. --> * {@inheritDoc} * <!-- end-user-doc --> * @generated */ public EList<Instruction> getCode() { if (code == null) { code = new EObjectContainmentWithInverseEList<Instruction>(Instruction.class, this, EmftvmPackage.CODE_BLOCK__CODE, EmftvmPackage.INSTRUCTION__OWNING_BLOCK); } return code; } /** * <!-- begin-user-doc. --> * {@inheritDoc} * <!-- end-user-doc --> * @generated */ public EList<LineNumber> getLineNumbers() { if (lineNumbers == null) { lineNumbers = new EObjectContainmentWithInverseEList<LineNumber>(LineNumber.class, this, EmftvmPackage.CODE_BLOCK__LINE_NUMBERS, EmftvmPackage.LINE_NUMBER__OWNING_BLOCK); } return lineNumbers; } /** * <!-- begin-user-doc. --> * {@inheritDoc} * <!-- end-user-doc --> * @generated */ public EList<LocalVariable> getLocalVariables() { if (localVariables == null) { localVariables = new EObjectContainmentWithInverseEList<LocalVariable>(LocalVariable.class, this, EmftvmPackage.CODE_BLOCK__LOCAL_VARIABLES, EmftvmPackage.LOCAL_VARIABLE__OWNING_BLOCK); } return localVariables; } /** * <!-- begin-user-doc. --> * {@inheritDoc} * <!-- end-user-doc --> * @generated */ public Rule getMatcherFor() { if (eContainerFeatureID() != EmftvmPackage.CODE_BLOCK__MATCHER_FOR) return null; return (Rule)eContainer(); } /** * <!-- begin-user-doc. --> * @see CodeBlockImpl#setMatcherFor(Rule) * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetMatcherFor(Rule newMatcherFor, NotificationChain msgs) { msgs = eBasicSetContainer((InternalEObject)newMatcherFor, EmftvmPackage.CODE_BLOCK__MATCHER_FOR, msgs); return msgs; } /** * <!-- begin-user-doc. --> * {@inheritDoc} * <!-- end-user-doc --> * @generated */ public void setMatcherFor(Rule newMatcherFor) { if (newMatcherFor != eInternalContainer() || (eContainerFeatureID() != EmftvmPackage.CODE_BLOCK__MATCHER_FOR && newMatcherFor != null)) { if (EcoreUtil.isAncestor(this, newMatcherFor)) throw new IllegalArgumentException("Recursive containment not allowed for " + toString()); NotificationChain msgs = null; if (eInternalContainer() != null) msgs = eBasicRemoveFromContainer(msgs); if (newMatcherFor != null) msgs = ((InternalEObject)newMatcherFor).eInverseAdd(this, EmftvmPackage.RULE__MATCHER, Rule.class, msgs); msgs = basicSetMatcherFor(newMatcherFor, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, EmftvmPackage.CODE_BLOCK__MATCHER_FOR, newMatcherFor, newMatcherFor)); } /** * <!-- begin-user-doc. --> * {@inheritDoc} * <!-- end-user-doc --> * @generated */ public Rule getApplierFor() { if (eContainerFeatureID() != EmftvmPackage.CODE_BLOCK__APPLIER_FOR) return null; return (Rule)eContainer(); } /** * <!-- begin-user-doc. --> * @see #setApplierFor(Rule) * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetApplierFor(Rule newApplierFor, NotificationChain msgs) { msgs = eBasicSetContainer((InternalEObject)newApplierFor, EmftvmPackage.CODE_BLOCK__APPLIER_FOR, msgs); return msgs; } /** * <!-- begin-user-doc. --> * {@inheritDoc} * <!-- end-user-doc --> * @generated */ public void setApplierFor(Rule newApplierFor) { if (newApplierFor != eInternalContainer() || (eContainerFeatureID() != EmftvmPackage.CODE_BLOCK__APPLIER_FOR && newApplierFor != null)) { if (EcoreUtil.isAncestor(this, newApplierFor)) throw new IllegalArgumentException("Recursive containment not allowed for " + toString()); NotificationChain msgs = null; if (eInternalContainer() != null) msgs = eBasicRemoveFromContainer(msgs); if (newApplierFor != null) msgs = ((InternalEObject)newApplierFor).eInverseAdd(this, EmftvmPackage.RULE__APPLIER, Rule.class, msgs); msgs = basicSetApplierFor(newApplierFor, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, EmftvmPackage.CODE_BLOCK__APPLIER_FOR, newApplierFor, newApplierFor)); } /** * <!-- begin-user-doc. --> * {@inheritDoc} * <!-- end-user-doc --> * @generated */ public Rule getPostApplyFor() { if (eContainerFeatureID() != EmftvmPackage.CODE_BLOCK__POST_APPLY_FOR) return null; return (Rule)eContainer(); } /** * <!-- begin-user-doc. --> * @see #setPostApplyFor(Rule) * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetPostApplyFor(Rule newPostApplyFor, NotificationChain msgs) { msgs = eBasicSetContainer((InternalEObject)newPostApplyFor, EmftvmPackage.CODE_BLOCK__POST_APPLY_FOR, msgs); return msgs; } /** * <!-- begin-user-doc. --> * {@inheritDoc} * <!-- end-user-doc --> * @generated */ public void setPostApplyFor(Rule newPostApplyFor) { if (newPostApplyFor != eInternalContainer() || (eContainerFeatureID() != EmftvmPackage.CODE_BLOCK__POST_APPLY_FOR && newPostApplyFor != null)) { if (EcoreUtil.isAncestor(this, newPostApplyFor)) throw new IllegalArgumentException("Recursive containment not allowed for " + toString()); NotificationChain msgs = null; if (eInternalContainer() != null) msgs = eBasicRemoveFromContainer(msgs); if (newPostApplyFor != null) msgs = ((InternalEObject)newPostApplyFor).eInverseAdd(this, EmftvmPackage.RULE__POST_APPLY, Rule.class, msgs); msgs = basicSetPostApplyFor(newPostApplyFor, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, EmftvmPackage.CODE_BLOCK__POST_APPLY_FOR, newPostApplyFor, newPostApplyFor)); } /** * <!-- begin-user-doc. --> * {@inheritDoc} * <!-- end-user-doc --> * @generated */ public Operation getBodyFor() { if (eContainerFeatureID() != EmftvmPackage.CODE_BLOCK__BODY_FOR) return null; return (Operation)eContainer(); } /** * <!-- begin-user-doc. --> * @see #setBodyFor(Operation) * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetBodyFor(Operation newBodyFor, NotificationChain msgs) { msgs = eBasicSetContainer((InternalEObject)newBodyFor, EmftvmPackage.CODE_BLOCK__BODY_FOR, msgs); return msgs; } /** * <!-- begin-user-doc. --> * {@inheritDoc} * <!-- end-user-doc --> * @generated */ public void setBodyFor(Operation newBodyFor) { if (newBodyFor != eInternalContainer() || (eContainerFeatureID() != EmftvmPackage.CODE_BLOCK__BODY_FOR && newBodyFor != null)) { if (EcoreUtil.isAncestor(this, newBodyFor)) throw new IllegalArgumentException("Recursive containment not allowed for " + toString()); NotificationChain msgs = null; if (eInternalContainer() != null) msgs = eBasicRemoveFromContainer(msgs); if (newBodyFor != null) msgs = ((InternalEObject)newBodyFor).eInverseAdd(this, EmftvmPackage.OPERATION__BODY, Operation.class, msgs); msgs = basicSetBodyFor(newBodyFor, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, EmftvmPackage.CODE_BLOCK__BODY_FOR, newBodyFor, newBodyFor)); } /** * <!-- begin-user-doc. --> * {@inheritDoc} * <!-- end-user-doc --> * @generated */ public Field getInitialiserFor() { if (eContainerFeatureID() != EmftvmPackage.CODE_BLOCK__INITIALISER_FOR) return null; return (Field)eContainer(); } /** * <!-- begin-user-doc. --> * @see #setInitialiserFor(Field) * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetInitialiserFor(Field newInitialiserFor, NotificationChain msgs) { msgs = eBasicSetContainer((InternalEObject)newInitialiserFor, EmftvmPackage.CODE_BLOCK__INITIALISER_FOR, msgs); return msgs; } /** * <!-- begin-user-doc. --> * {@inheritDoc} * <!-- end-user-doc --> * @generated */ public void setInitialiserFor(Field newInitialiserFor) { if (newInitialiserFor != eInternalContainer() || (eContainerFeatureID() != EmftvmPackage.CODE_BLOCK__INITIALISER_FOR && newInitialiserFor != null)) { if (EcoreUtil.isAncestor(this, newInitialiserFor)) throw new IllegalArgumentException("Recursive containment not allowed for " + toString()); NotificationChain msgs = null; if (eInternalContainer() != null) msgs = eBasicRemoveFromContainer(msgs); if (newInitialiserFor != null) msgs = ((InternalEObject)newInitialiserFor).eInverseAdd(this, EmftvmPackage.FIELD__INITIALISER, Field.class, msgs); msgs = basicSetInitialiserFor(newInitialiserFor, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, EmftvmPackage.CODE_BLOCK__INITIALISER_FOR, newInitialiserFor, newInitialiserFor)); } /** * <!-- begin-user-doc. --> * {@inheritDoc} * <!-- end-user-doc --> * @generated */ public EList<CodeBlock> getNested() { if (nested == null) { nested = new EObjectContainmentWithInverseEList<CodeBlock>(CodeBlock.class, this, EmftvmPackage.CODE_BLOCK__NESTED, EmftvmPackage.CODE_BLOCK__NESTED_FOR); } return nested; } /** * <!-- begin-user-doc. --> * {@inheritDoc} * <!-- end-user-doc --> * @generated */ public CodeBlock getNestedFor() { if (eContainerFeatureID() != EmftvmPackage.CODE_BLOCK__NESTED_FOR) return null; return (CodeBlock)eContainer(); } /** * <!-- begin-user-doc. --> * @see #setNestedFor(CodeBlock) * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetNestedFor(CodeBlock newNestedFor, NotificationChain msgs) { msgs = eBasicSetContainer((InternalEObject)newNestedFor, EmftvmPackage.CODE_BLOCK__NESTED_FOR, msgs); return msgs; } /** * <!-- begin-user-doc. --> * {@inheritDoc} * <!-- end-user-doc --> * @generated */ public void setNestedFor(CodeBlock newNestedFor) { if (newNestedFor != eInternalContainer() || (eContainerFeatureID() != EmftvmPackage.CODE_BLOCK__NESTED_FOR && newNestedFor != null)) { if (EcoreUtil.isAncestor(this, newNestedFor)) throw new IllegalArgumentException("Recursive containment not allowed for " + toString()); NotificationChain msgs = null; if (eInternalContainer() != null) msgs = eBasicRemoveFromContainer(msgs); if (newNestedFor != null) msgs = ((InternalEObject)newNestedFor).eInverseAdd(this, EmftvmPackage.CODE_BLOCK__NESTED, CodeBlock.class, msgs); msgs = basicSetNestedFor(newNestedFor, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, EmftvmPackage.CODE_BLOCK__NESTED_FOR, newNestedFor, newNestedFor)); } /** * <!-- begin-user-doc. --> * {@inheritDoc} * <!-- end-user-doc --> * @generated */ public StackFrame getParentFrame() { return parentFrame; } /** * <!-- begin-user-doc. --> * {@inheritDoc} * <!-- end-user-doc --> * @generated */ public void setParentFrame(StackFrame newParentFrame) { StackFrame oldParentFrame = parentFrame; parentFrame = newParentFrame; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, EmftvmPackage.CODE_BLOCK__PARENT_FRAME, oldParentFrame, parentFrame)); } /** * <!-- begin-user-doc. --> * {@inheritDoc} * <!-- end-user-doc --> * @generated */ public InputRuleElement getBindingFor() { if (eContainerFeatureID() != EmftvmPackage.CODE_BLOCK__BINDING_FOR) return null; return (InputRuleElement)eContainer(); } /** * <!-- begin-user-doc. --> * @see #setBindingFor(InputRuleElement) * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetBindingFor(InputRuleElement newBindingFor, NotificationChain msgs) { msgs = eBasicSetContainer((InternalEObject)newBindingFor, EmftvmPackage.CODE_BLOCK__BINDING_FOR, msgs); return msgs; } /** * <!-- begin-user-doc. --> * {@inheritDoc} * <!-- end-user-doc --> * @generated */ public void setBindingFor(InputRuleElement newBindingFor) { if (newBindingFor != eInternalContainer() || (eContainerFeatureID() != EmftvmPackage.CODE_BLOCK__BINDING_FOR && newBindingFor != null)) { if (EcoreUtil.isAncestor(this, newBindingFor)) throw new IllegalArgumentException("Recursive containment not allowed for " + toString()); NotificationChain msgs = null; if (eInternalContainer() != null) msgs = eBasicRemoveFromContainer(msgs); if (newBindingFor != null) msgs = ((InternalEObject)newBindingFor).eInverseAdd(this, EmftvmPackage.INPUT_RULE_ELEMENT__BINDING, InputRuleElement.class, msgs); msgs = basicSetBindingFor(newBindingFor, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, EmftvmPackage.CODE_BLOCK__BINDING_FOR, newBindingFor, newBindingFor)); } /** * <!-- begin-user-doc. --> * {@inheritDoc} * @see org.eclipse.m2m.atl.emftvm.CodeBlock#execute(StackFrame) * <!-- end-user-doc --> * @generated NOT */ public StackFrame execute(final StackFrame frame) { final JITCodeBlock jcb = getJITCodeBlock(); if (jcb != null) { return jcb.execute(frame); } runcount += 1; // increase invocation counter to trigger JIT int pc = 0; final EList<Instruction> code = getCode(); final int codeSize = code.size(); final ExecEnv env = frame.getEnv(); final VMMonitor monitor = env.getMonitor(); CodeBlock cb; StackFrame rFrame; int argcount; if (monitor != null) { monitor.enter(frame); } try { LOOP: while (pc < codeSize) { Instruction instr = code.get(pc++); if (monitor != null) { if (monitor.isTerminated()) { throw new VMException(frame, "Execution terminated."); } else { frame.setPc(pc); monitor.step(frame); } } switch (instr.getOpcode()) { case PUSH: frame.push(((Push)instr).getValue()); break; case PUSHT: frame.push(true); break; case PUSHF: frame.push(false); break; case POP: frame.popv(); break; case LOAD: frame.load(((Load)instr).getCbOffset(), ((Load)instr).getSlot()); break; case STORE: frame.store(((Store)instr).getCbOffset(), ((Store)instr).getSlot()); break; case SET: set(frame.pop(), frame.pop(), ((Set)instr).getFieldname(), env); break; case GET: frame.setPc(pc); frame.push(get(((Get)instr).getFieldname(), frame)); break; case GET_TRANS: frame.setPc(pc); frame.push(getTrans(((GetTrans)instr).getFieldname(), frame)); break; case SET_STATIC: setStatic(frame.pop(), frame.pop(), ((SetStatic)instr).getFieldname(), env); break; case GET_STATIC: frame.setPc(pc); frame.push(getStatic(((GetStatic)instr).getFieldname(), frame)); break; case FINDTYPE: frame.push(frame.getEnv().findType( ((Findtype)instr).getModelname(), ((Findtype)instr).getTypename())); break; case FINDTYPE_S: frame.push(frame.getEnv().findType( (String)frame.pop(), (String)frame.pop())); break; case NEW: frame.push(newInstr(((New)instr).getModelname(), frame.pop(), frame)); break; case NEW_S: frame.push(newInstr((String)frame.pop(), frame.pop(), frame)); break; case DELETE: delete(frame); break; case DUP: frame.dup(); break; case DUP_X1: frame.dupX1(); break; case SWAP: frame.swap(); break; case SWAP_X1: frame.swapX1(); break; case IF: if ((Boolean)frame.pop()) { pc = ((If)instr).getOffset(); } break; case IFN: if (!(Boolean)frame.pop()) { pc = ((Ifn)instr).getOffset(); } break; case GOTO: pc = ((Goto)instr).getOffset(); break; case ITERATE: Iterator<?> i = ((Collection<?>)frame.pop()).iterator(); if (i.hasNext()) { frame.push(i); frame.push(i.next()); } else { pc = ((Iterate)instr).getOffset(); // jump over ENDITERATE } break; case ENDITERATE: i = (Iterator<?>)frame.pop(); if (i.hasNext()) { frame.push(i); frame.push(i.next()); pc = ((Enditerate)instr).getOffset(); // jump to first loop instruction } break; case INVOKE: frame.setPc(pc); frame.push(invoke((Invoke)instr, frame)); break; case INVOKE_STATIC: frame.setPc(pc); frame.push(invokeStatic(((InvokeStatic)instr).getOpname(), ((InvokeStatic)instr).getArgcount(), frame)); break; case INVOKE_SUPER: frame.setPc(pc); frame.push(invokeSuper(getOperation(), ((InvokeSuper)instr).getOpname(), ((InvokeSuper)instr).getArgcount(), frame)); break; case ALLINST: frame.push(EMFTVMUtil.findAllInstances((EClass)frame.pop(), frame.getEnv())); break; case ALLINST_IN: frame.push(EMFTVMUtil.findAllInstIn(frame.pop(), (EClass)frame.pop(), frame.getEnv())); break; case ISNULL: frame.push(frame.pop() == null); break; case GETENVTYPE: frame.push(EXEC_ENV); break; case NOT: frame.push(!(Boolean)frame.pop()); break; case AND: cb = ((And)instr).getCodeBlock(); frame.setPc(pc); frame.push((Boolean)frame.pop() && - (Boolean)cb.execute(frame.getSubFrame(cb, null)).pop()); + (Boolean)cb.execute(new StackFrame(frame, cb)).pop()); break; case OR: cb = ((Or)instr).getCodeBlock(); frame.setPc(pc); frame.push((Boolean)frame.pop() || - (Boolean)cb.execute(frame.getSubFrame(cb, null)).pop()); + (Boolean)cb.execute(new StackFrame(frame, cb)).pop()); break; case XOR: frame.push((Boolean)frame.pop() ^ (Boolean)frame.pop()); break; case IMPLIES: cb = ((Implies)instr).getCodeBlock(); frame.setPc(pc); frame.push(!(Boolean)frame.pop() || - (Boolean)cb.execute(frame.getSubFrame(cb, null)).pop()); + (Boolean)cb.execute(new StackFrame(frame, cb)).pop()); break; case IFTE: frame.setPc(pc); if ((Boolean)frame.pop()) { cb = ((Ifte)instr).getThenCb(); } else { cb = ((Ifte)instr).getElseCb(); } - frame.push(cb.execute(frame.getSubFrame(cb, null)).pop()); + frame.push(cb.execute(new StackFrame(frame, cb)).pop()); break; case RETURN: break LOOP; case GETCB: frame.push(((Getcb)instr).getCodeBlock()); break; case INVOKE_ALL_CBS: frame.setPc(pc); // Use Java's left-to-right evaluation semantics: // stack = [..., arg1, arg2] argcount = ((InvokeAllCbs)instr).getArgcount(); Object[] args = argcount > 0 ? frame.pop(argcount) : EMPTY; for (CodeBlock ncb : getNested()) { rFrame = ncb.execute(frame.getSubFrame(ncb, args)); if (!rFrame.stackEmpty()) { frame.push(rFrame.pop()); } } break; case INVOKE_CB: cb = ((InvokeCb)instr).getCodeBlock(); frame.setPc(pc); // Use Java's left-to-right evaluation semantics: // stack = [..., arg1, arg2] argcount = ((InvokeCb)instr).getArgcount(); rFrame = cb.execute(frame.getSubFrame(cb, argcount > 0 ? frame.pop(argcount) : EMPTY)); if (!rFrame.stackEmpty()) { frame.push(rFrame.pop()); } break; case INVOKE_CB_S: cb = (CodeBlock)frame.pop(); frame.setPc(pc); // Use Java's left-to-right evaluation semantics: // stack = [..., arg1, arg2] argcount = ((InvokeCbS)instr).getArgcount(); rFrame = cb.execute(frame.getSubFrame(cb, argcount > 0 ? frame.pop(argcount) : EMPTY)); if (!rFrame.stackEmpty()) { frame.push(rFrame.pop()); } else { frame.push(null); // unknown code block => always produce one stack element } break; case MATCH: frame.setPc(pc); // Use Java's left-to-right evaluation semantics: // stack = [..., arg1, arg2] argcount = ((Match)instr).getArgcount(); frame.push(argcount > 0 ? matchOne(frame, findRule(frame.getEnv(), ((Match)instr).getRulename()), frame.pop(argcount, new EObject[argcount])) : matchOne(frame, findRule(frame.getEnv(), ((Match)instr).getRulename()))); break; case MATCH_S: frame.setPc(pc); // stack = [..., arg1, arg2, rule] argcount = ((MatchS)instr).getArgcount(); frame.push(argcount > 0 ? matchOne(frame, (Rule)frame.pop(), frame.pop(argcount, new EObject[argcount])) : matchOne(frame, (Rule)frame.pop())); break; case ADD: add(-1, frame.pop(), frame.pop(), ((Add)instr).getFieldname(), env); break; case REMOVE: remove(frame.pop(), frame.pop(), ((Remove)instr).getFieldname(), env); break; case INSERT: add((Integer)frame.pop(), frame.pop(), frame.pop(), ((Insert)instr).getFieldname(), env); break; case GET_SUPER: frame.setPc(pc); frame.push(getSuper(getField(), ((GetSuper)instr).getFieldname(), frame)); break; case GETENV: frame.push(env); break; default: throw new VMException(frame, String.format("Unsupported opcode: %s", instr.getOpcode())); } // switch } // while } catch (VMException e) { throw e; } catch (Exception e) { frame.setPc(pc); throw new VMException(frame, e); } if (monitor != null) { monitor.leave(frame); } final CodeBlockJIT jc = env.getJITCompiler(); if (jc != null && runcount > JIT_THRESHOLD && getJITCodeBlock() == null) { // JIT everything that runs more than JIT_THRESHOLD try { setJITCodeBlock(jc.jit(this)); } catch (Exception e) { frame.setPc(pc); throw new VMException(frame, e); } } return frame; } /** * <!-- begin-user-doc. --> * {@inheritDoc} * <!-- end-user-doc --> * @generated NOT */ public int getStackLevel() { final EList<Instruction> code = getCode(); if (code.isEmpty()) { return 0; } return code.get(code.size() - 1).getStackLevel(); } /** * <!-- begin-user-doc. --> * {@inheritDoc} * <!-- end-user-doc --> * @generated NOT */ public Module getModule() { final EObject container = eContainer(); if (container != null) { switch (container.eClass().getClassifierID()) { case EmftvmPackage.FEATURE: case EmftvmPackage.FIELD: case EmftvmPackage.OPERATION: return ((Feature)container).getModule(); case EmftvmPackage.RULE: return ((Rule)container).getModule(); case EmftvmPackage.INPUT_RULE_ELEMENT: return ((InputRuleElement)container).getInputFor().getModule(); case EmftvmPackage.CODE_BLOCK: return ((CodeBlock)container).getModule(); default: break; } } return null; } /** * <!-- begin-user-doc. --> * {@inheritDoc} * <!-- end-user-doc --> * @generated NOT */ public Operation getOperation() { final EObject container = eContainer(); if (container != null) { switch (container.eClass().getClassifierID()) { case EmftvmPackage.OPERATION: return (Operation)container; case EmftvmPackage.CODE_BLOCK: return ((CodeBlock)container).getOperation(); default: break; } } return null; } /** * <!-- begin-user-doc. --> * {@inheritDoc} * <!-- end-user-doc --> * @generated NOT */ public Field getField() { final EObject container = eContainer(); if (container != null) { switch (container.eClass().getClassifierID()) { case EmftvmPackage.FIELD: return (Field)container; case EmftvmPackage.CODE_BLOCK: return ((CodeBlock)container).getField(); default: break; } } return null; } /** * <!-- begin-user-doc. --> * {@inheritDoc} * <!-- end-user-doc --> * @generated NOT */ public EList<Instruction> getPredecessors(final Instruction i) { if (!predecessors.containsKey(i)) { final EList<Instruction> preds = new BasicEList<Instruction>(); final EList<Instruction> code = getCode(); final int index = code.indexOf(i); assert index > -1; if (index > 0) { Instruction prev = code.get(index - 1); if (!(prev instanceof Goto)) { preds.add(prev); } for (Instruction i2 : code) { if (i2 instanceof BranchInstruction && ((BranchInstruction)i2).getTarget() == prev) { preds.add(i2); } } } predecessors.put(i, ECollections.unmodifiableEList(preds)); } return predecessors.get(i); } /** * <!-- begin-user-doc. --> * {@inheritDoc} * <!-- end-user-doc --> * @generated NOT */ public EList<Instruction> getAllPredecessors(final Instruction i) { if (!allPredecessors.containsKey(i)) { final EList<Instruction> predecessors = new BasicEList<Instruction>(); allPredecessors(i, predecessors); allPredecessors.put(i, ECollections.unmodifiableEList(predecessors)); } return allPredecessors.get(i); } /** * Collects the transitive closure of predecessor instructions for <code>i</code>. * @param i the instruction to collect the predecessors for. * @param currentPreds the predecessor instructions. * @return the predecessor instructions. */ private EList<Instruction> allPredecessors(final Instruction i, final EList<Instruction> currentPreds) { final EList<Instruction> preds = getPredecessors(i); for (Instruction pred : preds) { if (!currentPreds.contains(pred)) { currentPreds.add(pred); allPredecessors(pred, currentPreds); } } return currentPreds; } /** * <!-- begin-user-doc. --> * {@inheritDoc} * <!-- end-user-doc --> * @generated NOT */ public EList<Instruction> getNonLoopingPredecessors(Instruction i) { if (!nlPredecessors.containsKey(i)) { final EList<Instruction> code = getCode(); final int index = code.indexOf(i); final EList<Instruction> preds = new BasicEList<Instruction>(); for (Instruction p : getPredecessors(i)) { if (code.indexOf(p) < index || !getAllPredecessors(p).contains(i)) { preds.add(p); } } nlPredecessors.put(i, ECollections.unmodifiableEList(preds)); } return nlPredecessors.get(i); } /** * <!-- begin-user-doc. --> * {@inheritDoc} * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case EmftvmPackage.CODE_BLOCK__CODE: return ((InternalEList<InternalEObject>)(InternalEList<?>)getCode()).basicAdd(otherEnd, msgs); case EmftvmPackage.CODE_BLOCK__LINE_NUMBERS: return ((InternalEList<InternalEObject>)(InternalEList<?>)getLineNumbers()).basicAdd(otherEnd, msgs); case EmftvmPackage.CODE_BLOCK__LOCAL_VARIABLES: return ((InternalEList<InternalEObject>)(InternalEList<?>)getLocalVariables()).basicAdd(otherEnd, msgs); case EmftvmPackage.CODE_BLOCK__MATCHER_FOR: if (eInternalContainer() != null) msgs = eBasicRemoveFromContainer(msgs); return basicSetMatcherFor((Rule)otherEnd, msgs); case EmftvmPackage.CODE_BLOCK__APPLIER_FOR: if (eInternalContainer() != null) msgs = eBasicRemoveFromContainer(msgs); return basicSetApplierFor((Rule)otherEnd, msgs); case EmftvmPackage.CODE_BLOCK__POST_APPLY_FOR: if (eInternalContainer() != null) msgs = eBasicRemoveFromContainer(msgs); return basicSetPostApplyFor((Rule)otherEnd, msgs); case EmftvmPackage.CODE_BLOCK__BODY_FOR: if (eInternalContainer() != null) msgs = eBasicRemoveFromContainer(msgs); return basicSetBodyFor((Operation)otherEnd, msgs); case EmftvmPackage.CODE_BLOCK__INITIALISER_FOR: if (eInternalContainer() != null) msgs = eBasicRemoveFromContainer(msgs); return basicSetInitialiserFor((Field)otherEnd, msgs); case EmftvmPackage.CODE_BLOCK__NESTED: return ((InternalEList<InternalEObject>)(InternalEList<?>)getNested()).basicAdd(otherEnd, msgs); case EmftvmPackage.CODE_BLOCK__NESTED_FOR: if (eInternalContainer() != null) msgs = eBasicRemoveFromContainer(msgs); return basicSetNestedFor((CodeBlock)otherEnd, msgs); case EmftvmPackage.CODE_BLOCK__BINDING_FOR: if (eInternalContainer() != null) msgs = eBasicRemoveFromContainer(msgs); return basicSetBindingFor((InputRuleElement)otherEnd, msgs); } return super.eInverseAdd(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc. --> * {@inheritDoc} * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case EmftvmPackage.CODE_BLOCK__CODE: return ((InternalEList<?>)getCode()).basicRemove(otherEnd, msgs); case EmftvmPackage.CODE_BLOCK__LINE_NUMBERS: return ((InternalEList<?>)getLineNumbers()).basicRemove(otherEnd, msgs); case EmftvmPackage.CODE_BLOCK__LOCAL_VARIABLES: return ((InternalEList<?>)getLocalVariables()).basicRemove(otherEnd, msgs); case EmftvmPackage.CODE_BLOCK__MATCHER_FOR: return basicSetMatcherFor(null, msgs); case EmftvmPackage.CODE_BLOCK__APPLIER_FOR: return basicSetApplierFor(null, msgs); case EmftvmPackage.CODE_BLOCK__POST_APPLY_FOR: return basicSetPostApplyFor(null, msgs); case EmftvmPackage.CODE_BLOCK__BODY_FOR: return basicSetBodyFor(null, msgs); case EmftvmPackage.CODE_BLOCK__INITIALISER_FOR: return basicSetInitialiserFor(null, msgs); case EmftvmPackage.CODE_BLOCK__NESTED: return ((InternalEList<?>)getNested()).basicRemove(otherEnd, msgs); case EmftvmPackage.CODE_BLOCK__NESTED_FOR: return basicSetNestedFor(null, msgs); case EmftvmPackage.CODE_BLOCK__BINDING_FOR: return basicSetBindingFor(null, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc. --> * {@inheritDoc} * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eBasicRemoveFromContainerFeature(NotificationChain msgs) { switch (eContainerFeatureID()) { case EmftvmPackage.CODE_BLOCK__MATCHER_FOR: return eInternalContainer().eInverseRemove(this, EmftvmPackage.RULE__MATCHER, Rule.class, msgs); case EmftvmPackage.CODE_BLOCK__APPLIER_FOR: return eInternalContainer().eInverseRemove(this, EmftvmPackage.RULE__APPLIER, Rule.class, msgs); case EmftvmPackage.CODE_BLOCK__POST_APPLY_FOR: return eInternalContainer().eInverseRemove(this, EmftvmPackage.RULE__POST_APPLY, Rule.class, msgs); case EmftvmPackage.CODE_BLOCK__BODY_FOR: return eInternalContainer().eInverseRemove(this, EmftvmPackage.OPERATION__BODY, Operation.class, msgs); case EmftvmPackage.CODE_BLOCK__INITIALISER_FOR: return eInternalContainer().eInverseRemove(this, EmftvmPackage.FIELD__INITIALISER, Field.class, msgs); case EmftvmPackage.CODE_BLOCK__NESTED_FOR: return eInternalContainer().eInverseRemove(this, EmftvmPackage.CODE_BLOCK__NESTED, CodeBlock.class, msgs); case EmftvmPackage.CODE_BLOCK__BINDING_FOR: return eInternalContainer().eInverseRemove(this, EmftvmPackage.INPUT_RULE_ELEMENT__BINDING, InputRuleElement.class, msgs); } return super.eBasicRemoveFromContainerFeature(msgs); } /** * <!-- begin-user-doc. --> * {@inheritDoc} * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case EmftvmPackage.CODE_BLOCK__MAX_LOCALS: return getMaxLocals(); case EmftvmPackage.CODE_BLOCK__MAX_STACK: return getMaxStack(); case EmftvmPackage.CODE_BLOCK__CODE: return getCode(); case EmftvmPackage.CODE_BLOCK__LINE_NUMBERS: return getLineNumbers(); case EmftvmPackage.CODE_BLOCK__LOCAL_VARIABLES: return getLocalVariables(); case EmftvmPackage.CODE_BLOCK__MATCHER_FOR: return getMatcherFor(); case EmftvmPackage.CODE_BLOCK__APPLIER_FOR: return getApplierFor(); case EmftvmPackage.CODE_BLOCK__POST_APPLY_FOR: return getPostApplyFor(); case EmftvmPackage.CODE_BLOCK__BODY_FOR: return getBodyFor(); case EmftvmPackage.CODE_BLOCK__INITIALISER_FOR: return getInitialiserFor(); case EmftvmPackage.CODE_BLOCK__NESTED: return getNested(); case EmftvmPackage.CODE_BLOCK__NESTED_FOR: return getNestedFor(); case EmftvmPackage.CODE_BLOCK__PARENT_FRAME: return getParentFrame(); case EmftvmPackage.CODE_BLOCK__BINDING_FOR: return getBindingFor(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc. --> * {@inheritDoc} * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case EmftvmPackage.CODE_BLOCK__MAX_LOCALS: setMaxLocals((Integer)newValue); return; case EmftvmPackage.CODE_BLOCK__MAX_STACK: setMaxStack((Integer)newValue); return; case EmftvmPackage.CODE_BLOCK__CODE: getCode().clear(); getCode().addAll((Collection<? extends Instruction>)newValue); return; case EmftvmPackage.CODE_BLOCK__LINE_NUMBERS: getLineNumbers().clear(); getLineNumbers().addAll((Collection<? extends LineNumber>)newValue); return; case EmftvmPackage.CODE_BLOCK__LOCAL_VARIABLES: getLocalVariables().clear(); getLocalVariables().addAll((Collection<? extends LocalVariable>)newValue); return; case EmftvmPackage.CODE_BLOCK__MATCHER_FOR: setMatcherFor((Rule)newValue); return; case EmftvmPackage.CODE_BLOCK__APPLIER_FOR: setApplierFor((Rule)newValue); return; case EmftvmPackage.CODE_BLOCK__POST_APPLY_FOR: setPostApplyFor((Rule)newValue); return; case EmftvmPackage.CODE_BLOCK__BODY_FOR: setBodyFor((Operation)newValue); return; case EmftvmPackage.CODE_BLOCK__INITIALISER_FOR: setInitialiserFor((Field)newValue); return; case EmftvmPackage.CODE_BLOCK__NESTED: getNested().clear(); getNested().addAll((Collection<? extends CodeBlock>)newValue); return; case EmftvmPackage.CODE_BLOCK__NESTED_FOR: setNestedFor((CodeBlock)newValue); return; case EmftvmPackage.CODE_BLOCK__PARENT_FRAME: setParentFrame((StackFrame)newValue); return; case EmftvmPackage.CODE_BLOCK__BINDING_FOR: setBindingFor((InputRuleElement)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc. --> * {@inheritDoc} * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case EmftvmPackage.CODE_BLOCK__MAX_LOCALS: setMaxLocals(MAX_LOCALS_EDEFAULT); return; case EmftvmPackage.CODE_BLOCK__MAX_STACK: setMaxStack(MAX_STACK_EDEFAULT); return; case EmftvmPackage.CODE_BLOCK__CODE: getCode().clear(); return; case EmftvmPackage.CODE_BLOCK__LINE_NUMBERS: getLineNumbers().clear(); return; case EmftvmPackage.CODE_BLOCK__LOCAL_VARIABLES: getLocalVariables().clear(); return; case EmftvmPackage.CODE_BLOCK__MATCHER_FOR: setMatcherFor((Rule)null); return; case EmftvmPackage.CODE_BLOCK__APPLIER_FOR: setApplierFor((Rule)null); return; case EmftvmPackage.CODE_BLOCK__POST_APPLY_FOR: setPostApplyFor((Rule)null); return; case EmftvmPackage.CODE_BLOCK__BODY_FOR: setBodyFor((Operation)null); return; case EmftvmPackage.CODE_BLOCK__INITIALISER_FOR: setInitialiserFor((Field)null); return; case EmftvmPackage.CODE_BLOCK__NESTED: getNested().clear(); return; case EmftvmPackage.CODE_BLOCK__NESTED_FOR: setNestedFor((CodeBlock)null); return; case EmftvmPackage.CODE_BLOCK__PARENT_FRAME: setParentFrame(PARENT_FRAME_EDEFAULT); return; case EmftvmPackage.CODE_BLOCK__BINDING_FOR: setBindingFor((InputRuleElement)null); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc. --> * {@inheritDoc} * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case EmftvmPackage.CODE_BLOCK__MAX_LOCALS: return getMaxLocals() != MAX_LOCALS_EDEFAULT; case EmftvmPackage.CODE_BLOCK__MAX_STACK: return getMaxStack() != MAX_STACK_EDEFAULT; case EmftvmPackage.CODE_BLOCK__CODE: return code != null && !code.isEmpty(); case EmftvmPackage.CODE_BLOCK__LINE_NUMBERS: return lineNumbers != null && !lineNumbers.isEmpty(); case EmftvmPackage.CODE_BLOCK__LOCAL_VARIABLES: return localVariables != null && !localVariables.isEmpty(); case EmftvmPackage.CODE_BLOCK__MATCHER_FOR: return getMatcherFor() != null; case EmftvmPackage.CODE_BLOCK__APPLIER_FOR: return getApplierFor() != null; case EmftvmPackage.CODE_BLOCK__POST_APPLY_FOR: return getPostApplyFor() != null; case EmftvmPackage.CODE_BLOCK__BODY_FOR: return getBodyFor() != null; case EmftvmPackage.CODE_BLOCK__INITIALISER_FOR: return getInitialiserFor() != null; case EmftvmPackage.CODE_BLOCK__NESTED: return nested != null && !nested.isEmpty(); case EmftvmPackage.CODE_BLOCK__NESTED_FOR: return getNestedFor() != null; case EmftvmPackage.CODE_BLOCK__PARENT_FRAME: return PARENT_FRAME_EDEFAULT == null ? parentFrame != null : !PARENT_FRAME_EDEFAULT.equals(parentFrame); case EmftvmPackage.CODE_BLOCK__BINDING_FOR: return getBindingFor() != null; } return super.eIsSet(featureID); } /** * {@inheritDoc} */ @Override public void eNotify(Notification notification) { super.eNotify(notification); switch (notification.getFeatureID(null)) { case EmftvmPackage.CODE_BLOCK__CODE: codeChanged(); break; case EmftvmPackage.CODE_BLOCK__LOCAL_VARIABLES: localVariablesChanged(); break; case EmftvmPackage.CODE_BLOCK__NESTED: nestedChanged(); break; } } /** * {@inheritDoc} */ @Override public boolean eNotificationRequired() { return true; } /** * <!-- begin-user-doc. --> * {@inheritDoc} * <!-- end-user-doc --> * @generated NOT */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(); final EObject container = eContainer(); if (container != null) { result.append(container); if (container instanceof CodeBlock) { result.append('@'); result.append(((CodeBlock)container).getNested().indexOf(this)); } else if (container instanceof Field) { // nothing } else if (container instanceof Operation) { // nothing } else if (container instanceof InputRuleElement) { result.append('@'); result.append(((InputRuleElement)container).getInputFor()); } else if (container instanceof Rule) { final Rule r = (Rule)container; if (r.getMatcher() == this) { result.append("@matcher"); } else if (r.getApplier() == this) { result.append("@applier"); } else if (r.getPostApply() == this) { result.append("@postApply"); } else { result.append("@unknown"); } } else { result.append("@unknown"); } } else { result.append("@uncontained"); } return result.toString(); } /** * {@inheritDoc} */ public JITCodeBlock getJITCodeBlock() { return jitCodeBlock; } /** * {@inheritDoc} */ public void setJITCodeBlock(final JITCodeBlock jcb) { this.jitCodeBlock = jcb; } /** * Returns the {@link Module} (for debugger). * @return the {@link Module} * @see CodeBlockImpl#getModule() */ public Module getASM() { return getModule(); } /** * {@inheritDoc} */ public Rule getRule() { if (!ruleSet) { CodeBlock cb = this; while (cb != null) { if (cb.eContainer() instanceof Rule) { rule = (Rule)cb.eContainer(); break; } else { cb = cb.getNestedFor(); } } ruleSet = true; } return rule; } /** * @param env * @param type * @param name * @return The {@link Field} with the given <code>type</code> and <code>name</code>, if any, otherwise <code>null</code> */ private Field findField(final ExecEnv env, Object type, String name) { final Rule rule = getRule(); final Field field; if (rule != null) { field = rule.findField(type, name); } else { field = null; } if (field == null) { return env.findField(type, name); } else { return field; } } /** * @param env * @param type * @param name * @return The static {@link Field} with the given <code>type</code> and <code>name</code>, if any, otherwise <code>null</code> */ private Field findStaticField(final ExecEnv env, Object type, String name) { final Rule rule = getRule(); final Field field; if (rule != null) { field = rule.findStaticField(type, name); } else { field = null; } if (field == null) { return env.findStaticField(type, name); } else { return field; } } /** * Implements the SET instruction. * @param v value * @param o object * @param propname the property name * @param env the execution environment * @throws NoSuchFieldException * @throws IllegalAccessException * @throws IllegalArgumentException */ private void set(final Object v, final Object o, final String propname, final ExecEnv env) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException { if (o instanceof EObject) { final EObject eo = (EObject)o; final EClass type = eo.eClass(); final Field field = findField(env, type, propname); if (field != null) { field.setValue(o, v); return; } final EStructuralFeature sf = type.getEStructuralFeature(propname); if (sf != null) { EMFTVMUtil.set(env, eo, sf, v); return; } final Resource resource = eo.eResource(); if (EMFTVMUtil.XMI_ID_FEATURE.equals(propname) && resource instanceof XMIResource) { //$NON-NLS-1$ ((XMIResource)resource).setID(eo, v.toString()); return; } throw new NoSuchFieldException(String.format("Field %s::%s not found", EMFTVMUtil.toPrettyString(type, env), propname)); } // o is a regular Java object final Class<?> type = o == null ? Void.TYPE : o.getClass(); final Field field = findField(env, type, propname); if (field != null) { field.setValue(o, v); return; } try { final java.lang.reflect.Field f = type.getField(propname); f.set(o, v); } catch (NoSuchFieldException e) { throw new NoSuchFieldException(String.format("Field %s::%s not found", EMFTVMUtil.toPrettyString(type, env), propname)); } } /** * Adds <code>v</code> to <code>o.propname</code>. * Implements the ADD and INSERT instructions. * @param index the insertion index (-1 for end) * @param v value * @param o object * @param propname the property name * @param env the execution environment * @throws NoSuchFieldException * @throws IllegalAccessException * @throws IllegalArgumentException */ private void add(final int index, final Object v, final Object o, final String propname, final ExecEnv env) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException { //TODO enable add on fields if (o instanceof EObject) { final EObject eo = (EObject)o; final EClass type = eo.eClass(); final EStructuralFeature sf = type.getEStructuralFeature(propname); if (sf != null) { EMFTVMUtil.add(env, eo, sf, v, index); return; } final Resource resource = eo.eResource(); if (EMFTVMUtil.XMI_ID_FEATURE.equals(propname) && resource instanceof XMIResource) { //$NON-NLS-1$ if (((XMIResource)resource).getID(eo) != null) { throw new IllegalArgumentException(String.format( "Cannot add %s to field %s::%s: maximum multiplicity of 1 reached", v, EMFTVMUtil.toPrettyString(eo, env), propname)); } if (index > 0) { throw new IndexOutOfBoundsException(String.valueOf(index)); } ((XMIResource)resource).setID(eo, v.toString()); return; } throw new NoSuchFieldException(String.format("Field %s::%s not found", EMFTVMUtil.toPrettyString(type, env), propname)); } } /** * Implements the REMOVE instruction. * @param v value * @param o object * @param propname the property name * @param env the execution environment * @throws NoSuchFieldException * @throws IllegalAccessException * @throws IllegalArgumentException */ private void remove(final Object v, final Object o, final String propname, final ExecEnv env) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException { //TODO enable remove on fields if (o instanceof EObject) { final EObject eo = (EObject)o; final EClass type = eo.eClass(); final EStructuralFeature sf = type.getEStructuralFeature(propname); if (sf != null) { EMFTVMUtil.remove(env, eo, sf, v); return; } final Resource resource = eo.eResource(); if (EMFTVMUtil.XMI_ID_FEATURE.equals(propname) && resource instanceof XMIResource) { //$NON-NLS-1$ final XMIResource xmiRes = (XMIResource)resource; final Object xmiID = xmiRes.getID(eo); if (xmiID == null ? v == null : xmiID.equals(v)) { xmiRes.setID(eo, null); } return; } throw new NoSuchFieldException(String.format("Field %s::%s not found", EMFTVMUtil.toPrettyString(type, env), propname)); } } /** * Implements the GET instruction. * @param propname * @param env * @param frame * @return the property value * @throws NoSuchFieldException * @throws IllegalAccessException * @throws IllegalArgumentException */ @SuppressWarnings("unchecked") private Object get(final String propname, final StackFrame frame) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException { final ExecEnv env = frame.getEnv(); final Object o = frame.pop(); if (o instanceof EObject) { final EObject eo = (EObject)o; final EClass type = eo.eClass(); final Field field = findField(env, type, propname); if (field != null) { return field.getValue(o, frame); } final EStructuralFeature sf = type.getEStructuralFeature(propname); if (sf != null) { return EMFTVMUtil.get(env, eo, sf); } final Resource resource = eo.eResource(); if (EMFTVMUtil.XMI_ID_FEATURE.equals(propname) && resource instanceof XMIResource) { //$NON-NLS-1$ return ((XMIResource)resource).getID(eo); } throw new NoSuchFieldException(String.format("Field %s::%s not found", EMFTVMUtil.toPrettyString(type, env), propname)); } // o is a regular Java object final Class<?> type = o == null ? Void.TYPE : o.getClass(); final Field field = findField(env, type, propname); if (field != null) { return field.getValue(o, frame); } try { final java.lang.reflect.Field f = type.getField(propname); final Object result = f.get(o); if (result instanceof List<?>) { return new LazyListOnList<Object>((List<Object>)result); } else if (result instanceof java.util.Set<?>) { return new LazySetOnSet<Object>((java.util.Set<Object>)result); } else if (result instanceof Collection<?>) { return new LazyBagOnCollection<Object>((Collection<Object>)result); } else { return result; } } catch (NoSuchFieldException e) { throw new NoSuchFieldException(String.format("Field %s::%s not found", EMFTVMUtil.toPrettyString(type, env), propname)); } } /** * Implements the GET_TRANS instruction. * @param propname * @param env * @param frame * @throws NoSuchFieldException * @throws IllegalAccessException * @throws IllegalArgumentException */ private Collection<Object> getTrans(final String propname, final StackFrame frame) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException { final ExecEnv env = frame.getEnv(); final Object o = frame.pop(); if (o instanceof EObject) { final EObject eo = (EObject)o; final EClass type = eo.eClass(); final Field field = findField(env, type, propname); if (field != null) { return EMFTVMUtil.getTrans(o, field, frame, new LazyList<Object>()); } else { final EStructuralFeature sf = type.getEStructuralFeature(propname); if (sf == null) { throw new NoSuchFieldException(String.format("Field %s::%s not found", EMFTVMUtil.toPrettyString(type, env), propname)); } return EMFTVMUtil.getTrans(eo, sf, env, new LazyList<Object>()); } } else { final Class<?> type = o.getClass(); final Field field = findField(env, type, propname); if (field != null) { return EMFTVMUtil.getTrans(o, field, frame, new LazyList<Object>()); } else { final java.lang.reflect.Field f = type.getField(propname); return EMFTVMUtil.getTrans(o, f, new LazyList<Object>()); } } } /** * Implements the GET_SUPER instruction. * @param fieldCtx the current {@link Field} context * @param propname * @param env * @param frame * @return the property value * @throws NoSuchFieldException * @throws IllegalAccessException * @throws IllegalArgumentException */ @SuppressWarnings("unchecked") private Object getSuper(final Field fieldCtx, final String propname, final StackFrame frame) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException { if (fieldCtx == null) { throw new IllegalArgumentException("GET_SUPER can only be used in fields"); } final EClassifier context = fieldCtx.getEContext(); if (context == null) { throw new IllegalArgumentException(String.format("Field misses context type: %s", fieldCtx)); } final ExecEnv env = frame.getEnv(); Object o = frame.pop(); final List<?> superTypes; if (context instanceof EClass) { superTypes = ((EClass)context).getESuperTypes(); } else { final Class<?> ic = context.getInstanceClass(); if (ic == null) { throw new IllegalArgumentException(String.format("Primitive EMF type without instance class %s", context)); } superTypes = Collections.singletonList(ic.getSuperclass()); } final java.util.Set<Object> superFs = new LinkedHashSet<Object>(); if (o instanceof EObject) { // o may have EStructuralFeatures for (Object superType : superTypes) { Object superF = env.findField(superType, propname); if (superF != null) { superFs.add(superF); } else if (superType instanceof EClass) { superF = ((EClass)superType).getEStructuralFeature(propname); if (superF != null) { superFs.add(superF); } else if (((EClass)superType).getInstanceClass() != null) { try { superF = ((EClass)superType).getInstanceClass().getField(propname); assert superF != null; superFs.add(superF); } catch (NoSuchFieldException e) { // not found - skip } } } else if (superType instanceof Class<?>) { try { superF = ((Class<?>)superType).getField(propname); assert superF != null; superFs.add(superF); } catch (NoSuchFieldException e) { // not found - skip } } } } else { // o is a regular Java object - may be null for (Object superType : superTypes) { Object superF = env.findField(superType, propname); if (superF != null) { superFs.add(superF); } else if (superType instanceof EClass && ((EClass)superType).getInstanceClass() != null) { try { superF = ((EClass)superType).getInstanceClass().getField(propname); assert superF != null; superFs.add(superF); } catch (NoSuchFieldException e) { // not found - skip } } else if (superType instanceof Class<?>) { try { superF = ((Class<?>)superType).getField(propname); assert superF != null; superFs.add(superF); } catch (NoSuchFieldException e) { // not found - skip } } } } if (superFs.size() > 1) { throw new DuplicateEntryException(String.format( "More than one super-field found for context %s: %s", context, superFs)); } if (!superFs.isEmpty()) { final Object superF = superFs.iterator().next(); if (superF instanceof Field) { return ((Field)superF).getValue(o, frame); } else if (superF instanceof EStructuralFeature) { return EMFTVMUtil.get(env, (EObject)o, (EStructuralFeature)superF); } else { final Object result = ((java.lang.reflect.Field)superF).get(o); if (result instanceof List<?>) { return new LazyListOnList<Object>((List<Object>)result); } else if (result instanceof java.util.Set<?>) { return new LazySetOnSet<Object>((java.util.Set<Object>)result); } else if (result instanceof Collection<?>) { return new LazyBagOnCollection<Object>((Collection<Object>)result); } else { return result; } } } throw new NoSuchFieldException(String.format("Super-field of %s::%s not found", EMFTVMUtil.toPrettyString(context, env), propname)); } /** * Implements the SET_STATIC instruction. * @param v value * @param o object * @param propname the property name * @param env the execution environment * @throws NoSuchFieldException * @throws IllegalAccessException * @throws IllegalArgumentException */ private void setStatic(final Object v, final Object o, final String propname, final ExecEnv env) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException { final Object ort = EMFTVMUtil.getRegistryType(o); if (ort instanceof EClass) { final EClass type = (EClass)ort; final Field field = findStaticField(env, type, propname); if (field != null) { field.setStaticValue(v); } else { throw new NoSuchFieldException(String.format("Field %s::%s not found", EMFTVMUtil.toPrettyString(type, env), propname)); } } else if (ort instanceof Class<?>) { final Class<?> type = (Class<?>)ort; final Field field = findStaticField(env, type, propname); if (field != null) { field.setValue(ort, v); } else { final java.lang.reflect.Field f = type.getField(propname); if (Modifier.isStatic(f.getModifiers())) { f.set(null, v); } else { throw new NoSuchFieldException(String.format("Field %s::%s not found", EMFTVMUtil.toPrettyString(type, env), propname)); } } } else { throw new IllegalArgumentException(String.format("%s is not a type", EMFTVMUtil.toPrettyString(ort, env))); } } /** * Implements the GET_STATIC instruction. * @param propname * @param frame * @return the property value * @throws NoSuchFieldException * @throws IllegalAccessException * @throws IllegalArgumentException */ private Object getStatic(final String propname, final StackFrame frame) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException { final ExecEnv env = frame.getEnv(); final Object o = EMFTVMUtil.getRegistryType(frame.pop()); if (o instanceof EClass) { final EClass type = (EClass)o; final Field field = findStaticField(env, type, propname); if (field != null) { return field.getStaticValue(frame); } else { throw new NoSuchFieldException(String.format("Field %s::%s not found", EMFTVMUtil.toPrettyString(type, env), propname)); } } else if (o instanceof Class<?>) { final Class<?> type = (Class<?>)o; final Field field = findStaticField(env, type, propname); if (field != null) { return field.getStaticValue(frame); } else { final java.lang.reflect.Field f = type.getField(propname); if (Modifier.isStatic(f.getModifiers())) { return f.get(null); } else { throw new NoSuchFieldException(String.format("Field %s::%s not found", EMFTVMUtil.toPrettyString(type, env), propname)); } } } else { throw new IllegalArgumentException(String.format("%s is not a type", o)); } } /** * Implements the NEW and NEW_S instructions. * @param modelname * @param type * @param fram * @return the new object */ private static Object newInstr(final String modelname, final Object type, final StackFrame frame) { final ExecEnv env = frame.getEnv(); if (type instanceof EClass) { final EClass eType = (EClass)type; Model model = env.getOutputModels().get(modelname); if (model == null) { model = env.getInoutModels().get(modelname); } if (model == null) { throw new IllegalArgumentException(String.format("Inout/output model %s not found", modelname)); } return model.newElement(eType); } else { try { return NativeTypes.newInstance((Class<?>)type); } catch (Exception e) { throw new IllegalArgumentException(e); } } } /** * Implements the DELETE instruction. * @param frame */ private static void delete(final StackFrame frame) { final ExecEnv env = frame.getEnv(); final EObject element = (EObject)frame.pop(); final Resource res = element.eResource(); if (res == null) { throw new IllegalArgumentException(String.format( "Element %s is cannot be deleted; not contained in a model", EMFTVMUtil.toPrettyString(element, env))); } final Model model = env.getInputModelOf(element); if (model != null) { throw new IllegalArgumentException(String.format( "Element %s is cannot be deleted; contained in input model %s", EMFTVMUtil.toPrettyString(element, env), env.getModelID(model))); } env.queueForDelete(element, frame); } /** * Implements the INVOKE instruction. * @param instr the INVOKE instruction * @param frame the current stack frame * @return the invocation result * @throws InvocationTargetException * @throws IllegalAccessException * @throws IllegalArgumentException */ private static Object invoke(final Invoke instr, final StackFrame frame) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { final String opname = instr.getOpname(); final int argcount = instr.getArgcount(); final Object o; final Operation op; switch (argcount) { case 0: // Use Java's left-to-right evaluation semantics: // stack = [..., self, arg1, arg2] o = frame.pop(); op = frame.getEnv().findOperation( EMFTVMUtil.getArgumentType(o), opname); if (op != null) { final CodeBlock body = op.getBody(); final StackFrame rFrame = body.execute(frame.getSubFrame(body, o)); return rFrame.stackEmpty() ? null : rFrame.pop(); } final Method method = EMFTVMUtil.findNativeMethod(o == null? Void.TYPE : o.getClass(), opname, false); if (method != null) { instr.setNativeMethod(method); // record invoked method for JIT compiler return EMFTVMUtil.invokeNative(frame, o, opname); } throw new UnsupportedOperationException(String.format("%s::%s()", EMFTVMUtil.getTypeName(frame.getEnv(), EMFTVMUtil.getArgumentType(o)), opname)); case 1: // Use Java's left-to-right evaluation semantics: // stack = [..., self, arg1, arg2] final Object arg = frame.pop(); o = frame.pop(); op = frame.getEnv().findOperation( EMFTVMUtil.getArgumentType(o), opname, EMFTVMUtil.getArgumentType(arg)); if (op != null) { final CodeBlock body = op.getBody(); final StackFrame rFrame = body.execute(frame.getSubFrame(body, o, arg)); return rFrame.stackEmpty() ? null : rFrame.pop(); } final Method method1 = EMFTVMUtil.findNativeMethod( o == null? Void.TYPE : o.getClass(), opname, arg == null ? Void.TYPE : arg.getClass(), false); if (method1 != null) { instr.setNativeMethod(method1); // record invoked method for JIT compiler return EMFTVMUtil.invokeNative(frame, o, method1, arg); } throw new UnsupportedOperationException(String.format("%s::%s(%s)", EMFTVMUtil.getTypeName(frame.getEnv(), EMFTVMUtil.getArgumentType(o)), opname, EMFTVMUtil.getTypeName(frame.getEnv(), EMFTVMUtil.getArgumentType(arg)))); default: // Use Java's left-to-right evaluation semantics: // stack = [..., self, arg1, arg2] final Object[] args = frame.pop(argcount); //TODO treat context as a regular argument (cf. Java's Method.invoke()) o = frame.pop(); op = frame.getEnv().findOperation( EMFTVMUtil.getArgumentType(o), opname, EMFTVMUtil.getArgumentTypes(args)); if (op != null) { final CodeBlock body = op.getBody(); final StackFrame rFrame = body.execute(frame.getSubFrame(body, o, args)); return rFrame.stackEmpty() ? null : rFrame.pop(); } final Method methodn = EMFTVMUtil.findNativeMethod( o == null? Void.TYPE : o.getClass(), opname, EMFTVMUtil.getArgumentClasses(args), false); if (methodn != null) { instr.setNativeMethod(methodn); // record invoked method for JIT compiler return EMFTVMUtil.invokeNative(frame, o, methodn, args); } throw new UnsupportedOperationException(String.format("%s::%s(%s)", EMFTVMUtil.getTypeName(frame.getEnv(), EMFTVMUtil.getArgumentType(o)), opname, EMFTVMUtil.getTypeName(frame.getEnv(), EMFTVMUtil.getArgumentTypes(args)))); } } /** * Implements the INVOKE_STATIC instruction. * @param opname * @param argcount * @param frame * @return the invocation result * @throws InvocationTargetException * @throws IllegalAccessException * @throws IllegalArgumentException */ private static Object invokeStatic(final String opname, final int argcount, final StackFrame frame) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { final ExecEnv env = frame.getEnv(); final Object type; final Operation op; switch (argcount) { case 0: // Use Java's left-to-right evaluation semantics: // stack = [..., type, arg1, arg2] type = frame.pop(); if (type == null) { throw new IllegalArgumentException(String.format("Cannot invoke static operation %s on null type", opname)); } if (type == env.eClass()) { // Lazy and called rule invocations are indistinguishable from static operations in ATL final Rule rule = env.findRule(opname); if (rule != null && rule.getMode() == RuleMode.MANUAL) { return matchOne(frame, rule); } } op = env.findStaticOperation( type, opname); if (op != null) { final CodeBlock body = op.getBody(); final StackFrame rFrame = body.execute(new StackFrame(frame, body)); // no need to copy arguments return rFrame.stackEmpty() ? null : rFrame.pop(); } if (type instanceof Class<?>) { return EMFTVMUtil.invokeNativeStatic(frame, (Class<?>)type, opname); } throw new UnsupportedOperationException(String.format("static %s::%s()", EMFTVMUtil.getTypeName(env, type), opname)); case 1: // Use Java's left-to-right evaluation semantics: // stack = [..., type, arg1, arg2] final Object arg = frame.pop(); type = frame.pop(); if (type == null) { throw new IllegalArgumentException(String.format("Cannot invoke static operation %s on null type", opname)); } if (type == env.eClass()) { // Lazy and called rule invocations are indistinguishable from static operations in ATL final Rule rule = env.findRule(opname); if (rule != null && rule.getMode() == RuleMode.MANUAL) { return matchOne(frame, rule, new EObject[]{(EObject)arg}); } } op = env.findStaticOperation( type, opname, EMFTVMUtil.getArgumentType(arg)); if (op != null) { final CodeBlock body = op.getBody(); final StackFrame rFrame = body.execute(frame.getSubFrame(body, arg)); return rFrame.stackEmpty() ? null : rFrame.pop(); } if (type instanceof Class<?>) { return EMFTVMUtil.invokeNativeStatic(frame, (Class<?>)type, opname, arg); } throw new UnsupportedOperationException(String.format("static %s::%s(%s)", EMFTVMUtil.getTypeName(env, type), opname, EMFTVMUtil.getTypeName(env, EMFTVMUtil.getArgumentType(arg)))); default: // Use Java's left-to-right evaluation semantics: // stack = [..., type, arg1, arg2] final Object[] args = frame.pop(argcount); type = frame.pop(); if (type == null) { throw new IllegalArgumentException(String.format("Cannot invoke static operation %s on null type", opname)); } if (type == env.eClass()) { // Lazy and called rule invocations are indistinguishable from static operations in ATL final Rule rule = env.findRule(opname); if (rule != null && rule.getMode() == RuleMode.MANUAL) { EObject[] eargs = new EObject[argcount]; System.arraycopy(args, 0, eargs, 0, argcount); return matchOne(frame, rule, eargs); } } //TODO treat context type as a regular argument (cf. Java's Method.invoke()) op = env.findStaticOperation( type, opname, EMFTVMUtil.getArgumentTypes(args)); if (op != null) { final CodeBlock body = op.getBody(); final StackFrame rFrame = body.execute(frame.getSubFrame(body, args)); return rFrame.stackEmpty() ? null : rFrame.pop(); } if (type instanceof Class<?>) { return EMFTVMUtil.invokeNativeStatic(frame, (Class<?>)type, opname, args); } throw new UnsupportedOperationException(String.format("static %s::%s(%s)", EMFTVMUtil.getTypeName(env, type), opname, EMFTVMUtil.getTypeNames(env, EMFTVMUtil.getArgumentTypes(args)))); } } /** * Implements the INVOKE_SUPER instruction. * @param eContext the current execution context type * @param opname * @param argcount * @param frame * @return the invocation result * @throws InvocationTargetException * @throws IllegalAccessException * @throws IllegalArgumentException */ private static Object invokeSuper(final Operation op, final String opname, final int argcount, final StackFrame frame) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { if (op == null) { throw new IllegalArgumentException("INVOKE_SUPER can only be used in operations"); } final EClassifier context = op.getEContext(); if (context == null) { throw new IllegalArgumentException(String.format("Operation misses context type: %s", op)); } final java.util.Set<Operation> ops = new LinkedHashSet<Operation>(); final List<?> superTypes; if (context instanceof EClass) { superTypes = ((EClass)context).getESuperTypes(); } else { final Class<?> ic = context.getInstanceClass(); if (ic == null) { throw new IllegalArgumentException(String.format("Primitive EMF type without instance class %s", context)); } superTypes = Collections.singletonList(ic.getSuperclass()); } final ExecEnv env = frame.getEnv(); Operation superOp = null; final Object o; final Class<?> ic; switch (argcount) { case 0: // Use Java's left-to-right evaluation semantics: // stack = [..., self, arg1, arg2] o = frame.pop(); for (Object superType : superTypes) { superOp = env.findOperation(superType, opname); if (superOp != null) { ops.add(superOp); } } if (ops.size() > 1) { throw new DuplicateEntryException(String.format( "More than one super-operation found for context %s: %s", context, ops)); } if (!ops.isEmpty()) { superOp = ops.iterator().next(); } if (superOp != null) { final CodeBlock body = superOp.getBody(); final StackFrame rFrame = body.execute(frame.getSubFrame(body, o)); return rFrame.stackEmpty() ? null : rFrame.pop(); } ic = context.getInstanceClass(); if (ic != null) { return EMFTVMUtil.invokeNativeSuper(frame, ic, o, opname); } throw new UnsupportedOperationException(String.format("super %s::%s()", EMFTVMUtil.getTypeName(env, context), opname)); case 1: // Use Java's left-to-right evaluation semantics: // stack = [..., self, arg1, arg2] final Object arg = frame.pop(); o = frame.pop(); for (Object superType : superTypes) { superOp = env.findOperation(superType, opname, EMFTVMUtil.getArgumentType(arg)); if (superOp != null) { ops.add(superOp); } } if (ops.size() > 1) { throw new DuplicateEntryException(String.format( "More than one super-operation found for context %s: %s", context, ops)); } if (!ops.isEmpty()) { superOp = ops.iterator().next(); } if (superOp != null) { final CodeBlock body = superOp.getBody(); final StackFrame rFrame = body.execute(frame.getSubFrame(body, o, arg)); return rFrame.stackEmpty() ? null : rFrame.pop(); } ic = context.getInstanceClass(); if (ic != null) { return EMFTVMUtil.invokeNativeSuper(frame, ic, o, opname, arg); } throw new UnsupportedOperationException(String.format("super %s::%s(%s)", EMFTVMUtil.getTypeName(env, context), opname, EMFTVMUtil.getTypeName(env, EMFTVMUtil.getArgumentType(arg)))); default: // Use Java's left-to-right evaluation semantics: // stack = [..., self, arg1, arg2] final Object[] args = frame.pop(argcount); o = frame.pop(); for (Object superType : superTypes) { superOp = env.findOperation(superType, opname, EMFTVMUtil.getArgumentTypes(args)); if (superOp != null) { ops.add(superOp); } } if (ops.size() > 1) { throw new DuplicateEntryException(String.format( "More than one super-operation found for context %s: %s", context, ops)); } if (!ops.isEmpty()) { superOp = ops.iterator().next(); } if (superOp != null) { final CodeBlock body = superOp.getBody(); final StackFrame rFrame = body.execute(frame.getSubFrame(body, o, args)); return rFrame.stackEmpty() ? null : rFrame.pop(); } ic = context.getInstanceClass(); if (ic != null) { return EMFTVMUtil.invokeNativeSuper(frame, ic, o, opname, args); } throw new UnsupportedOperationException(String.format("super %s::%s(%s)", EMFTVMUtil.getTypeName(env, context), opname, EMFTVMUtil.getTypeNames(env, EMFTVMUtil.getArgumentTypes(args)))); } } /** * Finds the rule referred to by <pre>instr</pre>. * @param env * @param rulename * @return the rule mentioned by instr * @throws IllegalArgumentException if rule not found */ private static Rule findRule(final ExecEnv env, final String rulename) { final Rule rule = env.findRule(rulename); if (rule == null) { throw new IllegalArgumentException(String.format("Rule %s not found", rulename)); } return rule; } /** * Executes <code>rule</code> with <code>args</code>. * @param frame the current stack frame * @param rule the rule * @param args the rule arguments */ private static Object matchOne(final StackFrame frame, final Rule rule, final EObject[] args) { final int argcount = args.length; if (argcount != rule.getInputElements().size()) { throw new VMException(frame, String.format( "Rule %s has different amount of input elements than expected: %d instead of %d", rule.getName(), rule.getInputElements().size(), argcount)); } return rule.matchManual(frame, args); } /** * Executes <code>rule</code> without arguments. * @param frame the current stack frame * @param rule the rule */ private static Object matchOne(final StackFrame frame, final Rule rule) { if (rule.getInputElements().size() != 0) { throw new VMException(frame, String.format( "Rule %s has different amount of input elements than expected: %d instead of %d", rule.getName(), rule.getInputElements().size(), 0)); } return rule.matchManual(frame, EEMPTY); } /** * Clears values derived from {@link #getCode()}. */ private void codeChanged() { predecessors.clear(); allPredecessors.clear(); nlPredecessors.clear(); eUnset(EmftvmPackage.CODE_BLOCK__MAX_STACK); setJITCodeBlock(null); } /** * Clears values derived from {@link #getLocalVariables()}. */ private void localVariablesChanged() { eUnset(EmftvmPackage.CODE_BLOCK__MAX_LOCALS); setJITCodeBlock(null); } /** * Clears values derived from {@link #getNested()}. */ private void nestedChanged() { setJITCodeBlock(null); } } //CodeBlockImpl
false
true
public StackFrame execute(final StackFrame frame) { final JITCodeBlock jcb = getJITCodeBlock(); if (jcb != null) { return jcb.execute(frame); } runcount += 1; // increase invocation counter to trigger JIT int pc = 0; final EList<Instruction> code = getCode(); final int codeSize = code.size(); final ExecEnv env = frame.getEnv(); final VMMonitor monitor = env.getMonitor(); CodeBlock cb; StackFrame rFrame; int argcount; if (monitor != null) { monitor.enter(frame); } try { LOOP: while (pc < codeSize) { Instruction instr = code.get(pc++); if (monitor != null) { if (monitor.isTerminated()) { throw new VMException(frame, "Execution terminated."); } else { frame.setPc(pc); monitor.step(frame); } } switch (instr.getOpcode()) { case PUSH: frame.push(((Push)instr).getValue()); break; case PUSHT: frame.push(true); break; case PUSHF: frame.push(false); break; case POP: frame.popv(); break; case LOAD: frame.load(((Load)instr).getCbOffset(), ((Load)instr).getSlot()); break; case STORE: frame.store(((Store)instr).getCbOffset(), ((Store)instr).getSlot()); break; case SET: set(frame.pop(), frame.pop(), ((Set)instr).getFieldname(), env); break; case GET: frame.setPc(pc); frame.push(get(((Get)instr).getFieldname(), frame)); break; case GET_TRANS: frame.setPc(pc); frame.push(getTrans(((GetTrans)instr).getFieldname(), frame)); break; case SET_STATIC: setStatic(frame.pop(), frame.pop(), ((SetStatic)instr).getFieldname(), env); break; case GET_STATIC: frame.setPc(pc); frame.push(getStatic(((GetStatic)instr).getFieldname(), frame)); break; case FINDTYPE: frame.push(frame.getEnv().findType( ((Findtype)instr).getModelname(), ((Findtype)instr).getTypename())); break; case FINDTYPE_S: frame.push(frame.getEnv().findType( (String)frame.pop(), (String)frame.pop())); break; case NEW: frame.push(newInstr(((New)instr).getModelname(), frame.pop(), frame)); break; case NEW_S: frame.push(newInstr((String)frame.pop(), frame.pop(), frame)); break; case DELETE: delete(frame); break; case DUP: frame.dup(); break; case DUP_X1: frame.dupX1(); break; case SWAP: frame.swap(); break; case SWAP_X1: frame.swapX1(); break; case IF: if ((Boolean)frame.pop()) { pc = ((If)instr).getOffset(); } break; case IFN: if (!(Boolean)frame.pop()) { pc = ((Ifn)instr).getOffset(); } break; case GOTO: pc = ((Goto)instr).getOffset(); break; case ITERATE: Iterator<?> i = ((Collection<?>)frame.pop()).iterator(); if (i.hasNext()) { frame.push(i); frame.push(i.next()); } else { pc = ((Iterate)instr).getOffset(); // jump over ENDITERATE } break; case ENDITERATE: i = (Iterator<?>)frame.pop(); if (i.hasNext()) { frame.push(i); frame.push(i.next()); pc = ((Enditerate)instr).getOffset(); // jump to first loop instruction } break; case INVOKE: frame.setPc(pc); frame.push(invoke((Invoke)instr, frame)); break; case INVOKE_STATIC: frame.setPc(pc); frame.push(invokeStatic(((InvokeStatic)instr).getOpname(), ((InvokeStatic)instr).getArgcount(), frame)); break; case INVOKE_SUPER: frame.setPc(pc); frame.push(invokeSuper(getOperation(), ((InvokeSuper)instr).getOpname(), ((InvokeSuper)instr).getArgcount(), frame)); break; case ALLINST: frame.push(EMFTVMUtil.findAllInstances((EClass)frame.pop(), frame.getEnv())); break; case ALLINST_IN: frame.push(EMFTVMUtil.findAllInstIn(frame.pop(), (EClass)frame.pop(), frame.getEnv())); break; case ISNULL: frame.push(frame.pop() == null); break; case GETENVTYPE: frame.push(EXEC_ENV); break; case NOT: frame.push(!(Boolean)frame.pop()); break; case AND: cb = ((And)instr).getCodeBlock(); frame.setPc(pc); frame.push((Boolean)frame.pop() && (Boolean)cb.execute(frame.getSubFrame(cb, null)).pop()); break; case OR: cb = ((Or)instr).getCodeBlock(); frame.setPc(pc); frame.push((Boolean)frame.pop() || (Boolean)cb.execute(frame.getSubFrame(cb, null)).pop()); break; case XOR: frame.push((Boolean)frame.pop() ^ (Boolean)frame.pop()); break; case IMPLIES: cb = ((Implies)instr).getCodeBlock(); frame.setPc(pc); frame.push(!(Boolean)frame.pop() || (Boolean)cb.execute(frame.getSubFrame(cb, null)).pop()); break; case IFTE: frame.setPc(pc); if ((Boolean)frame.pop()) { cb = ((Ifte)instr).getThenCb(); } else { cb = ((Ifte)instr).getElseCb(); } frame.push(cb.execute(frame.getSubFrame(cb, null)).pop()); break; case RETURN: break LOOP; case GETCB: frame.push(((Getcb)instr).getCodeBlock()); break; case INVOKE_ALL_CBS: frame.setPc(pc); // Use Java's left-to-right evaluation semantics: // stack = [..., arg1, arg2] argcount = ((InvokeAllCbs)instr).getArgcount(); Object[] args = argcount > 0 ? frame.pop(argcount) : EMPTY; for (CodeBlock ncb : getNested()) { rFrame = ncb.execute(frame.getSubFrame(ncb, args)); if (!rFrame.stackEmpty()) { frame.push(rFrame.pop()); } } break; case INVOKE_CB: cb = ((InvokeCb)instr).getCodeBlock(); frame.setPc(pc); // Use Java's left-to-right evaluation semantics: // stack = [..., arg1, arg2] argcount = ((InvokeCb)instr).getArgcount(); rFrame = cb.execute(frame.getSubFrame(cb, argcount > 0 ? frame.pop(argcount) : EMPTY)); if (!rFrame.stackEmpty()) { frame.push(rFrame.pop()); } break; case INVOKE_CB_S: cb = (CodeBlock)frame.pop(); frame.setPc(pc); // Use Java's left-to-right evaluation semantics: // stack = [..., arg1, arg2] argcount = ((InvokeCbS)instr).getArgcount(); rFrame = cb.execute(frame.getSubFrame(cb, argcount > 0 ? frame.pop(argcount) : EMPTY)); if (!rFrame.stackEmpty()) { frame.push(rFrame.pop()); } else { frame.push(null); // unknown code block => always produce one stack element } break; case MATCH: frame.setPc(pc); // Use Java's left-to-right evaluation semantics: // stack = [..., arg1, arg2] argcount = ((Match)instr).getArgcount(); frame.push(argcount > 0 ? matchOne(frame, findRule(frame.getEnv(), ((Match)instr).getRulename()), frame.pop(argcount, new EObject[argcount])) : matchOne(frame, findRule(frame.getEnv(), ((Match)instr).getRulename()))); break; case MATCH_S: frame.setPc(pc); // stack = [..., arg1, arg2, rule] argcount = ((MatchS)instr).getArgcount(); frame.push(argcount > 0 ? matchOne(frame, (Rule)frame.pop(), frame.pop(argcount, new EObject[argcount])) : matchOne(frame, (Rule)frame.pop())); break; case ADD: add(-1, frame.pop(), frame.pop(), ((Add)instr).getFieldname(), env); break; case REMOVE: remove(frame.pop(), frame.pop(), ((Remove)instr).getFieldname(), env); break; case INSERT: add((Integer)frame.pop(), frame.pop(), frame.pop(), ((Insert)instr).getFieldname(), env); break; case GET_SUPER: frame.setPc(pc); frame.push(getSuper(getField(), ((GetSuper)instr).getFieldname(), frame)); break; case GETENV: frame.push(env); break; default: throw new VMException(frame, String.format("Unsupported opcode: %s", instr.getOpcode())); } // switch } // while } catch (VMException e) { throw e; } catch (Exception e) { frame.setPc(pc); throw new VMException(frame, e); } if (monitor != null) { monitor.leave(frame); } final CodeBlockJIT jc = env.getJITCompiler(); if (jc != null && runcount > JIT_THRESHOLD && getJITCodeBlock() == null) { // JIT everything that runs more than JIT_THRESHOLD try { setJITCodeBlock(jc.jit(this)); } catch (Exception e) { frame.setPc(pc); throw new VMException(frame, e); } } return frame; }
public StackFrame execute(final StackFrame frame) { final JITCodeBlock jcb = getJITCodeBlock(); if (jcb != null) { return jcb.execute(frame); } runcount += 1; // increase invocation counter to trigger JIT int pc = 0; final EList<Instruction> code = getCode(); final int codeSize = code.size(); final ExecEnv env = frame.getEnv(); final VMMonitor monitor = env.getMonitor(); CodeBlock cb; StackFrame rFrame; int argcount; if (monitor != null) { monitor.enter(frame); } try { LOOP: while (pc < codeSize) { Instruction instr = code.get(pc++); if (monitor != null) { if (monitor.isTerminated()) { throw new VMException(frame, "Execution terminated."); } else { frame.setPc(pc); monitor.step(frame); } } switch (instr.getOpcode()) { case PUSH: frame.push(((Push)instr).getValue()); break; case PUSHT: frame.push(true); break; case PUSHF: frame.push(false); break; case POP: frame.popv(); break; case LOAD: frame.load(((Load)instr).getCbOffset(), ((Load)instr).getSlot()); break; case STORE: frame.store(((Store)instr).getCbOffset(), ((Store)instr).getSlot()); break; case SET: set(frame.pop(), frame.pop(), ((Set)instr).getFieldname(), env); break; case GET: frame.setPc(pc); frame.push(get(((Get)instr).getFieldname(), frame)); break; case GET_TRANS: frame.setPc(pc); frame.push(getTrans(((GetTrans)instr).getFieldname(), frame)); break; case SET_STATIC: setStatic(frame.pop(), frame.pop(), ((SetStatic)instr).getFieldname(), env); break; case GET_STATIC: frame.setPc(pc); frame.push(getStatic(((GetStatic)instr).getFieldname(), frame)); break; case FINDTYPE: frame.push(frame.getEnv().findType( ((Findtype)instr).getModelname(), ((Findtype)instr).getTypename())); break; case FINDTYPE_S: frame.push(frame.getEnv().findType( (String)frame.pop(), (String)frame.pop())); break; case NEW: frame.push(newInstr(((New)instr).getModelname(), frame.pop(), frame)); break; case NEW_S: frame.push(newInstr((String)frame.pop(), frame.pop(), frame)); break; case DELETE: delete(frame); break; case DUP: frame.dup(); break; case DUP_X1: frame.dupX1(); break; case SWAP: frame.swap(); break; case SWAP_X1: frame.swapX1(); break; case IF: if ((Boolean)frame.pop()) { pc = ((If)instr).getOffset(); } break; case IFN: if (!(Boolean)frame.pop()) { pc = ((Ifn)instr).getOffset(); } break; case GOTO: pc = ((Goto)instr).getOffset(); break; case ITERATE: Iterator<?> i = ((Collection<?>)frame.pop()).iterator(); if (i.hasNext()) { frame.push(i); frame.push(i.next()); } else { pc = ((Iterate)instr).getOffset(); // jump over ENDITERATE } break; case ENDITERATE: i = (Iterator<?>)frame.pop(); if (i.hasNext()) { frame.push(i); frame.push(i.next()); pc = ((Enditerate)instr).getOffset(); // jump to first loop instruction } break; case INVOKE: frame.setPc(pc); frame.push(invoke((Invoke)instr, frame)); break; case INVOKE_STATIC: frame.setPc(pc); frame.push(invokeStatic(((InvokeStatic)instr).getOpname(), ((InvokeStatic)instr).getArgcount(), frame)); break; case INVOKE_SUPER: frame.setPc(pc); frame.push(invokeSuper(getOperation(), ((InvokeSuper)instr).getOpname(), ((InvokeSuper)instr).getArgcount(), frame)); break; case ALLINST: frame.push(EMFTVMUtil.findAllInstances((EClass)frame.pop(), frame.getEnv())); break; case ALLINST_IN: frame.push(EMFTVMUtil.findAllInstIn(frame.pop(), (EClass)frame.pop(), frame.getEnv())); break; case ISNULL: frame.push(frame.pop() == null); break; case GETENVTYPE: frame.push(EXEC_ENV); break; case NOT: frame.push(!(Boolean)frame.pop()); break; case AND: cb = ((And)instr).getCodeBlock(); frame.setPc(pc); frame.push((Boolean)frame.pop() && (Boolean)cb.execute(new StackFrame(frame, cb)).pop()); break; case OR: cb = ((Or)instr).getCodeBlock(); frame.setPc(pc); frame.push((Boolean)frame.pop() || (Boolean)cb.execute(new StackFrame(frame, cb)).pop()); break; case XOR: frame.push((Boolean)frame.pop() ^ (Boolean)frame.pop()); break; case IMPLIES: cb = ((Implies)instr).getCodeBlock(); frame.setPc(pc); frame.push(!(Boolean)frame.pop() || (Boolean)cb.execute(new StackFrame(frame, cb)).pop()); break; case IFTE: frame.setPc(pc); if ((Boolean)frame.pop()) { cb = ((Ifte)instr).getThenCb(); } else { cb = ((Ifte)instr).getElseCb(); } frame.push(cb.execute(new StackFrame(frame, cb)).pop()); break; case RETURN: break LOOP; case GETCB: frame.push(((Getcb)instr).getCodeBlock()); break; case INVOKE_ALL_CBS: frame.setPc(pc); // Use Java's left-to-right evaluation semantics: // stack = [..., arg1, arg2] argcount = ((InvokeAllCbs)instr).getArgcount(); Object[] args = argcount > 0 ? frame.pop(argcount) : EMPTY; for (CodeBlock ncb : getNested()) { rFrame = ncb.execute(frame.getSubFrame(ncb, args)); if (!rFrame.stackEmpty()) { frame.push(rFrame.pop()); } } break; case INVOKE_CB: cb = ((InvokeCb)instr).getCodeBlock(); frame.setPc(pc); // Use Java's left-to-right evaluation semantics: // stack = [..., arg1, arg2] argcount = ((InvokeCb)instr).getArgcount(); rFrame = cb.execute(frame.getSubFrame(cb, argcount > 0 ? frame.pop(argcount) : EMPTY)); if (!rFrame.stackEmpty()) { frame.push(rFrame.pop()); } break; case INVOKE_CB_S: cb = (CodeBlock)frame.pop(); frame.setPc(pc); // Use Java's left-to-right evaluation semantics: // stack = [..., arg1, arg2] argcount = ((InvokeCbS)instr).getArgcount(); rFrame = cb.execute(frame.getSubFrame(cb, argcount > 0 ? frame.pop(argcount) : EMPTY)); if (!rFrame.stackEmpty()) { frame.push(rFrame.pop()); } else { frame.push(null); // unknown code block => always produce one stack element } break; case MATCH: frame.setPc(pc); // Use Java's left-to-right evaluation semantics: // stack = [..., arg1, arg2] argcount = ((Match)instr).getArgcount(); frame.push(argcount > 0 ? matchOne(frame, findRule(frame.getEnv(), ((Match)instr).getRulename()), frame.pop(argcount, new EObject[argcount])) : matchOne(frame, findRule(frame.getEnv(), ((Match)instr).getRulename()))); break; case MATCH_S: frame.setPc(pc); // stack = [..., arg1, arg2, rule] argcount = ((MatchS)instr).getArgcount(); frame.push(argcount > 0 ? matchOne(frame, (Rule)frame.pop(), frame.pop(argcount, new EObject[argcount])) : matchOne(frame, (Rule)frame.pop())); break; case ADD: add(-1, frame.pop(), frame.pop(), ((Add)instr).getFieldname(), env); break; case REMOVE: remove(frame.pop(), frame.pop(), ((Remove)instr).getFieldname(), env); break; case INSERT: add((Integer)frame.pop(), frame.pop(), frame.pop(), ((Insert)instr).getFieldname(), env); break; case GET_SUPER: frame.setPc(pc); frame.push(getSuper(getField(), ((GetSuper)instr).getFieldname(), frame)); break; case GETENV: frame.push(env); break; default: throw new VMException(frame, String.format("Unsupported opcode: %s", instr.getOpcode())); } // switch } // while } catch (VMException e) { throw e; } catch (Exception e) { frame.setPc(pc); throw new VMException(frame, e); } if (monitor != null) { monitor.leave(frame); } final CodeBlockJIT jc = env.getJITCompiler(); if (jc != null && runcount > JIT_THRESHOLD && getJITCodeBlock() == null) { // JIT everything that runs more than JIT_THRESHOLD try { setJITCodeBlock(jc.jit(this)); } catch (Exception e) { frame.setPc(pc); throw new VMException(frame, e); } } return frame; }
diff --git a/hamcrest-unit-test/src/main/java/org/hamcrest/MatcherAssertTest.java b/hamcrest-unit-test/src/main/java/org/hamcrest/MatcherAssertTest.java index cf822ba..f31d568 100644 --- a/hamcrest-unit-test/src/main/java/org/hamcrest/MatcherAssertTest.java +++ b/hamcrest-unit-test/src/main/java/org/hamcrest/MatcherAssertTest.java @@ -1,83 +1,83 @@ package org.hamcrest; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import junit.framework.TestCase; public class MatcherAssertTest extends TestCase { public void testIncludesDescriptionOfTestedValueInErrorMessage() { String expected = "expected"; String actual = "actual"; String expectedMessage = "identifier\nExpected: \"expected\"\n but: was \"actual\""; try { assertThat("identifier", actual, equalTo(expected)); } catch (AssertionError e) { assertTrue(e.getMessage().startsWith(expectedMessage)); return; } fail("should have failed"); } public void testDescriptionCanBeElided() { String expected = "expected"; String actual = "actual"; String expectedMessage = "\nExpected: \"expected\"\n but: was \"actual\""; try { assertThat(actual, equalTo(expected)); } catch (AssertionError e) { assertTrue(e.getMessage().startsWith(expectedMessage)); return; } fail("should have failed"); } public void testCanTestBooleanDirectly() { assertThat("success reason message", true); try { assertThat("failing reason message", false); } catch (AssertionError e) { assertEquals("failing reason message", e.getMessage()); return; } fail("should have failed"); } public void testIncludesMismatchDescription() { Matcher<String> matcherWithCustomMismatchDescription = new BaseMatcher<String>() { public boolean matches(Object item) { return false; } public void describeTo(Description description) { description.appendText("Something cool"); } @Override public void describeMismatch(Object item, Description mismatchDescription) { mismatchDescription.appendText("Not cool"); } }; - String expectedMessage = "\nExpected: Something cool\n got: \"Value\"\nmismatch: Not cool"; + String expectedMessage = "\nExpected: Something cool\n but: Not cool"; try { assertThat("Value", matcherWithCustomMismatchDescription); fail("should have failed"); } catch (AssertionError e) { assertEquals(expectedMessage, e.getMessage()); } } }
true
true
public void testIncludesMismatchDescription() { Matcher<String> matcherWithCustomMismatchDescription = new BaseMatcher<String>() { public boolean matches(Object item) { return false; } public void describeTo(Description description) { description.appendText("Something cool"); } @Override public void describeMismatch(Object item, Description mismatchDescription) { mismatchDescription.appendText("Not cool"); } }; String expectedMessage = "\nExpected: Something cool\n got: \"Value\"\nmismatch: Not cool"; try { assertThat("Value", matcherWithCustomMismatchDescription); fail("should have failed"); } catch (AssertionError e) { assertEquals(expectedMessage, e.getMessage()); } }
public void testIncludesMismatchDescription() { Matcher<String> matcherWithCustomMismatchDescription = new BaseMatcher<String>() { public boolean matches(Object item) { return false; } public void describeTo(Description description) { description.appendText("Something cool"); } @Override public void describeMismatch(Object item, Description mismatchDescription) { mismatchDescription.appendText("Not cool"); } }; String expectedMessage = "\nExpected: Something cool\n but: Not cool"; try { assertThat("Value", matcherWithCustomMismatchDescription); fail("should have failed"); } catch (AssertionError e) { assertEquals(expectedMessage, e.getMessage()); } }
diff --git a/src/core/Scene.java b/src/core/Scene.java index 56fcc9b..bafe0fb 100755 --- a/src/core/Scene.java +++ b/src/core/Scene.java @@ -1,359 +1,359 @@ package core; import global.GlobalSettings; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.io.PrintStream; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Random; import javax.swing.JPanel; import actors.Block; import actors.Player; import background.Background; import background.BackgroundActor; /** * Scene class. Base class for Scenes to hold and display actors. */ public class Scene extends JPanel { public GlobalSettings gs; private double ytiles = 1.1; public HashSet<Actor> childs; private Background bg; private Actor player; // current scroll position private double xposition = 0; private LevelLoader lloader = null; // initial scroll speed //0.012 public double xscrollspeed = 0.010; // scroll increment each round // 0.0025 private double xscrollinc = 0.0000; // steps to perform scrolling in (for collision) private double xscrollsteps = 0.005; // value that holds current scroll speed (for stepwise movement) private double xscrolltmp = 0; // with of the scene public double xsize = 2.3; // position of the ground (0 to 1) private double ground = 0.8; private long score = 0; private int round = 1; private boolean paused = false; private boolean isSpacePressed = false; public Scene(GlobalSettings gs) { System.err.println("DEBUG : SCENE "); this.gs = gs; childs = new HashSet<Actor>(); this.setFocusable(true); this.addKeyListener(new KeyListener() { @Override public void keyTyped(KeyEvent e) { } @Override public void keyPressed(KeyEvent e) { //TODO: DELETE DEBUG KEY if(e.getKeyCode() == KeyEvent.VK_P){ paused = true; System.out.println(((Player)player).getTouchedObstacle()!=null); } else{ isSpacePressed = true; if(paused) { //paused = false; } else { ((Player)player).jump(); } } } @Override public void keyReleased(KeyEvent e) { isSpacePressed = false; } }); player = new Player(this); //################################### //Hier wird das Level aus der Datei geladen oder generiert //################################## //Level one = new Level(this,"res/level01.dat"); //What NEXT: Sollte hier ein Levelloader implementiert werden der das nächste Level einleitet ? lloader = new LevelLoader(this, "res/levels/"); lloader.start(); bg = new Background(this); bg.addBackgroundActor(new BackgroundActor(this,1.0,1), 1); bg.addBackgroundActor(new BackgroundActor(this,1.7,1), 1); bg.addBackgroundActor(new BackgroundActor(this,1.1,1), 2); bg.addBackgroundActor(new BackgroundActor(this,1.8,1), 2); bg.addBackgroundActor(new BackgroundActor(this,1.2,1), 3); bg.addBackgroundActor(new BackgroundActor(this,1.9,1), 3); bg.addBackgroundActor(new BackgroundActor(this,1.3,1), 4); bg.addBackgroundActor(new BackgroundActor(this,2.0,1), 4); // -- test -- /*addActor(new Actor(this, 1.0, 0.8)); addActor(new Actor(this, 2.0, 0.8)); addActor(new Actor(this, 1.24, 0.7)); addActor(new Actor(this, 1.9, 0.8));*/ // -- /test -- } /** * Returns the grid position of the ground. * @return * The grid position of the ground. */ public double getGround() { return ground; } /** * Returns the real position from grid position x. * @param x * The grid position to get the real position from. * @return * The real position calculated from grid position x. */ public int getCoordX(double x) { //return (int) (-getPosition()*getWidth() + ((this.getWidth() / (ytiles * ((double)getWidth()/(double)getHeight()))) * x)); double coord = getWidth() * (x / ytiles); double scroll = getWidth() * (xposition / ytiles); return (int)(coord - scroll + 0.5); } public int getCoordXFixed(double x) { double coord = getWidth() * (x / ytiles) + 0.5; return (int)(coord); } /** * Returns the real position from grid position y. * @param y * The grid position to get the real position from. * @return * The real position calculated from grid position y. */ public int getCoordY(double y) { return (int) ((this.getHeight() / ytiles) * y + 0.5); } /** * Returns the real width from grid width w. * @param w * The grid width to get the real width from. * @return * The real width calculated from grid width w. */ public int getWidth(double w) { //return (int) ((this.getWidth() / (ytiles * ((double)getWidth()/(double)getHeight()))) * w); double coord = (double) getWidth() * (w / ytiles) + 0.5; return (int) coord; } /** * Returns the real height from grid height h. * @param h * The grid height to get the real height from. * @return * The real height calculated from grid width w. */ public int getHeight(double h) { return (int) ((this.getHeight() / ytiles) * h + 0.5); } /** * Returns the x position of the scene (the scroll). * @return * The x position of the scene (the scroll). */ public double getPosition() { return xposition; } /** * Returns the x scroll speed. * @return * The x scroll speed. */ public double getScrollSpeed() { return xscrolltmp<xscrollsteps?xscrolltmp:xscrollsteps; } /** * Adds an actor to the scene. * @param a * The actor to be added to the scene. */ public void addActor(Actor a) { //add(a); childs.add(a); } public HashSet<Actor> getActors(){ return childs; } public boolean getSpaceState(){ return isSpacePressed; } public void resetPlayer() { //xposition = 0.0; xscrollspeed += xscrollinc; //player.x = 0.1; round += 1; bg.reset(); // TODO: fix player position reset bug } public boolean getPaused() { return paused; } public void generateObstacles(){ int obstacleCount = (int) ((int) Math.random() * ((xsize*5.0) - (xsize*4.0)) + (xsize*4.0)); boolean genFlag = false; // check if a x-value has already been created double preX = 0.0; String obstacleName = ""; Random r = new Random(); PrintStream levelGen = null; /*try { levelGen = new PrintStream(new File("res/randLevel.dat")); } catch (FileNotFoundException e) { // TODO Auto-generated catch block System.out.println("Error while generating level"); }*/ double xValArr[] = new double[obstacleCount]; double yValArr[] = new double[obstacleCount]; //System.out.println("Length of x = "+xValArr.length+" "+"obstaclecount = "+obstacleCount); for(int i = 0;i<obstacleCount;i++){ double randomX = 0.5 + ((xsize-2.0) - 0.5) * r.nextDouble(); double randomY = 0.7 + (0.8 - 0.7) * r.nextDouble(); randomX = (double)Math.round(randomX * 100) / 100; randomY = (double)Math.round(randomY*10)/10; xValArr[i] = randomX; yValArr[i] = randomY; } Arrays.sort(xValArr); //System.out.println(Arrays.toString(xValArr)); for(int j=0;j<obstacleCount;j++){ if(j>0){ // value of j has to be bigger than 0 bc. of the comparison if((xValArr[j]-xValArr[j-1])<0.8){ if((xValArr[j]+2.5)>xsize){/* do nothing*/} else{ if(j<xValArr.length/2) xValArr[j]=+1.5; else xValArr[j]=+0.8; } } } double temp = Math.random()*2; int randObstacle = (int) temp; switch(randObstacle){ case 0 : obstacleName = "block"; break; case 1 : obstacleName = "triangle"; break; } //levelGen.println(obstacleName+";"+xValArr[j]+";"+yValArr[j]); addActor(new Block(this, xValArr[j] + getPosition(),yValArr[j])); } } @Override public void paintComponent(Graphics g) { ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); //--update-- if(!paused) { score += 1; if(xposition >= xsize) { lloader.start(); resetPlayer(); } // smooth fast movement so intersections aren't skipped for(xscrolltmp = xscrollspeed; xscrolltmp > 0.000001 && !paused; xscrolltmp -= xscrollsteps) { xposition += getScrollSpeed(); // update the actors (movement) bg.update(); player.update(); for(Actor c: childs) { if(c.getRelX() > xposition - 1 && c.getRelX() < xposition + 2) c.update(); } // check if the player intersects with an obstacle for(Actor c: childs) { if(c.getRelX() > xposition - 1 && c.getRelX() < xposition + 2) if(player.intersects(c)) { //System.out.println(player+" intersects with "+c); c.collide((Player) player); //player. } } } xscrolltmp = 0; } //--/update-- if(((Player)player).dead == true) { paused = true; } //--paint-- g.setColor(Color.white); g.fillRect(0, 0, getWidth(), getHeight()); g.setColor(Color.red); ((Graphics2D)g).drawString("Round: "+round, 10, 20); ((Graphics2D)g).drawString("Speed: "+xscrollspeed, 10, 40); - ((Graphics2D)g).drawString("Score: "+new Double(score) / 10, 10, 40); + ((Graphics2D)g).drawString("Score: "+new Double(score) / 10, 10, 60); bg.paintComponent(g); player.paintComponent(g); for(Actor c: childs) { if(c.getRelX() > xposition - 1 && c.getRelX() < xposition + 2) c.paintComponent(g); } ((Graphics2D) g).drawString("0.0.2-indev", getCoordXFixed(0.85), getCoordY(0.9)); if(paused) { g.setColor(Color.red); ((Graphics2D) g).drawString("GAME OVER", getCoordXFixed(0.45), getCoordY(0.48)); } //--/paint-- } }
true
true
public void paintComponent(Graphics g) { ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); //--update-- if(!paused) { score += 1; if(xposition >= xsize) { lloader.start(); resetPlayer(); } // smooth fast movement so intersections aren't skipped for(xscrolltmp = xscrollspeed; xscrolltmp > 0.000001 && !paused; xscrolltmp -= xscrollsteps) { xposition += getScrollSpeed(); // update the actors (movement) bg.update(); player.update(); for(Actor c: childs) { if(c.getRelX() > xposition - 1 && c.getRelX() < xposition + 2) c.update(); } // check if the player intersects with an obstacle for(Actor c: childs) { if(c.getRelX() > xposition - 1 && c.getRelX() < xposition + 2) if(player.intersects(c)) { //System.out.println(player+" intersects with "+c); c.collide((Player) player); //player. } } } xscrolltmp = 0; } //--/update-- if(((Player)player).dead == true) { paused = true; } //--paint-- g.setColor(Color.white); g.fillRect(0, 0, getWidth(), getHeight()); g.setColor(Color.red); ((Graphics2D)g).drawString("Round: "+round, 10, 20); ((Graphics2D)g).drawString("Speed: "+xscrollspeed, 10, 40); ((Graphics2D)g).drawString("Score: "+new Double(score) / 10, 10, 40); bg.paintComponent(g); player.paintComponent(g); for(Actor c: childs) { if(c.getRelX() > xposition - 1 && c.getRelX() < xposition + 2) c.paintComponent(g); } ((Graphics2D) g).drawString("0.0.2-indev", getCoordXFixed(0.85), getCoordY(0.9)); if(paused) { g.setColor(Color.red); ((Graphics2D) g).drawString("GAME OVER", getCoordXFixed(0.45), getCoordY(0.48)); } //--/paint-- }
public void paintComponent(Graphics g) { ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); //--update-- if(!paused) { score += 1; if(xposition >= xsize) { lloader.start(); resetPlayer(); } // smooth fast movement so intersections aren't skipped for(xscrolltmp = xscrollspeed; xscrolltmp > 0.000001 && !paused; xscrolltmp -= xscrollsteps) { xposition += getScrollSpeed(); // update the actors (movement) bg.update(); player.update(); for(Actor c: childs) { if(c.getRelX() > xposition - 1 && c.getRelX() < xposition + 2) c.update(); } // check if the player intersects with an obstacle for(Actor c: childs) { if(c.getRelX() > xposition - 1 && c.getRelX() < xposition + 2) if(player.intersects(c)) { //System.out.println(player+" intersects with "+c); c.collide((Player) player); //player. } } } xscrolltmp = 0; } //--/update-- if(((Player)player).dead == true) { paused = true; } //--paint-- g.setColor(Color.white); g.fillRect(0, 0, getWidth(), getHeight()); g.setColor(Color.red); ((Graphics2D)g).drawString("Round: "+round, 10, 20); ((Graphics2D)g).drawString("Speed: "+xscrollspeed, 10, 40); ((Graphics2D)g).drawString("Score: "+new Double(score) / 10, 10, 60); bg.paintComponent(g); player.paintComponent(g); for(Actor c: childs) { if(c.getRelX() > xposition - 1 && c.getRelX() < xposition + 2) c.paintComponent(g); } ((Graphics2D) g).drawString("0.0.2-indev", getCoordXFixed(0.85), getCoordY(0.9)); if(paused) { g.setColor(Color.red); ((Graphics2D) g).drawString("GAME OVER", getCoordXFixed(0.45), getCoordY(0.48)); } //--/paint-- }
diff --git a/src/com/android/settings/deviceinfo/Status.java b/src/com/android/settings/deviceinfo/Status.java index ea3ca9764..99a8975e0 100644 --- a/src/com/android/settings/deviceinfo/Status.java +++ b/src/com/android/settings/deviceinfo/Status.java @@ -1,420 +1,426 @@ /* * 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 com.android.settings.deviceinfo; import android.bluetooth.BluetoothAdapter; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.res.Resources; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.BatteryManager; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.SystemClock; import android.os.SystemProperties; import android.preference.Preference; import android.preference.PreferenceActivity; import android.telephony.PhoneNumberUtils; import android.telephony.PhoneStateListener; import android.telephony.ServiceState; import android.telephony.TelephonyManager; import android.text.TextUtils; import com.android.internal.telephony.Phone; import com.android.internal.telephony.PhoneFactory; import com.android.internal.telephony.PhoneStateIntentReceiver; import com.android.internal.telephony.TelephonyProperties; import com.android.settings.R; import java.lang.ref.WeakReference; /** * Display the following information * # Phone Number * # Network * # Roaming * # Device Id (IMEI in GSM and MEID in CDMA) * # Network type * # Signal Strength * # Battery Strength : TODO * # Uptime * # Awake Time * # XMPP/buzz/tickle status : TODO * */ public class Status extends PreferenceActivity { private static final String KEY_WIFI_MAC_ADDRESS = "wifi_mac_address"; private static final String KEY_BT_ADDRESS = "bt_address"; private static final int EVENT_SIGNAL_STRENGTH_CHANGED = 200; private static final int EVENT_SERVICE_STATE_CHANGED = 300; private static final int EVENT_UPDATE_STATS = 500; private TelephonyManager mTelephonyManager; private Phone mPhone = null; private PhoneStateIntentReceiver mPhoneStateReceiver; private Resources mRes; private Preference mSignalStrength; private Preference mUptime; private static String sUnknown; private Preference mBatteryStatus; private Preference mBatteryLevel; private Handler mHandler; private static class MyHandler extends Handler { private WeakReference<Status> mStatus; public MyHandler(Status activity) { mStatus = new WeakReference<Status>(activity); } @Override public void handleMessage(Message msg) { Status status = mStatus.get(); if (status == null) { return; } switch (msg.what) { case EVENT_SIGNAL_STRENGTH_CHANGED: status.updateSignalStrength(); break; case EVENT_SERVICE_STATE_CHANGED: ServiceState serviceState = status.mPhoneStateReceiver.getServiceState(); status.updateServiceState(serviceState); break; case EVENT_UPDATE_STATS: status.updateTimes(); sendEmptyMessageDelayed(EVENT_UPDATE_STATS, 1000); break; } } } private BroadcastReceiver mBatteryInfoReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (Intent.ACTION_BATTERY_CHANGED.equals(action)) { int level = intent.getIntExtra("level", 0); int scale = intent.getIntExtra("scale", 100); mBatteryLevel.setSummary(String.valueOf(level * 100 / scale) + "%"); int plugType = intent.getIntExtra("plugged", 0); int status = intent.getIntExtra("status", BatteryManager.BATTERY_STATUS_UNKNOWN); String statusString; if (status == BatteryManager.BATTERY_STATUS_CHARGING) { statusString = getString(R.string.battery_info_status_charging); if (plugType > 0) { statusString = statusString + " " + getString( (plugType == BatteryManager.BATTERY_PLUGGED_AC) ? R.string.battery_info_status_charging_ac : R.string.battery_info_status_charging_usb); } } else if (status == BatteryManager.BATTERY_STATUS_DISCHARGING) { statusString = getString(R.string.battery_info_status_discharging); } else if (status == BatteryManager.BATTERY_STATUS_NOT_CHARGING) { statusString = getString(R.string.battery_info_status_not_charging); } else if (status == BatteryManager.BATTERY_STATUS_FULL) { statusString = getString(R.string.battery_info_status_full); } else { statusString = getString(R.string.battery_info_status_unknown); } mBatteryStatus.setSummary(statusString); } } }; private PhoneStateListener mPhoneStateListener = new PhoneStateListener() { @Override public void onDataConnectionStateChanged(int state) { updateDataState(); updateNetworkType(); } }; @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); Preference removablePref; mHandler = new MyHandler(this); mTelephonyManager = (TelephonyManager)getSystemService(TELEPHONY_SERVICE); addPreferencesFromResource(R.xml.device_info_status); mBatteryLevel = findPreference("battery_level"); mBatteryStatus = findPreference("battery_status"); mRes = getResources(); if (sUnknown == null) { sUnknown = mRes.getString(R.string.device_info_default); } mPhone = PhoneFactory.getDefaultPhone(); // Note - missing in zaku build, be careful later... mSignalStrength = findPreference("signal_strength"); mUptime = findPreference("up_time"); //NOTE "imei" is the "Device ID" since it represents the IMEI in GSM and the MEID in CDMA if (mPhone.getPhoneName().equals("CDMA")) { setSummaryText("meid_number", mPhone.getMeid()); setSummaryText("min_number", mPhone.getCdmaMin()); setSummaryText("prl_version", mPhone.getCdmaPrlVersion()); // device is not GSM/UMTS, do not display GSM/UMTS features // check Null in case no specified preference in overlay xml removablePref = findPreference("imei"); if (removablePref != null) { getPreferenceScreen().removePreference(removablePref); } removablePref = findPreference("imei_sv"); if (removablePref != null) { getPreferenceScreen().removePreference(removablePref); } } else { setSummaryText("imei", mPhone.getDeviceId()); setSummaryText("imei_sv", ((TelephonyManager) getSystemService(TELEPHONY_SERVICE)) .getDeviceSoftwareVersion()); // device is not CDMA, do not display CDMA features // check Null in case no specified preference in overlay xml removablePref = findPreference("prl_version"); if (removablePref != null) { getPreferenceScreen().removePreference(removablePref); } removablePref = findPreference("meid_number"); if (removablePref != null) { getPreferenceScreen().removePreference(removablePref); } removablePref = findPreference("min_number"); if (removablePref != null) { getPreferenceScreen().removePreference(removablePref); } } - setSummaryText("number", PhoneNumberUtils.formatNumber(mPhone.getLine1Number())); + String rawNumber = mPhone.getLine1Number(); // may be null or empty + String formattedNumber = null; + if (!TextUtils.isEmpty(rawNumber)) { + formattedNumber = PhoneNumberUtils.formatNumber(rawNumber); + } + // If formattedNumber is null or empty, it'll display as "Unknown". + setSummaryText("number", formattedNumber); mPhoneStateReceiver = new PhoneStateIntentReceiver(this, mHandler); mPhoneStateReceiver.notifySignalStrength(EVENT_SIGNAL_STRENGTH_CHANGED); mPhoneStateReceiver.notifyServiceState(EVENT_SERVICE_STATE_CHANGED); setWifiStatus(); setBtStatus(); } @Override protected void onResume() { super.onResume(); mPhoneStateReceiver.registerIntent(); registerReceiver(mBatteryInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); updateSignalStrength(); updateServiceState(mPhone.getServiceState()); updateDataState(); mTelephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_DATA_CONNECTION_STATE); mHandler.sendEmptyMessage(EVENT_UPDATE_STATS); } @Override public void onPause() { super.onPause(); mPhoneStateReceiver.unregisterIntent(); mTelephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_NONE); unregisterReceiver(mBatteryInfoReceiver); mHandler.removeMessages(EVENT_UPDATE_STATS); } /** * @param preference The key for the Preference item * @param property The system property to fetch * @param alt The default value, if the property doesn't exist */ private void setSummary(String preference, String property, String alt) { try { findPreference(preference).setSummary( SystemProperties.get(property, alt)); } catch (RuntimeException e) { } } private void setSummaryText(String preference, String text) { if (TextUtils.isEmpty(text)) { text = sUnknown; } // some preferences may be missing if (findPreference(preference) != null) { findPreference(preference).setSummary(text); } } private void updateNetworkType() { // Whether EDGE, UMTS, etc... setSummary("network_type", TelephonyProperties.PROPERTY_DATA_NETWORK_TYPE, sUnknown); } private void updateDataState() { int state = mTelephonyManager.getDataState(); String display = mRes.getString(R.string.radioInfo_unknown); switch (state) { case TelephonyManager.DATA_CONNECTED: display = mRes.getString(R.string.radioInfo_data_connected); break; case TelephonyManager.DATA_SUSPENDED: display = mRes.getString(R.string.radioInfo_data_suspended); break; case TelephonyManager.DATA_CONNECTING: display = mRes.getString(R.string.radioInfo_data_connecting); break; case TelephonyManager.DATA_DISCONNECTED: display = mRes.getString(R.string.radioInfo_data_disconnected); break; } setSummaryText("data_state", display); } private void updateServiceState(ServiceState serviceState) { int state = serviceState.getState(); String display = mRes.getString(R.string.radioInfo_unknown); switch (state) { case ServiceState.STATE_IN_SERVICE: display = mRes.getString(R.string.radioInfo_service_in); break; case ServiceState.STATE_OUT_OF_SERVICE: case ServiceState.STATE_EMERGENCY_ONLY: display = mRes.getString(R.string.radioInfo_service_out); break; case ServiceState.STATE_POWER_OFF: display = mRes.getString(R.string.radioInfo_service_off); break; } setSummaryText("service_state", display); if (serviceState.getRoaming()) { setSummaryText("roaming_state", mRes.getString(R.string.radioInfo_roaming_in)); } else { setSummaryText("roaming_state", mRes.getString(R.string.radioInfo_roaming_not)); } setSummaryText("operator_name", serviceState.getOperatorAlphaLong()); } void updateSignalStrength() { // TODO PhoneStateIntentReceiver is deprecated and PhoneStateListener // should probably used instead. // not loaded in some versions of the code (e.g., zaku) if (mSignalStrength != null) { int state = mPhoneStateReceiver.getServiceState().getState(); Resources r = getResources(); if ((ServiceState.STATE_OUT_OF_SERVICE == state) || (ServiceState.STATE_POWER_OFF == state)) { mSignalStrength.setSummary("0"); } int signalDbm = mPhoneStateReceiver.getSignalStrengthDbm(); if (-1 == signalDbm) signalDbm = 0; int signalAsu = mPhoneStateReceiver.getSignalStrength(); if (-1 == signalAsu) signalAsu = 0; mSignalStrength.setSummary(String.valueOf(signalDbm) + " " + r.getString(R.string.radioInfo_display_dbm) + " " + String.valueOf(signalAsu) + " " + r.getString(R.string.radioInfo_display_asu)); } } private void setWifiStatus() { WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); Preference wifiMacAddressPref = findPreference(KEY_WIFI_MAC_ADDRESS); String macAddress = wifiInfo == null ? null : wifiInfo.getMacAddress(); wifiMacAddressPref.setSummary(!TextUtils.isEmpty(macAddress) ? macAddress : getString(R.string.status_unavailable)); } private void setBtStatus() { BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter(); Preference btAddressPref = findPreference(KEY_BT_ADDRESS); if (bluetooth == null) { // device not BT capable getPreferenceScreen().removePreference(btAddressPref); } else { String address = bluetooth.isEnabled() ? bluetooth.getAddress() : null; btAddressPref.setSummary(!TextUtils.isEmpty(address) ? address : getString(R.string.status_unavailable)); } } void updateTimes() { long at = SystemClock.uptimeMillis() / 1000; long ut = SystemClock.elapsedRealtime() / 1000; if (ut == 0) { ut = 1; } mUptime.setSummary(convert(ut)); } private String pad(int n) { if (n >= 10) { return String.valueOf(n); } else { return "0" + String.valueOf(n); } } private String convert(long t) { int s = (int)(t % 60); int m = (int)((t / 60) % 60); int h = (int)((t / 3600)); return h + ":" + pad(m) + ":" + pad(s); } }
true
true
protected void onCreate(Bundle icicle) { super.onCreate(icicle); Preference removablePref; mHandler = new MyHandler(this); mTelephonyManager = (TelephonyManager)getSystemService(TELEPHONY_SERVICE); addPreferencesFromResource(R.xml.device_info_status); mBatteryLevel = findPreference("battery_level"); mBatteryStatus = findPreference("battery_status"); mRes = getResources(); if (sUnknown == null) { sUnknown = mRes.getString(R.string.device_info_default); } mPhone = PhoneFactory.getDefaultPhone(); // Note - missing in zaku build, be careful later... mSignalStrength = findPreference("signal_strength"); mUptime = findPreference("up_time"); //NOTE "imei" is the "Device ID" since it represents the IMEI in GSM and the MEID in CDMA if (mPhone.getPhoneName().equals("CDMA")) { setSummaryText("meid_number", mPhone.getMeid()); setSummaryText("min_number", mPhone.getCdmaMin()); setSummaryText("prl_version", mPhone.getCdmaPrlVersion()); // device is not GSM/UMTS, do not display GSM/UMTS features // check Null in case no specified preference in overlay xml removablePref = findPreference("imei"); if (removablePref != null) { getPreferenceScreen().removePreference(removablePref); } removablePref = findPreference("imei_sv"); if (removablePref != null) { getPreferenceScreen().removePreference(removablePref); } } else { setSummaryText("imei", mPhone.getDeviceId()); setSummaryText("imei_sv", ((TelephonyManager) getSystemService(TELEPHONY_SERVICE)) .getDeviceSoftwareVersion()); // device is not CDMA, do not display CDMA features // check Null in case no specified preference in overlay xml removablePref = findPreference("prl_version"); if (removablePref != null) { getPreferenceScreen().removePreference(removablePref); } removablePref = findPreference("meid_number"); if (removablePref != null) { getPreferenceScreen().removePreference(removablePref); } removablePref = findPreference("min_number"); if (removablePref != null) { getPreferenceScreen().removePreference(removablePref); } } setSummaryText("number", PhoneNumberUtils.formatNumber(mPhone.getLine1Number())); mPhoneStateReceiver = new PhoneStateIntentReceiver(this, mHandler); mPhoneStateReceiver.notifySignalStrength(EVENT_SIGNAL_STRENGTH_CHANGED); mPhoneStateReceiver.notifyServiceState(EVENT_SERVICE_STATE_CHANGED); setWifiStatus(); setBtStatus(); }
protected void onCreate(Bundle icicle) { super.onCreate(icicle); Preference removablePref; mHandler = new MyHandler(this); mTelephonyManager = (TelephonyManager)getSystemService(TELEPHONY_SERVICE); addPreferencesFromResource(R.xml.device_info_status); mBatteryLevel = findPreference("battery_level"); mBatteryStatus = findPreference("battery_status"); mRes = getResources(); if (sUnknown == null) { sUnknown = mRes.getString(R.string.device_info_default); } mPhone = PhoneFactory.getDefaultPhone(); // Note - missing in zaku build, be careful later... mSignalStrength = findPreference("signal_strength"); mUptime = findPreference("up_time"); //NOTE "imei" is the "Device ID" since it represents the IMEI in GSM and the MEID in CDMA if (mPhone.getPhoneName().equals("CDMA")) { setSummaryText("meid_number", mPhone.getMeid()); setSummaryText("min_number", mPhone.getCdmaMin()); setSummaryText("prl_version", mPhone.getCdmaPrlVersion()); // device is not GSM/UMTS, do not display GSM/UMTS features // check Null in case no specified preference in overlay xml removablePref = findPreference("imei"); if (removablePref != null) { getPreferenceScreen().removePreference(removablePref); } removablePref = findPreference("imei_sv"); if (removablePref != null) { getPreferenceScreen().removePreference(removablePref); } } else { setSummaryText("imei", mPhone.getDeviceId()); setSummaryText("imei_sv", ((TelephonyManager) getSystemService(TELEPHONY_SERVICE)) .getDeviceSoftwareVersion()); // device is not CDMA, do not display CDMA features // check Null in case no specified preference in overlay xml removablePref = findPreference("prl_version"); if (removablePref != null) { getPreferenceScreen().removePreference(removablePref); } removablePref = findPreference("meid_number"); if (removablePref != null) { getPreferenceScreen().removePreference(removablePref); } removablePref = findPreference("min_number"); if (removablePref != null) { getPreferenceScreen().removePreference(removablePref); } } String rawNumber = mPhone.getLine1Number(); // may be null or empty String formattedNumber = null; if (!TextUtils.isEmpty(rawNumber)) { formattedNumber = PhoneNumberUtils.formatNumber(rawNumber); } // If formattedNumber is null or empty, it'll display as "Unknown". setSummaryText("number", formattedNumber); mPhoneStateReceiver = new PhoneStateIntentReceiver(this, mHandler); mPhoneStateReceiver.notifySignalStrength(EVENT_SIGNAL_STRENGTH_CHANGED); mPhoneStateReceiver.notifyServiceState(EVENT_SERVICE_STATE_CHANGED); setWifiStatus(); setBtStatus(); }
diff --git a/source/net/sourceforge/fullsync/launcher/Launcher.java b/source/net/sourceforge/fullsync/launcher/Launcher.java index b684000..83491b0 100644 --- a/source/net/sourceforge/fullsync/launcher/Launcher.java +++ b/source/net/sourceforge/fullsync/launcher/Launcher.java @@ -1,90 +1,90 @@ /* * 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. * * For information about the authors of this project Have a look * at the AUTHORS file in the root of this project. */ package net.sourceforge.fullsync.launcher; import java.io.File; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.jar.Attributes; import java.util.jar.JarFile; import java.util.jar.Manifest; public class Launcher { /** * setup the platform specific *sigh* classpath for SWT and load the application. * @param args command line arguments */ public static void main(final String[] args) { // TODO: redirect stdout && stderr here! try { String arch = "x86"; String osName = System.getProperty("os.name").toLowerCase(); String os = "unknown"; if (-1 != System.getProperty("os.arch").indexOf("64")) { arch = "x86_64"; } if (-1 != osName.indexOf("linux")) { os = "gtk-linux"; } else if (-1 != osName.indexOf("windows")) { - os = "win32"; + os = "win32-win32"; } else if (-1 != osName.indexOf("mac")) { os = "cocoa-macosx"; } String dot = new File(".").getAbsoluteFile().toURI().toString(); ArrayList<URL> jars = new ArrayList<URL>(); System.out.println("launching FullSync... OS=" + os + "; ARCH=" + arch + "; DOT=" + dot); // add correct SWT implementation to the class-loader jars.add(new URL(dot + "/lib/swt-" + os + "-" + arch + ".jar")); // read out the "fake" class-path set on the launcher jar File launcher = new File("./launcher.jar"); JarFile jf = new JarFile(launcher); Manifest manifest = jf.getManifest(); Attributes attributes = manifest.getMainAttributes(); String fsClassPath = attributes.getValue("FullSync-Class-Path"); for (String s : fsClassPath.split("\\.jar\\s")) { jars.add(new URL(dot + "/" + s.trim() + ".jar")); } jf.close(); URL[] urls = new URL[jars.size()]; System.arraycopy(jars.toArray(), 0, urls, 0, urls.length); // instantiate an URL class-loader with the constructed class-path and load the real main class URLClassLoader cl = new URLClassLoader(urls, Launcher.class.getClassLoader()); Class<?> cls = cl.loadClass("net.sourceforge.fullsync.cli.Main"); Method main = cls.getDeclaredMethod("main", new Class<?>[] { String[].class }); Thread.currentThread().setContextClassLoader(cl); // call the main method using reflection so that there is no static reference to it main.invoke(null, new Object[] { args }); } catch (Exception e) { // TODO: tell the user e.printStackTrace(); } } }
true
true
public static void main(final String[] args) { // TODO: redirect stdout && stderr here! try { String arch = "x86"; String osName = System.getProperty("os.name").toLowerCase(); String os = "unknown"; if (-1 != System.getProperty("os.arch").indexOf("64")) { arch = "x86_64"; } if (-1 != osName.indexOf("linux")) { os = "gtk-linux"; } else if (-1 != osName.indexOf("windows")) { os = "win32"; } else if (-1 != osName.indexOf("mac")) { os = "cocoa-macosx"; } String dot = new File(".").getAbsoluteFile().toURI().toString(); ArrayList<URL> jars = new ArrayList<URL>(); System.out.println("launching FullSync... OS=" + os + "; ARCH=" + arch + "; DOT=" + dot); // add correct SWT implementation to the class-loader jars.add(new URL(dot + "/lib/swt-" + os + "-" + arch + ".jar")); // read out the "fake" class-path set on the launcher jar File launcher = new File("./launcher.jar"); JarFile jf = new JarFile(launcher); Manifest manifest = jf.getManifest(); Attributes attributes = manifest.getMainAttributes(); String fsClassPath = attributes.getValue("FullSync-Class-Path"); for (String s : fsClassPath.split("\\.jar\\s")) { jars.add(new URL(dot + "/" + s.trim() + ".jar")); } jf.close(); URL[] urls = new URL[jars.size()]; System.arraycopy(jars.toArray(), 0, urls, 0, urls.length); // instantiate an URL class-loader with the constructed class-path and load the real main class URLClassLoader cl = new URLClassLoader(urls, Launcher.class.getClassLoader()); Class<?> cls = cl.loadClass("net.sourceforge.fullsync.cli.Main"); Method main = cls.getDeclaredMethod("main", new Class<?>[] { String[].class }); Thread.currentThread().setContextClassLoader(cl); // call the main method using reflection so that there is no static reference to it main.invoke(null, new Object[] { args }); } catch (Exception e) { // TODO: tell the user e.printStackTrace(); } }
public static void main(final String[] args) { // TODO: redirect stdout && stderr here! try { String arch = "x86"; String osName = System.getProperty("os.name").toLowerCase(); String os = "unknown"; if (-1 != System.getProperty("os.arch").indexOf("64")) { arch = "x86_64"; } if (-1 != osName.indexOf("linux")) { os = "gtk-linux"; } else if (-1 != osName.indexOf("windows")) { os = "win32-win32"; } else if (-1 != osName.indexOf("mac")) { os = "cocoa-macosx"; } String dot = new File(".").getAbsoluteFile().toURI().toString(); ArrayList<URL> jars = new ArrayList<URL>(); System.out.println("launching FullSync... OS=" + os + "; ARCH=" + arch + "; DOT=" + dot); // add correct SWT implementation to the class-loader jars.add(new URL(dot + "/lib/swt-" + os + "-" + arch + ".jar")); // read out the "fake" class-path set on the launcher jar File launcher = new File("./launcher.jar"); JarFile jf = new JarFile(launcher); Manifest manifest = jf.getManifest(); Attributes attributes = manifest.getMainAttributes(); String fsClassPath = attributes.getValue("FullSync-Class-Path"); for (String s : fsClassPath.split("\\.jar\\s")) { jars.add(new URL(dot + "/" + s.trim() + ".jar")); } jf.close(); URL[] urls = new URL[jars.size()]; System.arraycopy(jars.toArray(), 0, urls, 0, urls.length); // instantiate an URL class-loader with the constructed class-path and load the real main class URLClassLoader cl = new URLClassLoader(urls, Launcher.class.getClassLoader()); Class<?> cls = cl.loadClass("net.sourceforge.fullsync.cli.Main"); Method main = cls.getDeclaredMethod("main", new Class<?>[] { String[].class }); Thread.currentThread().setContextClassLoader(cl); // call the main method using reflection so that there is no static reference to it main.invoke(null, new Object[] { args }); } catch (Exception e) { // TODO: tell the user e.printStackTrace(); } }
diff --git a/org.eclipse.scout.rt.server/src/org/eclipse/scout/rt/server/servlet/filter/TomcatSecurityFilter.java b/org.eclipse.scout.rt.server/src/org/eclipse/scout/rt/server/servlet/filter/TomcatSecurityFilter.java index 14832cfdb7..36c67a9f8c 100644 --- a/org.eclipse.scout.rt.server/src/org/eclipse/scout/rt/server/servlet/filter/TomcatSecurityFilter.java +++ b/org.eclipse.scout.rt.server/src/org/eclipse/scout/rt/server/servlet/filter/TomcatSecurityFilter.java @@ -1,124 +1,125 @@ /******************************************************************************* * 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.server.servlet.filter; import java.io.IOException; import java.security.AccessController; import java.security.Principal; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import javax.security.auth.Subject; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.eclipse.scout.http.servletfilter.FilterConfigInjection; import org.eclipse.scout.rt.shared.services.common.security.SimplePrincipal; /** * In Tomcat, the Subject is lost after authentication and is not passed to the servlet. * Only the remoteUser and the userPrincipal are available.<br> * This servlet-filter ensures that each request is executed in a secure context. * This filter doesn't authenticate the caller, this is the responsibility of Tomcat/Container<br> * <br> * For Tomcat 6, following steps are required to achieve sso with Windows AD:<br> * <li>copy spnego.jar to tomcat\lib</li> <br> * <li>copy krb5.conf and login.conf to tomcat-home</li><br> * <li>adjust paramters in login.conf</li><br> * <li>adjust paramters in conf\web.xml</li><br> */ public class TomcatSecurityFilter implements Filter { private FilterConfigInjection m_injection; @Override public void init(FilterConfig config0) throws ServletException { m_injection = new FilterConfigInjection(config0, getClass()); } @Override public void destroy() { m_injection = null; } @Override public void doFilter(ServletRequest in, ServletResponse out, final FilterChain chain) throws IOException, ServletException { FilterConfigInjection.FilterConfig config = m_injection.getConfig(in); if (!config.isActive()) { chain.doFilter(in, out); return; } // final HttpServletRequest req = (HttpServletRequest) in; final HttpServletResponse res = (HttpServletResponse) out; // touch the session so it is effectively used req.getSession(); // check if we are already authenticated Subject subject = Subject.getSubject(AccessController.getContext()); if (subject == null) { Principal principal = req.getUserPrincipal(); if (principal == null || principal.getName() == null || principal.getName().trim().length() == 0) { principal = null; String name = req.getRemoteUser(); if (name != null && name.trim().length() > 0) { principal = new SimplePrincipal(name); } } if (principal != null) { subject = new Subject(); subject.getPrincipals().add(principal); } } // run in subject if (Subject.getSubject(AccessController.getContext()) != null) { doFilterInternal(req, res, chain); } else { try { Subject.doAs( subject, new PrivilegedExceptionAction<Object>() { + @Override public Object run() throws Exception { HttpServletRequest secureReq = req; if (!(secureReq instanceof SecureHttpServletRequestWrapper)) { Principal principal = Subject.getSubject(AccessController.getContext()).getPrincipals().iterator().next(); - secureReq = new SecureHttpServletRequestWrapper(req, principal, null); + secureReq = new SecureHttpServletRequestWrapper(req, principal, "BASIC_AUTH"); } doFilterInternal(secureReq, res, chain); return null; } } ); } catch (PrivilegedActionException e) { Throwable t = e.getCause(); if (t instanceof IOException) { throw (IOException) t; } else if (t instanceof ServletException) { throw (ServletException) t; } else { throw new ServletException(t); } } } } private void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException { chain.doFilter(req, res); } }
false
true
public void doFilter(ServletRequest in, ServletResponse out, final FilterChain chain) throws IOException, ServletException { FilterConfigInjection.FilterConfig config = m_injection.getConfig(in); if (!config.isActive()) { chain.doFilter(in, out); return; } // final HttpServletRequest req = (HttpServletRequest) in; final HttpServletResponse res = (HttpServletResponse) out; // touch the session so it is effectively used req.getSession(); // check if we are already authenticated Subject subject = Subject.getSubject(AccessController.getContext()); if (subject == null) { Principal principal = req.getUserPrincipal(); if (principal == null || principal.getName() == null || principal.getName().trim().length() == 0) { principal = null; String name = req.getRemoteUser(); if (name != null && name.trim().length() > 0) { principal = new SimplePrincipal(name); } } if (principal != null) { subject = new Subject(); subject.getPrincipals().add(principal); } } // run in subject if (Subject.getSubject(AccessController.getContext()) != null) { doFilterInternal(req, res, chain); } else { try { Subject.doAs( subject, new PrivilegedExceptionAction<Object>() { public Object run() throws Exception { HttpServletRequest secureReq = req; if (!(secureReq instanceof SecureHttpServletRequestWrapper)) { Principal principal = Subject.getSubject(AccessController.getContext()).getPrincipals().iterator().next(); secureReq = new SecureHttpServletRequestWrapper(req, principal, null); } doFilterInternal(secureReq, res, chain); return null; } } ); } catch (PrivilegedActionException e) { Throwable t = e.getCause(); if (t instanceof IOException) { throw (IOException) t; } else if (t instanceof ServletException) { throw (ServletException) t; } else { throw new ServletException(t); } } } }
public void doFilter(ServletRequest in, ServletResponse out, final FilterChain chain) throws IOException, ServletException { FilterConfigInjection.FilterConfig config = m_injection.getConfig(in); if (!config.isActive()) { chain.doFilter(in, out); return; } // final HttpServletRequest req = (HttpServletRequest) in; final HttpServletResponse res = (HttpServletResponse) out; // touch the session so it is effectively used req.getSession(); // check if we are already authenticated Subject subject = Subject.getSubject(AccessController.getContext()); if (subject == null) { Principal principal = req.getUserPrincipal(); if (principal == null || principal.getName() == null || principal.getName().trim().length() == 0) { principal = null; String name = req.getRemoteUser(); if (name != null && name.trim().length() > 0) { principal = new SimplePrincipal(name); } } if (principal != null) { subject = new Subject(); subject.getPrincipals().add(principal); } } // run in subject if (Subject.getSubject(AccessController.getContext()) != null) { doFilterInternal(req, res, chain); } else { try { Subject.doAs( subject, new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { HttpServletRequest secureReq = req; if (!(secureReq instanceof SecureHttpServletRequestWrapper)) { Principal principal = Subject.getSubject(AccessController.getContext()).getPrincipals().iterator().next(); secureReq = new SecureHttpServletRequestWrapper(req, principal, "BASIC_AUTH"); } doFilterInternal(secureReq, res, chain); return null; } } ); } catch (PrivilegedActionException e) { Throwable t = e.getCause(); if (t instanceof IOException) { throw (IOException) t; } else if (t instanceof ServletException) { throw (ServletException) t; } else { throw new ServletException(t); } } } }